security.lib.php 16 KB

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