security.lib.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Component\HTMLPurifier\Filter\AllowIframes;
  4. use ChamiloSession as Session;
  5. /**
  6. * This is the security library for Chamilo.
  7. *
  8. * This library is based on recommendations found in the PHP5 Certification
  9. * Guide published at PHP|Architect, and other recommendations found on
  10. * http://www.phpsec.org/
  11. * The principles here are that all data is tainted (most scripts of Chamilo are
  12. * open to the public or at least to a certain public that could be malicious
  13. * under specific circumstances). We use the white list approach, where as we
  14. * consider that data can only be used in the database or in a file if it has
  15. * been filtered.
  16. *
  17. * For session fixation, use ...
  18. * For session hijacking, use get_ua() and check_ua()
  19. * For Cross-Site Request Forgeries, use get_token() and check_tocken()
  20. * For basic filtering, use filter()
  21. * For files inclusions (using dynamic paths) use check_rel_path() and check_abs_path()
  22. *
  23. * @package chamilo.library
  24. *
  25. * @author Yannick Warnier <ywarnier@beeznest.org>
  26. */
  27. /**
  28. * Security class.
  29. *
  30. * Include/require it in your code and call Security::function()
  31. * to use its functionalities.
  32. *
  33. * This class can also be used as a container for filtered data, by creating
  34. * a new Security object and using $secure->filter($new_var,[more options])
  35. * and then using $secure->clean['var'] as a filtered equivalent, although
  36. * this is *not* mandatory at all.
  37. */
  38. class Security
  39. {
  40. public static $clean = [];
  41. /**
  42. * Checks if the absolute path (directory) given is really under the
  43. * checker path (directory).
  44. *
  45. * @param string Absolute path to be checked (with trailing slash)
  46. * @param string Checker path under which the path
  47. * should be (absolute path, with trailing slash, get it from api_get_path(SYS_COURSE_PATH))
  48. *
  49. * @return bool True if the path is under the checker, false otherwise
  50. */
  51. public static function check_abs_path($abs_path, $checker_path)
  52. {
  53. // The checker path must be set.
  54. if (empty($checker_path)) {
  55. return false;
  56. }
  57. $true_path = str_replace("\\", '/', realpath($abs_path));
  58. $checker_path = str_replace("\\", '/', realpath($checker_path));
  59. if (empty($checker_path)) {
  60. return false;
  61. }
  62. $found = strpos($true_path.'/', $checker_path);
  63. if ($found === 0) {
  64. return true;
  65. } else {
  66. // Code specific to Windows and case-insensitive behaviour
  67. if (api_is_windows_os()) {
  68. $found = stripos($true_path.'/', $checker_path);
  69. if ($found === 0) {
  70. return true;
  71. }
  72. }
  73. }
  74. return false;
  75. }
  76. /**
  77. * Checks if the relative path (directory) given is really under the
  78. * checker path (directory).
  79. *
  80. * @param string Relative path to be checked (relative to the current directory) (with trailing slash)
  81. * @param string Checker path under which the path
  82. * should be (absolute path, with trailing slash, get it from api_get_path(SYS_COURSE_PATH))
  83. *
  84. * @return bool True if the path is under the checker, false otherwise
  85. */
  86. public static function check_rel_path($rel_path, $checker_path)
  87. {
  88. // The checker path must be set.
  89. if (empty($checker_path)) {
  90. return false;
  91. }
  92. $current_path = getcwd(); // No trailing slash.
  93. if (substr($rel_path, -1, 1) != '/') {
  94. $rel_path = '/'.$rel_path;
  95. }
  96. $abs_path = $current_path.$rel_path;
  97. $true_path = str_replace("\\", '/', realpath($abs_path));
  98. $found = strpos($true_path.'/', $checker_path);
  99. if ($found === 0) {
  100. return true;
  101. }
  102. return false;
  103. }
  104. /**
  105. * Filters dangerous filenames (*.php[.]?* and .htaccess) and returns it in
  106. * a non-executable form (for PHP and htaccess, this is still vulnerable to
  107. * other languages' files extensions).
  108. *
  109. * @param string $filename Unfiltered filename
  110. *
  111. * @return string
  112. */
  113. public static function filter_filename($filename)
  114. {
  115. return disable_dangerous_file($filename);
  116. }
  117. /**
  118. * @return string
  119. */
  120. public static function getTokenFromSession()
  121. {
  122. return Session::read('sec_token');
  123. }
  124. /**
  125. * This function checks that the token generated in get_token() has been kept (prevents
  126. * Cross-Site Request Forgeries attacks).
  127. *
  128. * @param string The array in which to get the token ('get' or 'post')
  129. *
  130. * @return bool True if it's the right token, false otherwise
  131. */
  132. public static function check_token($request_type = 'post')
  133. {
  134. $sessionToken = Session::read('sec_token');
  135. switch ($request_type) {
  136. case 'request':
  137. if (!empty($sessionToken) && isset($_REQUEST['sec_token']) && $sessionToken === $_REQUEST['sec_token']) {
  138. return true;
  139. }
  140. return false;
  141. case 'get':
  142. if (!empty($sessionToken) && isset($_GET['sec_token']) && $sessionToken === $_GET['sec_token']) {
  143. return true;
  144. }
  145. return false;
  146. case 'post':
  147. if (!empty($sessionToken) && isset($_POST['sec_token']) && $sessionToken === $_POST['sec_token']) {
  148. return true;
  149. }
  150. return false;
  151. default:
  152. if (!empty($sessionToken) && isset($request_type) && $sessionToken === $request_type) {
  153. return true;
  154. }
  155. return false;
  156. }
  157. return false; // Just in case, don't let anything slip.
  158. }
  159. /**
  160. * Checks the user agent of the client as recorder by get_ua() to prevent
  161. * most session hijacking attacks.
  162. *
  163. * @return bool True if the user agent is the same, false otherwise
  164. */
  165. public static function check_ua()
  166. {
  167. $security = Session::read('sec_ua');
  168. $securitySeed = Session::read('sec_ua_seed');
  169. if ($security === $_SERVER['HTTP_USER_AGENT'].$securitySeed) {
  170. return true;
  171. }
  172. return false;
  173. }
  174. /**
  175. * Clear the security token from the session.
  176. */
  177. public static function clear_token()
  178. {
  179. Session::erase('sec_token');
  180. }
  181. /**
  182. * This function sets a random token to be included in a form as a hidden field
  183. * and saves it into the user's session. Returns an HTML form element
  184. * This later prevents Cross-Site Request Forgeries by checking that the user is really
  185. * the one that sent this form in knowingly (this form hasn't been generated from
  186. * another website visited by the user at the same time).
  187. * Check the token with check_token().
  188. *
  189. * @return string Hidden-type input ready to insert into a form
  190. */
  191. public static function get_HTML_token()
  192. {
  193. $token = md5(uniqid(rand(), true));
  194. $string = '<input type="hidden" name="sec_token" value="'.$token.'" />';
  195. Session::write('sec_token', $token);
  196. return $string;
  197. }
  198. /**
  199. * This function sets a random token to be included in a form as a hidden field
  200. * and saves it into the user's session.
  201. * This later prevents Cross-Site Request Forgeries by checking that the user is really
  202. * the one that sent this form in knowingly (this form hasn't been generated from
  203. * another website visited by the user at the same time).
  204. * Check the token with check_token().
  205. *
  206. * @return string Token
  207. */
  208. public static function get_token()
  209. {
  210. $token = md5(uniqid(rand(), true));
  211. Session::write('sec_token', $token);
  212. return $token;
  213. }
  214. /**
  215. * @return string
  216. */
  217. public static function get_existing_token()
  218. {
  219. $token = Session::read('sec_token');
  220. if (!empty($token)) {
  221. return $token;
  222. } else {
  223. return self::get_token();
  224. }
  225. }
  226. /**
  227. * Gets the user agent in the session to later check it with check_ua() to prevent
  228. * most cases of session hijacking.
  229. */
  230. public static function get_ua()
  231. {
  232. $seed = uniqid(rand(), true);
  233. Session::write('sec_ua_seed', $seed);
  234. Session::write('sec_ua', $_SERVER['HTTP_USER_AGENT'].$seed);
  235. }
  236. /**
  237. * This function returns a variable from the clean array. If the variable doesn't exist,
  238. * it returns null.
  239. *
  240. * @param string Variable name
  241. *
  242. * @return mixed Variable or NULL on error
  243. */
  244. public static function get($varname)
  245. {
  246. if (isset(self::$clean[$varname])) {
  247. return self::$clean[$varname];
  248. }
  249. return null;
  250. }
  251. /**
  252. * This function tackles the XSS injections.
  253. * Filtering for XSS is very easily done by using the htmlentities() function.
  254. * This kind of filtering prevents JavaScript snippets to be understood as such.
  255. *
  256. * @param string The variable to filter for XSS, this params can be a string or an array (example : array(x,y))
  257. * @param int The user status,constant allowed (STUDENT, COURSEMANAGER, ANONYMOUS, COURSEMANAGERLOWSECURITY)
  258. * @param bool $filter_terms
  259. *
  260. * @return mixed Filtered string or array
  261. */
  262. public static function remove_XSS($var, $user_status = null, $filter_terms = false)
  263. {
  264. if ($filter_terms) {
  265. $var = self::filter_terms($var);
  266. }
  267. if (empty($user_status)) {
  268. if (api_is_anonymous()) {
  269. $user_status = ANONYMOUS;
  270. } else {
  271. if (api_is_allowed_to_edit()) {
  272. $user_status = COURSEMANAGER;
  273. } else {
  274. $user_status = STUDENT;
  275. }
  276. }
  277. }
  278. if ($user_status == COURSEMANAGERLOWSECURITY) {
  279. return $var; // No filtering.
  280. }
  281. static $purifier = [];
  282. if (!isset($purifier[$user_status])) {
  283. $cache_dir = api_get_path(SYS_ARCHIVE_PATH).'Serializer';
  284. if (!file_exists($cache_dir)) {
  285. $mode = api_get_permissions_for_new_directories();
  286. mkdir($cache_dir, $mode);
  287. }
  288. $config = HTMLPurifier_Config::createDefault();
  289. $config->set('Cache.SerializerPath', $cache_dir);
  290. $config->set('Core.Encoding', api_get_system_encoding());
  291. $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
  292. $config->set('HTML.MaxImgLength', '2560');
  293. $config->set('HTML.TidyLevel', 'light');
  294. $config->set('Core.ConvertDocumentToFragment', false);
  295. $config->set('Core.RemoveProcessingInstructions', true);
  296. if (api_get_setting('enable_iframe_inclusion') == 'true') {
  297. $config->set('Filter.Custom', [new AllowIframes()]);
  298. }
  299. // Shows _target attribute in anchors
  300. $config->set('Attr.AllowedFrameTargets', ['_blank', '_top', '_self', '_parent']);
  301. if ($user_status == STUDENT) {
  302. global $allowed_html_student;
  303. $config->set('HTML.SafeEmbed', true);
  304. $config->set('HTML.SafeObject', true);
  305. $config->set('Filter.YouTube', true);
  306. $config->set('HTML.FlashAllowFullScreen', true);
  307. $config->set('HTML.Allowed', $allowed_html_student);
  308. } elseif ($user_status == COURSEMANAGER) {
  309. global $allowed_html_teacher;
  310. $config->set('HTML.SafeEmbed', true);
  311. $config->set('HTML.SafeObject', true);
  312. $config->set('Filter.YouTube', true);
  313. $config->set('HTML.FlashAllowFullScreen', true);
  314. $config->set('HTML.Allowed', $allowed_html_teacher);
  315. } else {
  316. global $allowed_html_anonymous;
  317. $config->set('HTML.Allowed', $allowed_html_anonymous);
  318. }
  319. // We need it for example for the flv player (ids of surrounding div-tags have to be preserved).
  320. $config->set('Attr.EnableID', true);
  321. $config->set('CSS.AllowImportant', true);
  322. // We need for the flv player the css definition display: none;
  323. $config->set('CSS.AllowTricky', true);
  324. $config->set('CSS.Proprietary', true);
  325. // Allow uri scheme.
  326. $config->set('URI.AllowedSchemes', [
  327. 'http' => true,
  328. 'https' => true,
  329. 'mailto' => true,
  330. 'ftp' => true,
  331. 'nntp' => true,
  332. 'news' => true,
  333. 'data' => true,
  334. ]);
  335. // Allow <video> tag
  336. //$config->set('HTML.Doctype', 'HTML 4.01 Transitional');
  337. $config->set('HTML.SafeIframe', true);
  338. // Set some HTML5 properties
  339. $config->set('HTML.DefinitionID', 'html5-definitions'); // unqiue id
  340. $config->set('HTML.DefinitionRev', 1);
  341. if ($def = $config->maybeGetRawHTMLDefinition()) {
  342. // https://html.spec.whatwg.org/dev/media.html#the-video-element
  343. $def->addElement(
  344. 'video',
  345. 'Block',
  346. 'Optional: (source, Flow) | (Flow, source) | Flow',
  347. 'Common',
  348. [
  349. 'src' => 'URI',
  350. 'type' => 'Text',
  351. 'width' => 'Length',
  352. 'height' => 'Length',
  353. 'poster' => 'URI',
  354. 'preload' => 'Enum#auto,metadata,none',
  355. 'controls' => 'Bool',
  356. ]
  357. );
  358. // https://html.spec.whatwg.org/dev/media.html#the-audio-element
  359. $def->addElement(
  360. 'audio',
  361. 'Block',
  362. 'Optional: (source, Flow) | (Flow, source) | Flow',
  363. 'Common',
  364. [
  365. 'autoplay' => 'Bool',
  366. 'src' => 'URI',
  367. 'loop' => 'Bool',
  368. 'preload' => 'Enum#auto,metadata,none',
  369. 'controls' => 'Bool',
  370. 'muted' => 'Bool',
  371. ]
  372. );
  373. $def->addElement(
  374. 'source',
  375. 'Block',
  376. 'Flow',
  377. 'Common',
  378. ['src' => 'URI', 'type' => 'Text']
  379. );
  380. }
  381. $purifier[$user_status] = new HTMLPurifier($config);
  382. }
  383. if (is_array($var)) {
  384. return $purifier[$user_status]->purifyArray($var);
  385. } else {
  386. return $purifier[$user_status]->purify($var);
  387. }
  388. }
  389. /**
  390. * Filter content.
  391. *
  392. * @param string $text to be filter
  393. *
  394. * @return string
  395. */
  396. public static function filter_terms($text)
  397. {
  398. static $bad_terms = [];
  399. if (empty($bad_terms)) {
  400. $list = api_get_setting('filter_terms');
  401. if (!empty($list)) {
  402. $list = explode("\n", $list);
  403. $list = array_filter($list);
  404. if (!empty($list)) {
  405. foreach ($list as $term) {
  406. $term = str_replace(["\r\n", "\r", "\n", "\t"], '', $term);
  407. $html_entities_value = api_htmlentities($term, ENT_QUOTES, api_get_system_encoding());
  408. $bad_terms[] = $term;
  409. if ($term != $html_entities_value) {
  410. $bad_terms[] = $html_entities_value;
  411. }
  412. }
  413. }
  414. $bad_terms = array_filter($bad_terms);
  415. }
  416. }
  417. $replace = '***';
  418. if (!empty($bad_terms)) {
  419. // Fast way
  420. $new_text = str_ireplace($bad_terms, $replace, $text, $count);
  421. $text = $new_text;
  422. }
  423. return $text;
  424. }
  425. /**
  426. * This method provides specific protection (against XSS and other kinds of attacks)
  427. * for static images (icons) used by the system.
  428. * Image paths are supposed to be given by programmers - people who know what they do, anyway,
  429. * this method encourages a safe practice for generating icon paths, without using heavy solutions
  430. * based on HTMLPurifier for example.
  431. *
  432. * @param string $img_path the input path of the image, it could be relative or absolute URL
  433. *
  434. * @return string returns sanitized image path or an empty string when the image path is not secure
  435. *
  436. * @author Ivan Tcholakov, March 2011
  437. */
  438. public static function filter_img_path($image_path)
  439. {
  440. static $allowed_extensions = ['png', 'gif', 'jpg', 'jpeg', 'svg', 'webp'];
  441. $image_path = htmlspecialchars(trim($image_path)); // No html code is allowed.
  442. // We allow static images only, query strings are forbidden.
  443. if (strpos($image_path, '?') !== false) {
  444. return '';
  445. }
  446. if (($pos = strpos($image_path, ':')) !== false) {
  447. // Protocol has been specified, let's check it.
  448. if (stripos($image_path, 'javascript:') !== false) {
  449. // Javascript everywhere in the path is not allowed.
  450. return '';
  451. }
  452. // We allow only http: and https: protocols for now.
  453. //if (!preg_match('/^https?:\/\//i', $image_path)) {
  454. // return '';
  455. //}
  456. if (stripos($image_path, 'http://') !== 0 && stripos($image_path, 'https://') !== 0) {
  457. return '';
  458. }
  459. }
  460. // We allow file extensions for images only.
  461. //if (!preg_match('/.+\.(png|gif|jpg|jpeg)$/i', $image_path)) {
  462. // return '';
  463. //}
  464. if (($pos = strrpos($image_path, '.')) !== false) {
  465. if (!in_array(strtolower(substr($image_path, $pos + 1)), $allowed_extensions)) {
  466. return '';
  467. }
  468. } else {
  469. return '';
  470. }
  471. return $image_path;
  472. }
  473. /**
  474. * Get password requirements
  475. * It checks config value 'password_requirements' or uses the "classic"
  476. * Chamilo password requirements.
  477. *
  478. * @return array
  479. */
  480. public static function getPasswordRequirements()
  481. {
  482. // Default
  483. $requirements = [
  484. 'min' => [
  485. 'lowercase' => 0,
  486. 'uppercase' => 0,
  487. 'numeric' => 2,
  488. 'length' => 5,
  489. ],
  490. ];
  491. $passwordRequirements = api_get_configuration_value('password_requirements');
  492. if (!empty($passwordRequirements)) {
  493. $requirements = $passwordRequirements;
  494. }
  495. return $requirements;
  496. }
  497. /**
  498. * Gets password requirements in the platform language using get_lang
  499. * based in platform settings. See function 'self::getPasswordRequirements'.
  500. *
  501. * @return string
  502. */
  503. public static function getPasswordRequirementsToString($passedConditions = [])
  504. {
  505. $output = '';
  506. $setting = self::getPasswordRequirements();
  507. foreach ($setting as $type => $rules) {
  508. foreach ($rules as $rule => $parameter) {
  509. if (empty($parameter)) {
  510. continue;
  511. }
  512. $output .= sprintf(
  513. get_lang(
  514. 'NewPasswordRequirement'.ucfirst($type).'X'.ucfirst($rule)
  515. ),
  516. $parameter
  517. );
  518. $output .= '<br />';
  519. }
  520. }
  521. return $output;
  522. }
  523. }