security.lib.php 18 KB

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