security.lib.php 17 KB

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