security.lib.php 17 KB

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