security.lib.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This is the security library for Chamilo.
  5. *
  6. * This library is based on recommendations found in the PHP5 Certification
  7. * Guide published at PHP|Architect, and other recommendations found on
  8. * http://www.phpsec.org/
  9. * The principles here are that all data is tainted (most scripts of Chamilo are
  10. * open to the public or at least to a certain public that could be malicious
  11. * under specific circumstances). We use the white list approach, where as we
  12. * consider that data can only be used in the database or in a file if it has
  13. * been filtered.
  14. *
  15. * For session fixation, use ...
  16. * For session hijacking, use get_ua() and check_ua()
  17. * For Cross-Site Request Forgeries, use get_token() and check_tocken()
  18. * For basic filtering, use filter()
  19. * For files inclusions (using dynamic paths) use check_rel_path() and check_abs_path()
  20. *
  21. * @package chamilo.library
  22. * @author Yannick Warnier <ywarnier@beeznest.org>
  23. */
  24. /**
  25. * Security class
  26. *
  27. * Include/require it in your code and call Security::function()
  28. * to use its functionalities.
  29. *
  30. * This class can also be used as a container for filtered data, by creating
  31. * a new Security object and using $secure->filter($new_var,[more options])
  32. * and then using $secure->clean['var'] as a filtered equivalent, although
  33. * this is *not* mandatory at all.
  34. */
  35. class Security
  36. {
  37. public static $clean = array();
  38. /**
  39. * Checks if the absolute path (directory) given is really under the
  40. * checker path (directory)
  41. * @param string Absolute path to be checked (with trailing slash)
  42. * @param string Checker path under which the path should be (absolute path, with trailing slash, get it from api_get_path(SYS_COURSE_PATH))
  43. * @return bool True if the path is under the checker, false otherwise
  44. */
  45. public static function check_abs_path($abs_path, $checker_path)
  46. {
  47. if (empty($checker_path)) {
  48. return false;
  49. } // The checker path must be set.
  50. $true_path = str_replace("\\", '/', realpath($abs_path));
  51. $found = strpos($true_path.'/', $checker_path);
  52. if ($found === 0) {
  53. return true;
  54. } else {
  55. // Code specific to Windows and case-insensitive behaviour
  56. if (api_is_windows_os()) {
  57. $found = stripos($true_path.'/', $checker_path);
  58. if ($found === 0) {
  59. return true;
  60. }
  61. }
  62. // Code specific to courses directory stored on other disk.
  63. /*
  64. $checker_path = str_replace(api_get_path(SYS_COURSE_PATH), $_configuration['symbolic_course_folder_abs'], $checker_path);
  65. $found = strpos($true_path.'/', $checker_path);
  66. if ($found === 0) {
  67. return true;
  68. }*/
  69. }
  70. return false;
  71. }
  72. /**
  73. * Checks if the relative path (directory) given is really under the
  74. * checker path (directory)
  75. * @param string $rel_path Relative path to be checked (relative to the current directory) (with trailing slash)
  76. * @param string $checker_path Checker path under which the path should be (absolute path, with trailing slash, get it from api_get_path(SYS_COURSE_PATH))
  77. *
  78. * @return bool True if the path is under the checker, false otherwise
  79. */
  80. public static function check_rel_path($rel_path, $checker_path)
  81. {
  82. if (empty($checker_path)) {
  83. return false;
  84. } // The checker path must be set.
  85. $current_path = getcwd(); // No trailing slash.
  86. if (substr($rel_path, -1, 1) != '/') {
  87. $rel_path = '/'.$rel_path;
  88. }
  89. $abs_path = $current_path.$rel_path;
  90. $true_path = str_replace("\\", '/', realpath($abs_path));
  91. $found = strpos($true_path.'/', $checker_path);
  92. if ($found === 0) {
  93. return true;
  94. }
  95. return false;
  96. }
  97. /**
  98. * Filters dangerous filenames (*.php[.]?* and .htaccess) and returns it in
  99. * a non-executable form (for PHP and htaccess, this is still vulnerable to
  100. * other languages' files extensions)
  101. * @param string Unfiltered filename
  102. * @param string Filtered filename
  103. */
  104. public static function filter_filename($filename)
  105. {
  106. return FileManager::disable_dangerous_file($filename);
  107. }
  108. /**
  109. * This function checks that the token generated in get_token() has been kept (prevents
  110. * Cross-Site Request Forgeries attacks)
  111. * @param string $request_type The array in which to get the token ('get' or 'post')
  112. *
  113. * @return bool True if it's the right token, false otherwise
  114. *
  115. */
  116. public static function check_token($request_type = 'post')
  117. {
  118. $currentSessionToken = Security::getCurrentToken();
  119. switch ($request_type) {
  120. case 'request':
  121. if (isset($currentSessionToken) && isset($_REQUEST['sec_token']) && $currentSessionToken === $_REQUEST['sec_token']) {
  122. return true;
  123. }
  124. return false;
  125. case 'get':
  126. if (isset($currentSessionToken) && isset($_GET['sec_token']) && $currentSessionToken === $_GET['sec_token']) {
  127. return true;
  128. }
  129. return false;
  130. case 'post':
  131. if (isset($currentSessionToken) && isset($_POST['sec_token']) && $currentSessionToken === $_POST['sec_token']) {
  132. return true;
  133. }
  134. return false;
  135. default:
  136. if (isset($currentSessionToken) && isset($request_type) && $currentSessionToken === $request_type) {
  137. return true;
  138. }
  139. return false;
  140. }
  141. return false; // Just in case, don't let anything slip.
  142. }
  143. /**
  144. * Checks the user agent of the client as recorder by get_ua() to prevent
  145. * most session hijacking attacks.
  146. * @return bool True if the user agent is the same, false otherwise
  147. */
  148. public static function check_ua()
  149. {
  150. if (isset($_SESSION['sec_ua']) and $_SESSION['sec_ua'] === $_SERVER['HTTP_USER_AGENT'].$_SESSION['sec_ua_seed']) {
  151. return true;
  152. }
  153. return false;
  154. }
  155. /**
  156. * Clear the security token from the session
  157. * @return void
  158. */
  159. public static function clear_token()
  160. {
  161. $_SESSION['sec_token'] = null;
  162. unset($_SESSION['sec_token']);
  163. }
  164. /**
  165. * This function sets a random token to be included in a form as a hidden field
  166. * and saves it into the user's session. Returns an HTML form element
  167. * This later prevents Cross-Site Request Forgeries by checking that the user is really
  168. * the one that sent this form in knowingly (this form hasn't been generated from
  169. * another website visited by the user at the same time).
  170. * Check the token with check_token()
  171. * @return string Hidden-type input ready to insert into a form
  172. */
  173. public static function get_HTML_token()
  174. {
  175. $token = md5(uniqid(rand(), true));
  176. $string = '<input type="hidden" name="sec_token" value="'.$token.'" />';
  177. $_SESSION['sec_token'] = $token;
  178. return $string;
  179. }
  180. /**
  181. * This function sets a random token to be included in a form as a hidden field
  182. * and saves it into the user's session.
  183. * This later prevents Cross-Site Request Forgeries by checking that the user is really
  184. * the one that sent this form in knowingly (this form hasn't been generated from
  185. * another website visited by the user at the same time).
  186. * Check the token with check_token()
  187. * @return string Token
  188. */
  189. public static function get_token()
  190. {
  191. $token = md5(uniqid(rand(), true));
  192. $_SESSION['sec_token'] = $token;
  193. return $token;
  194. }
  195. /**
  196. * Get current token
  197. * @return null
  198. */
  199. public static function getCurrentToken()
  200. {
  201. return isset($_SESSION['sec_token']) ? $_SESSION['sec_token'] : null;
  202. }
  203. /**
  204. * Gets the user agent in the session to later check it with check_ua() to prevent
  205. * most cases of session hijacking.
  206. * @return void
  207. */
  208. public static function get_ua()
  209. {
  210. $_SESSION['sec_ua_seed'] = uniqid(rand(), true);
  211. $_SESSION['sec_ua'] = $_SERVER['HTTP_USER_AGENT'].$_SESSION['sec_ua_seed'];
  212. }
  213. /**
  214. * This function returns a variable from the clean array. If the variable doesn't exist,
  215. * it returns null
  216. * @param string Variable name
  217. * @return mixed Variable or NULL on error
  218. */
  219. public static function get($varname)
  220. {
  221. if (isset(self::$clean[$varname])) {
  222. return self::$clean[$varname];
  223. }
  224. return null;
  225. }
  226. /**
  227. * This function tackles the XSS injections.
  228. * Filtering for XSS is very easily done by using the htmlentities() function.
  229. * This kind of filtering prevents JavaScript snippets to be understood as such.
  230. * @param mixed The variable to filter for XSS, this params can be a string or an array (example : array(x,y))
  231. * @param integer The user status,constant allowed (STUDENT, COURSEMANAGER, ANONYMOUS, COURSEMANAGERLOWSECURITY)
  232. * @return mixed Filtered string or array
  233. */
  234. public static function remove_XSS($var, $user_status = ANONYMOUS, $filter_terms = false)
  235. {
  236. return $var;
  237. // @todo improvement - HTMLpurifier eats server memory ~ 3M
  238. // return $var;
  239. if ($filter_terms) {
  240. $var = self::filter_terms($var);
  241. }
  242. if ($user_status == COURSEMANAGERLOWSECURITY) {
  243. return $var; // No filtering.
  244. }
  245. static $purifier = array();
  246. if (!isset($purifier[$user_status])) {
  247. global $app;
  248. $cache_dir = $app['htmlpurifier.serializer'];
  249. $config = HTMLPurifier_Config::createDefault();
  250. //$config->set('Cache.DefinitionImpl', null); // Enable this line for testing purposes, for turning off caching. Don't forget to disable this line later!
  251. $config->set('Cache.SerializerPath', $cache_dir);
  252. $config->set('Core.Encoding', api_get_system_encoding());
  253. $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
  254. $config->set('HTML.MaxImgLength', '2560');
  255. $config->set('HTML.TidyLevel', 'light');
  256. $config->set('Core.ConvertDocumentToFragment', false);
  257. $config->set('Core.RemoveProcessingInstructions', true);
  258. if (api_get_setting('enable_iframe_inclusion') == 'true') {
  259. $config->set('Filter.Custom', array(new HTMLPurifier_Filter_AllowIframes()));
  260. }
  261. //Shows _target attribute in anchors
  262. $config->set('Attr.AllowedFrameTargets', array('_blank', '_top', '_self', '_parent'));
  263. if ($user_status == STUDENT) {
  264. global $allowed_html_student;
  265. $config->set('HTML.SafeEmbed', true);
  266. $config->set('HTML.SafeObject', true);
  267. $config->set('Filter.YouTube', true);
  268. $config->set('HTML.FlashAllowFullScreen', true);
  269. $config->set('HTML.Allowed', $allowed_html_student);
  270. } elseif ($user_status == COURSEMANAGER) {
  271. global $allowed_html_teacher;
  272. $config->set('HTML.SafeEmbed', true);
  273. $config->set('HTML.SafeObject', true);
  274. $config->set('Filter.YouTube', true);
  275. $config->set('HTML.FlashAllowFullScreen', true);
  276. $config->set('HTML.Allowed', $allowed_html_teacher);
  277. } else {
  278. global $allowed_html_anonymous;
  279. $config->set('HTML.Allowed', $allowed_html_anonymous);
  280. }
  281. $config->set(
  282. 'Attr.EnableID',
  283. true
  284. ); // We need it for example for the flv player (ids of surrounding div-tags have to be preserved).
  285. $config->set('CSS.AllowImportant', true);
  286. $config->set('CSS.AllowTricky', true); // We need for the flv player the css definition display: none;
  287. $config->set('CSS.Proprietary', true);
  288. $purifier[$user_status] = new HTMLPurifier($config);
  289. }
  290. if (is_array($var)) {
  291. return $purifier[$user_status]->purifyArray($var);
  292. } else {
  293. return $purifier[$user_status]->purify($var);
  294. }
  295. }
  296. /**
  297. *
  298. * Filter content
  299. * @param string content to be filter
  300. * @return string
  301. */
  302. static function filter_terms($text)
  303. {
  304. static $bad_terms = array();
  305. if (empty($bad_terms)) {
  306. $list = api_get_setting('filter_terms');
  307. $list = explode("\n", $list);
  308. $list = array_filter($list);
  309. if (!empty($list)) {
  310. foreach ($list as $term) {
  311. $term = str_replace(array("\r\n", "\r", "\n", "\t"), '', $term);
  312. $html_entities_value = api_htmlentities($term, ENT_QUOTES, api_get_system_encoding());
  313. $bad_terms[] = $term;
  314. if ($term != $html_entities_value) {
  315. $bad_terms[] = $html_entities_value;
  316. }
  317. }
  318. $bad_terms = array_filter($bad_terms);
  319. }
  320. }
  321. $replace = '***';
  322. if (!empty($bad_terms)) {
  323. //Fast way
  324. $new_text = str_ireplace($bad_terms, $replace, $text, $count);
  325. //We need statistics
  326. /*
  327. if (strlen($new_text) != strlen($text)) {
  328. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_FILTERED_TERMS);
  329. $attributes = array();
  330. $attributes['user_id'] =
  331. $attributes['course_id'] =
  332. $attributes['session_id'] =
  333. $attributes['tool_id'] =
  334. $attributes['term'] =
  335. $attributes['created_at'] = api_get_utc_datetime();
  336. $sql = Database::insert($table, $attributes);
  337. }
  338. */
  339. $text = $new_text;
  340. }
  341. return $text;
  342. }
  343. /**
  344. * This method provides specific protection (against XSS and other kinds of attacks) for static images (icons) used by the system.
  345. * Image paths are supposed to be given by programmers - people who know what they do, anyway, this method encourages
  346. * a safe practice for generating icon paths, without using heavy solutions based on HTMLPurifier for example.
  347. * @param string $img_path The input path of the image, it could be relative or absolute URL.
  348. * @return string Returns sanitized image path or an empty string when the image path is not secure.
  349. * @author Ivan Tcholakov, March 2011
  350. */
  351. public static function filter_img_path($image_path)
  352. {
  353. static $allowed_extensions = array('png', 'gif', 'jpg', 'jpeg');
  354. $image_path = htmlspecialchars(trim($image_path)); // No html code is allowed.
  355. // We allow static images only, query strings are forbidden.
  356. if (strpos($image_path, '?') !== false) {
  357. return '';
  358. }
  359. if (($pos = strpos($image_path, ':')) !== false) {
  360. // Protocol has been specified, let's check it.
  361. if (stripos($image_path, 'javascript:') !== false) {
  362. // Javascript everywhere in the path is not allowed.
  363. return '';
  364. }
  365. // We allow only http: and https: protocols for now.
  366. //if (!preg_match('/^https?:\/\//i', $image_path)) {
  367. // return '';
  368. //}
  369. if (stripos($image_path, 'http://') !== 0 && stripos($image_path, 'https://') !== 0) {
  370. return '';
  371. }
  372. }
  373. // We allow file extensions for images only.
  374. //if (!preg_match('/.+\.(png|gif|jpg|jpeg)$/i', $image_path)) {
  375. // return '';
  376. //}
  377. if (($pos = strrpos($image_path, '.')) !== false) {
  378. if (!in_array(strtolower(substr($image_path, $pos + 1)), $allowed_extensions)) {
  379. return '';
  380. }
  381. } else {
  382. return '';
  383. }
  384. return $image_path;
  385. }
  386. }