security.lib.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. use Chamilo\CoreBundle\Component\HTMLPurifier\Filter\AllowIframes;
  25. /**
  26. * Security class
  27. *
  28. * Include/require it in your code and call Security::function()
  29. * to use its functionalities.
  30. *
  31. * This class can also be used as a container for filtered data, by creating
  32. * a new Security object and using $secure->filter($new_var,[more options])
  33. * and then using $secure->clean['var'] as a filtered equivalent, although
  34. * this is *not* mandatory at all.
  35. */
  36. class Security
  37. {
  38. public static $clean = array();
  39. /**
  40. * Checks if the absolute path (directory) given is really under the
  41. * checker path (directory)
  42. * @param string Absolute path to be checked (with trailing slash)
  43. * @param string Checker path under which the path should be (absolute path, with trailing slash, get it from api_get_path(SYS_COURSE_PATH))
  44. * @return bool True if the path is under the checker, false otherwise
  45. */
  46. public static function check_abs_path($abs_path, $checker_path)
  47. {
  48. // The checker path must be set.
  49. if (empty($checker_path)) {
  50. return false;
  51. }
  52. $true_path = str_replace("\\", '/', realpath($abs_path));
  53. $checker_path = str_replace("\\", '/', realpath($checker_path));
  54. $found = strpos($true_path.'/', $checker_path);
  55. if ($found === 0) {
  56. return true;
  57. } else {
  58. // Code specific to Windows and case-insensitive behaviour
  59. if (api_is_windows_os()) {
  60. $found = stripos($true_path.'/', $checker_path);
  61. if ($found === 0) {
  62. return true;
  63. }
  64. }
  65. }
  66. return false;
  67. }
  68. /**
  69. * Checks if the relative path (directory) given is really under the
  70. * checker path (directory)
  71. * @param string Relative path to be checked (relative to the current directory) (with trailing slash)
  72. * @param string Checker path under which the path should be (absolute path, with trailing slash, get it from api_get_path(SYS_COURSE_PATH))
  73. * @return bool True if the path is under the checker, false otherwise
  74. */
  75. public static function check_rel_path($rel_path, $checker_path)
  76. {
  77. // The checker path must be set.
  78. if (empty($checker_path)) {
  79. return false;
  80. }
  81. $current_path = getcwd(); // No trailing slash.
  82. if (substr($rel_path, -1, 1) != '/') {
  83. $rel_path = '/'.$rel_path;
  84. }
  85. $abs_path = $current_path.$rel_path;
  86. $true_path=str_replace("\\", '/', realpath($abs_path));
  87. $found = strpos($true_path.'/', $checker_path);
  88. if ($found === 0) {
  89. return true;
  90. }
  91. return false;
  92. }
  93. /**
  94. * Filters dangerous filenames (*.php[.]?* and .htaccess) and returns it in
  95. * a non-executable form (for PHP and htaccess, this is still vulnerable to
  96. * other languages' files extensions)
  97. * @param string Unfiltered filename
  98. * @param string Filtered filename
  99. * @return string
  100. */
  101. public static function filter_filename($filename)
  102. {
  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. $cache_dir = api_get_path(SYS_ARCHIVE_PATH).'Serializer';
  297. if (!file_exists($cache_dir)) {
  298. mkdir($cache_dir, 0777);
  299. }
  300. $config = HTMLPurifier_Config::createDefault();
  301. $config->set('Cache.SerializerPath', $cache_dir);
  302. $config->set('Core.Encoding', api_get_system_encoding());
  303. $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
  304. $config->set('HTML.MaxImgLength', '2560');
  305. $config->set('HTML.TidyLevel', 'light');
  306. $config->set('Core.ConvertDocumentToFragment', false);
  307. $config->set('Core.RemoveProcessingInstructions', true);
  308. if (api_get_setting('editor.enable_iframe_inclusion') == 'true') {
  309. $config->set('Filter.Custom', array(new AllowIframes()));
  310. }
  311. // Shows _target attribute in anchors
  312. $config->set('Attr.AllowedFrameTargets', array('_blank','_top','_self', '_parent'));
  313. if ($user_status == STUDENT) {
  314. global $allowed_html_student;
  315. $config->set('HTML.SafeEmbed', true);
  316. $config->set('HTML.SafeObject', true);
  317. $config->set('Filter.YouTube', true);
  318. $config->set('HTML.FlashAllowFullScreen', true);
  319. $config->set('HTML.Allowed', $allowed_html_student);
  320. } elseif ($user_status == COURSEMANAGER) {
  321. global $allowed_html_teacher;
  322. $config->set('HTML.SafeEmbed', true);
  323. $config->set('HTML.SafeObject', true);
  324. $config->set('Filter.YouTube', true);
  325. $config->set('HTML.FlashAllowFullScreen', true);
  326. $config->set('HTML.Allowed', $allowed_html_teacher);
  327. } else {
  328. global $allowed_html_anonymous;
  329. $config->set('HTML.Allowed', $allowed_html_anonymous);
  330. }
  331. // We need it for example for the flv player (ids of surrounding div-tags have to be preserved).
  332. $config->set('Attr.EnableID', true);
  333. $config->set('CSS.AllowImportant', true);
  334. // We need for the flv player the css definition display: none;
  335. $config->set('CSS.AllowTricky', true);
  336. $config->set('CSS.Proprietary', true);
  337. // Allow uri scheme.
  338. $config->set('URI.AllowedSchemes', array(
  339. 'http' => true,
  340. 'https' => true,
  341. 'mailto' => true,
  342. 'ftp' => true,
  343. 'nntp' => true,
  344. 'news' => true,
  345. 'data' => true,
  346. ));
  347. $purifier[$user_status] = new HTMLPurifier($config);
  348. }
  349. if (is_array($var)) {
  350. return $purifier[$user_status]->purifyArray($var);
  351. } else {
  352. return $purifier[$user_status]->purify($var);
  353. }
  354. }
  355. /**
  356. *
  357. * Filter content
  358. * @param string content to be filter
  359. * @return string
  360. */
  361. static function filter_terms($text)
  362. {
  363. static $bad_terms = array();
  364. if (empty($bad_terms)) {
  365. $list = api_get_setting('security.filter_terms');
  366. $list = explode("\n", $list);
  367. $list = array_filter($list);
  368. if (!empty($list)) {
  369. foreach ($list as $term) {
  370. $term = str_replace(array("\r\n", "\r", "\n", "\t"), '', $term);
  371. $html_entities_value = api_htmlentities($term, ENT_QUOTES, api_get_system_encoding());
  372. $bad_terms[] = $term;
  373. if ($term != $html_entities_value) {
  374. $bad_terms[] = $html_entities_value;
  375. }
  376. }
  377. $bad_terms = array_filter($bad_terms);
  378. }
  379. }
  380. $replace = '***';
  381. if (!empty($bad_terms)) {
  382. //Fast way
  383. $new_text = str_ireplace($bad_terms, $replace, $text, $count);
  384. //We need statistics
  385. /*
  386. if (strlen($new_text) != strlen($text)) {
  387. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_FILTERED_TERMS);
  388. $attributes = array();
  389. $attributes['user_id'] =
  390. $attributes['course_id'] =
  391. $attributes['session_id'] =
  392. $attributes['tool_id'] =
  393. $attributes['term'] =
  394. $attributes['created_at'] = api_get_utc_datetime();
  395. $sql = Database::insert($table, $attributes);
  396. }
  397. */
  398. $text = $new_text;
  399. }
  400. return $text;
  401. }
  402. /**
  403. * This method provides specific protection (against XSS and other kinds of attacks) for static images (icons) used by the system.
  404. * Image paths are supposed to be given by programmers - people who know what they do, anyway, this method encourages
  405. * a safe practice for generating icon paths, without using heavy solutions based on HTMLPurifier for example.
  406. * @param string $img_path The input path of the image, it could be relative or absolute URL.
  407. * @return string Returns sanitized image path or an empty string when the image path is not secure.
  408. * @author Ivan Tcholakov, March 2011
  409. */
  410. public static function filter_img_path($image_path)
  411. {
  412. static $allowed_extensions = array('png', 'gif', 'jpg', 'jpeg', 'svg', 'webp');
  413. $image_path = htmlspecialchars(trim($image_path)); // No html code is allowed.
  414. // We allow static images only, query strings are forbidden.
  415. if (strpos($image_path, '?') !== false) {
  416. return '';
  417. }
  418. if (($pos = strpos($image_path, ':')) !== false) {
  419. // Protocol has been specified, let's check it.
  420. if (stripos($image_path, 'javascript:') !== false) {
  421. // Javascript everywhere in the path is not allowed.
  422. return '';
  423. }
  424. // We allow only http: and https: protocols for now.
  425. //if (!preg_match('/^https?:\/\//i', $image_path)) {
  426. // return '';
  427. //}
  428. if (stripos($image_path, 'http://') !== 0 && stripos($image_path, 'https://') !== 0) {
  429. return '';
  430. }
  431. }
  432. // We allow file extensions for images only.
  433. //if (!preg_match('/.+\.(png|gif|jpg|jpeg)$/i', $image_path)) {
  434. // return '';
  435. //}
  436. if (($pos = strrpos($image_path, '.')) !== false) {
  437. if (!in_array(strtolower(substr($image_path, $pos + 1)), $allowed_extensions)) {
  438. return '';
  439. }
  440. } else {
  441. return '';
  442. }
  443. return $image_path;
  444. }
  445. }