security.lib.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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. // The checker path must be set.
  48. if (empty($checker_path)) {
  49. return false;
  50. }
  51. $true_path = str_replace("\\", '/', realpath($abs_path));
  52. $checker_path = str_replace("\\", '/', realpath($checker_path));
  53. $found = strpos($true_path.'/', $checker_path);
  54. if ($found === 0) {
  55. return true;
  56. } else {
  57. // Code specific to Windows and case-insensitive behaviour
  58. if (api_is_windows_os()) {
  59. $found = stripos($true_path.'/', $checker_path);
  60. if ($found === 0) {
  61. return true;
  62. }
  63. }
  64. }
  65. return false;
  66. }
  67. /**
  68. * Checks if the relative path (directory) given is really under the
  69. * checker path (directory)
  70. * @param string Relative path to be checked (relative to the current directory) (with trailing slash)
  71. * @param string Checker path under which the path should be (absolute path, with trailing slash, get it from api_get_path(SYS_COURSE_PATH))
  72. * @return bool True if the path is under the checker, false otherwise
  73. */
  74. public static function check_rel_path($rel_path, $checker_path)
  75. {
  76. // The checker path must be set.
  77. if (empty($checker_path)) {
  78. return false;
  79. }
  80. $current_path = getcwd(); // No trailing slash.
  81. if (substr($rel_path, -1, 1) != '/') {
  82. $rel_path = '/'.$rel_path;
  83. }
  84. $abs_path = $current_path.$rel_path;
  85. $true_path=str_replace("\\", '/', realpath($abs_path));
  86. $found = strpos($true_path.'/', $checker_path);
  87. if ($found === 0) {
  88. return true;
  89. }
  90. return false;
  91. }
  92. /**
  93. * Filters dangerous filenames (*.php[.]?* and .htaccess) and returns it in
  94. * a non-executable form (for PHP and htaccess, this is still vulnerable to
  95. * other languages' files extensions)
  96. * @param string Unfiltered filename
  97. * @param string Filtered filename
  98. * @return string
  99. */
  100. public static function filter_filename($filename)
  101. {
  102. return disable_dangerous_file($filename);
  103. }
  104. /**
  105. * This function checks that the token generated in get_token() has been kept (prevents
  106. * Cross-Site Request Forgeries attacks)
  107. * @param string The array in which to get the token ('get' or 'post')
  108. * @return bool True if it's the right token, false otherwise
  109. */
  110. public static function check_token($request_type = 'post')
  111. {
  112. switch ($request_type) {
  113. case 'request':
  114. if (isset($_SESSION['sec_token']) && isset($_REQUEST['sec_token']) && $_SESSION['sec_token'] === $_REQUEST['sec_token']) {
  115. return true;
  116. }
  117. return false;
  118. case 'get':
  119. if (isset($_SESSION['sec_token']) && isset($_GET['sec_token']) && $_SESSION['sec_token'] === $_GET['sec_token']) {
  120. return true;
  121. }
  122. return false;
  123. case 'post':
  124. if (isset($_SESSION['sec_token']) && isset($_POST['sec_token']) && $_SESSION['sec_token'] === $_POST['sec_token']) {
  125. return true;
  126. }
  127. return false;
  128. default:
  129. if (isset($_SESSION['sec_token']) && isset($request_type) && $_SESSION['sec_token'] === $request_type) {
  130. return true;
  131. }
  132. return false;
  133. }
  134. return false; // Just in case, don't let anything slip.
  135. }
  136. /**
  137. * Checks the user agent of the client as recorder by get_ua() to prevent
  138. * most session hijacking attacks.
  139. * @return bool True if the user agent is the same, false otherwise
  140. */
  141. public static function check_ua()
  142. {
  143. if (isset($_SESSION['sec_ua']) and $_SESSION['sec_ua'] === $_SERVER['HTTP_USER_AGENT'].$_SESSION['sec_ua_seed']) {
  144. return true;
  145. }
  146. return false;
  147. }
  148. /**
  149. * Clear the security token from the session
  150. * @return void
  151. */
  152. public static function clear_token()
  153. {
  154. $_SESSION['sec_token'] = null;
  155. unset($_SESSION['sec_token']);
  156. }
  157. /**
  158. * This function sets a random token to be included in a form as a hidden field
  159. * and saves it into the user's session. Returns an HTML form element
  160. * This later prevents Cross-Site Request Forgeries by checking that the user is really
  161. * the one that sent this form in knowingly (this form hasn't been generated from
  162. * another website visited by the user at the same time).
  163. * Check the token with check_token()
  164. * @return string Hidden-type input ready to insert into a form
  165. */
  166. public static function get_HTML_token()
  167. {
  168. $token = md5(uniqid(rand(), TRUE));
  169. $string = '<input type="hidden" name="sec_token" value="'.$token.'" />';
  170. $_SESSION['sec_token'] = $token;
  171. return $string;
  172. }
  173. /**
  174. * This function sets a random token to be included in a form as a hidden field
  175. * and saves it into the user's session.
  176. * This later prevents Cross-Site Request Forgeries by checking that the user is really
  177. * the one that sent this form in knowingly (this form hasn't been generated from
  178. * another website visited by the user at the same time).
  179. * Check the token with check_token()
  180. * @return string Token
  181. */
  182. public static function get_token()
  183. {
  184. $token = md5(uniqid(rand(), TRUE));
  185. $_SESSION['sec_token'] = $token;
  186. return $token;
  187. }
  188. /**
  189. * @return string
  190. */
  191. public static function get_existing_token()
  192. {
  193. if (isset($_SESSION['sec_token']) && !empty($_SESSION['sec_token'])) {
  194. return $_SESSION['sec_token'];
  195. } else {
  196. return self::get_token();
  197. }
  198. }
  199. /**
  200. * Gets the user agent in the session to later check it with check_ua() to prevent
  201. * most cases of session hijacking.
  202. * @return void
  203. */
  204. public static function get_ua()
  205. {
  206. $_SESSION['sec_ua_seed'] = uniqid(rand(), TRUE);
  207. $_SESSION['sec_ua'] = $_SERVER['HTTP_USER_AGENT'].$_SESSION['sec_ua_seed'];
  208. }
  209. /**
  210. * This function filters a variable to the type given, with the options given
  211. * @param mixed The variable to be filtered
  212. * @param string The type of variable we expect (bool,int,float,string)
  213. * @param array Additional options
  214. * @return bool True if variable was filtered and added to the current object, false otherwise
  215. */
  216. public static function filter($var, $type = 'string', $options = array())
  217. {
  218. // This function has not been finished! Do not use!
  219. $result = false;
  220. // Get variable name and value.
  221. $args = func_get_args();
  222. $names = array_keys($args);
  223. $name = $names[0];
  224. $value = $args[$name];
  225. switch ($type) {
  226. case 'bool':
  227. $result = (bool) $var;
  228. break;
  229. case 'int':
  230. $result = (int) $var;
  231. break;
  232. case 'float':
  233. $result = (float) $var;
  234. break;
  235. case 'string/html':
  236. $result = self::remove_XSS($var);
  237. break;
  238. case 'string/db':
  239. $result = Database::escape_string($var);
  240. break;
  241. case 'array':
  242. // An array variable shouldn't be given to the filter.
  243. return false;
  244. default:
  245. return false;
  246. }
  247. if (!empty($option['save'])) {
  248. self::$clean[$name] = $result;
  249. }
  250. return $result;
  251. }
  252. /**
  253. * This function returns a variable from the clean array. If the variable doesn't exist,
  254. * it returns null
  255. * @param string Variable name
  256. * @return mixed Variable or NULL on error
  257. */
  258. public static function get($varname)
  259. {
  260. if (isset(self::$clean[$varname])) {
  261. return self::$clean[$varname];
  262. }
  263. return NULL;
  264. }
  265. /**
  266. * This function tackles the XSS injections.
  267. * Filtering for XSS is very easily done by using the htmlentities() function.
  268. * This kind of filtering prevents JavaScript snippets to be understood as such.
  269. * @param string The variable to filter for XSS, this params can be a string or an array (example : array(x,y))
  270. * @param int The user status,constant allowed (STUDENT, COURSEMANAGER, ANONYMOUS, COURSEMANAGERLOWSECURITY)
  271. * @param bool $filter_terms
  272. * @return mixed Filtered string or array
  273. */
  274. public static function remove_XSS($var, $user_status = null, $filter_terms = false)
  275. {
  276. if ($filter_terms) {
  277. $var = self::filter_terms($var);
  278. }
  279. if (empty($user_status)) {
  280. if (api_is_anonymous()) {
  281. $user_status = ANONYMOUS;
  282. } else {
  283. if (api_is_allowed_to_edit()) {
  284. $user_status = COURSEMANAGER;
  285. } else {
  286. $user_status = STUDENT;
  287. }
  288. }
  289. }
  290. if ($user_status == COURSEMANAGERLOWSECURITY) {
  291. return $var; // No filtering.
  292. }
  293. static $purifier = array();
  294. if (!isset($purifier[$user_status])) {
  295. $cache_dir = api_get_path(SYS_ARCHIVE_PATH).'Serializer';
  296. if (!file_exists($cache_dir)) {
  297. mkdir($cache_dir, 0777);
  298. }
  299. $config = HTMLPurifier_Config::createDefault();
  300. $config->set('Cache.SerializerPath', $cache_dir);
  301. $config->set('Core.Encoding', api_get_system_encoding());
  302. $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
  303. $config->set('HTML.MaxImgLength', '2560');
  304. $config->set('HTML.TidyLevel', 'light');
  305. $config->set('Core.ConvertDocumentToFragment', false);
  306. $config->set('Core.RemoveProcessingInstructions', true);
  307. if (api_get_setting('enable_iframe_inclusion') == 'true') {
  308. $config->set('Filter.Custom', array(new HTMLPurifier_Filter_AllowIframes()));
  309. }
  310. // Shows _target attribute in anchors
  311. $config->set('Attr.AllowedFrameTargets', array('_blank','_top','_self', '_parent'));
  312. if ($user_status == STUDENT) {
  313. global $allowed_html_student;
  314. $config->set('HTML.SafeEmbed', true);
  315. $config->set('HTML.SafeObject', true);
  316. $config->set('Filter.YouTube', true);
  317. $config->set('HTML.FlashAllowFullScreen', true);
  318. $config->set('HTML.Allowed', $allowed_html_student);
  319. } elseif ($user_status == COURSEMANAGER) {
  320. global $allowed_html_teacher;
  321. $config->set('HTML.SafeEmbed', true);
  322. $config->set('HTML.SafeObject', true);
  323. $config->set('Filter.YouTube', true);
  324. $config->set('HTML.FlashAllowFullScreen', true);
  325. $config->set('HTML.Allowed', $allowed_html_teacher);
  326. } else {
  327. global $allowed_html_anonymous;
  328. $config->set('HTML.Allowed', $allowed_html_anonymous);
  329. }
  330. // We need it for example for the flv player (ids of surrounding div-tags have to be preserved).
  331. $config->set('Attr.EnableID', true);
  332. $config->set('CSS.AllowImportant', true);
  333. // We need for the flv player the css definition display: none;
  334. $config->set('CSS.AllowTricky', true);
  335. $config->set('CSS.Proprietary', true);
  336. // Allow uri scheme.
  337. $config->set('URI.AllowedSchemes', array(
  338. 'http' => true,
  339. 'https' => true,
  340. 'mailto' => true,
  341. 'ftp' => true,
  342. 'nntp' => true,
  343. 'news' => true,
  344. 'data' => true,
  345. ));
  346. $purifier[$user_status] = new HTMLPurifier($config);
  347. }
  348. if (is_array($var)) {
  349. return $purifier[$user_status]->purifyArray($var);
  350. } else {
  351. return $purifier[$user_status]->purify($var);
  352. }
  353. }
  354. /**
  355. *
  356. * Filter content
  357. * @param string content to be filter
  358. * @return string
  359. */
  360. static function filter_terms($text)
  361. {
  362. static $bad_terms = array();
  363. if (empty($bad_terms)) {
  364. $list = api_get_setting('filter_terms');
  365. $list = explode("\n", $list);
  366. $list = array_filter($list);
  367. if (!empty($list)) {
  368. foreach ($list as $term) {
  369. $term = str_replace(array("\r\n", "\r", "\n", "\t"), '', $term);
  370. $html_entities_value = api_htmlentities($term, ENT_QUOTES, api_get_system_encoding());
  371. $bad_terms[] = $term;
  372. if ($term != $html_entities_value) {
  373. $bad_terms[] = $html_entities_value;
  374. }
  375. }
  376. $bad_terms = array_filter($bad_terms);
  377. }
  378. }
  379. $replace = '***';
  380. if (!empty($bad_terms)) {
  381. //Fast way
  382. $new_text = str_ireplace($bad_terms, $replace, $text, $count);
  383. //We need statistics
  384. /*
  385. if (strlen($new_text) != strlen($text)) {
  386. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_FILTERED_TERMS);
  387. $attributes = array();
  388. $attributes['user_id'] =
  389. $attributes['course_id'] =
  390. $attributes['session_id'] =
  391. $attributes['tool_id'] =
  392. $attributes['term'] =
  393. $attributes['created_at'] = api_get_utc_datetime();
  394. $sql = Database::insert($table, $attributes);
  395. }
  396. */
  397. $text = $new_text;
  398. }
  399. return $text;
  400. }
  401. /**
  402. * This method provides specific protection (against XSS and other kinds of attacks) for static images (icons) used by the system.
  403. * Image paths are supposed to be given by programmers - people who know what they do, anyway, this method encourages
  404. * a safe practice for generating icon paths, without using heavy solutions based on HTMLPurifier for example.
  405. * @param string $img_path The input path of the image, it could be relative or absolute URL.
  406. * @return string Returns sanitized image path or an empty string when the image path is not secure.
  407. * @author Ivan Tcholakov, March 2011
  408. */
  409. public static function filter_img_path($image_path)
  410. {
  411. static $allowed_extensions = array('png', 'gif', 'jpg', 'jpeg', 'svg', 'webp');
  412. $image_path = htmlspecialchars(trim($image_path)); // No html code is allowed.
  413. // We allow static images only, query strings are forbidden.
  414. if (strpos($image_path, '?') !== false) {
  415. return '';
  416. }
  417. if (($pos = strpos($image_path, ':')) !== false) {
  418. // Protocol has been specified, let's check it.
  419. if (stripos($image_path, 'javascript:') !== false) {
  420. // Javascript everywhere in the path is not allowed.
  421. return '';
  422. }
  423. // We allow only http: and https: protocols for now.
  424. //if (!preg_match('/^https?:\/\//i', $image_path)) {
  425. // return '';
  426. //}
  427. if (stripos($image_path, 'http://') !== 0 && stripos($image_path, 'https://') !== 0) {
  428. return '';
  429. }
  430. }
  431. // We allow file extensions for images only.
  432. //if (!preg_match('/.+\.(png|gif|jpg|jpeg)$/i', $image_path)) {
  433. // return '';
  434. //}
  435. if (($pos = strrpos($image_path, '.')) !== false) {
  436. if (!in_array(strtolower(substr($image_path, $pos + 1)), $allowed_extensions)) {
  437. return '';
  438. }
  439. } else {
  440. return '';
  441. }
  442. return $image_path;
  443. }
  444. }