security.lib.php 18 KB

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