security.lib.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This is the security library for Chamilo.
  5. *
  6. * This library is based on recommendations found in the PHP5 Certification
  7. * Guide published at PHP|Architect, and other recommendations found on
  8. * http://www.phpsec.org/
  9. * The principles here are that all data is tainted (most scripts of Chamilo are
  10. * open to the public or at least to a certain public that could be malicious
  11. * under specific circumstances). We use the white list approach, where as we
  12. * consider that data can only be used in the database or in a file if it has
  13. * been filtered.
  14. *
  15. * For session fixation, use ...
  16. * For session hijacking, use get_ua() and check_ua()
  17. * For Cross-Site Request Forgeries, use get_token() and check_tocken()
  18. * For basic filtering, use filter()
  19. * For files inclusions (using dynamic paths) use check_rel_path() and check_abs_path()
  20. *
  21. * @package chamilo.library
  22. * @author Yannick Warnier <ywarnier@beeznest.org>
  23. */
  24. /**
  25. * Security class
  26. *
  27. * Include/require it in your code and call Security::function()
  28. * to use its functionalities.
  29. *
  30. * This class can also be used as a container for filtered data, by creating
  31. * a new Security object and using $secure->filter($new_var,[more options])
  32. * and then using $secure->clean['var'] as a filtered equivalent, although
  33. * this is *not* mandatory at all.
  34. */
  35. class Security {
  36. public static $clean = array();
  37. /**
  38. * Checks if the absolute path (directory) given is really under the
  39. * checker path (directory)
  40. * @param string Absolute path to be checked (with trailing slash)
  41. * @param string Checker path under which the path should be (absolute path, with trailing slash, get it from api_get_path(SYS_COURSE_PATH))
  42. * @return bool True if the path is under the checker, false otherwise
  43. */
  44. public static function check_abs_path ($abs_path,$checker_path) {
  45. if (empty($checker_path)) {return false;} //checker path must be set
  46. $true_path=str_replace("\\", "/", realpath($abs_path));
  47. $found = strpos($true_path.'/',$checker_path);
  48. if ($found===0) {
  49. return true;
  50. }
  51. return false;
  52. }
  53. /**
  54. * Checks if the relative path (directory) given is really under the
  55. * checker path (directory)
  56. * @param string Relative path to be checked (relative to the current directory) (with trailing slash)
  57. * @param string Checker path under which the path should be (absolute path, with trailing slash, get it from api_get_path(SYS_COURSE_PATH))
  58. * @return bool True if the path is under the checker, false otherwise
  59. */
  60. public static function check_rel_path ($rel_path,$checker_path) {
  61. if (empty($checker_path)){return false;} //checker path must be set
  62. $current_path = getcwd(); //no trailing slash
  63. if (substr($rel_path,-1,1)!='/') {
  64. $rel_path = '/'.$rel_path;
  65. }
  66. $abs_path = $current_path.$rel_path;
  67. $true_path=str_replace("\\", "/", realpath($abs_path));
  68. $found = strpos($true_path.'/',$checker_path);
  69. if ($found===0) {
  70. return true;
  71. }
  72. return false;
  73. }
  74. /**
  75. * Filters dangerous filenames (*.php[.]?* and .htaccess) and returns it in
  76. * a non-executable form (for PHP and htaccess, this is still vulnerable to
  77. * other languages' files extensions)
  78. * @param string Unfiltered filename
  79. * @param string Filtered filename
  80. */
  81. public static function filter_filename ($filename) {
  82. require_once(api_get_path(LIBRARY_PATH).'fileUpload.lib.php');
  83. return disable_dangerous_file($filename);
  84. }
  85. /**
  86. * This function checks that the token generated in get_token() has been kept (prevents
  87. * Cross-Site Request Forgeries attacks)
  88. * @param string The array in which to get the token ('get' or 'post')
  89. * @return bool True if it's the right token, false otherwise
  90. */
  91. public static function check_token ($array='post') {
  92. switch ($array) {
  93. case 'get':
  94. if (isset($_SESSION['sec_token']) && isset($_GET['sec_token']) && $_SESSION['sec_token'] === $_GET['sec_token']) {
  95. return true;
  96. }
  97. return false;
  98. case 'post':
  99. if (isset($_SESSION['sec_token']) && isset($_POST['sec_token']) && $_SESSION['sec_token'] === $_POST['sec_token']) {
  100. return true;
  101. }
  102. return false;
  103. default:
  104. if (isset($_SESSION['sec_token']) && isset($array) && $_SESSION['sec_token'] === $array) {
  105. return true;
  106. }
  107. return false;
  108. }
  109. return false; //just in case, don't let anything slip
  110. }
  111. /**
  112. * Checks the user agent of the client as recorder by get_ua() to prevent
  113. * most session hijacking attacks.
  114. * @return bool True if the user agent is the same, false otherwise
  115. */
  116. public static function check_ua () {
  117. if (isset($_SESSION['sec_ua']) and $_SESSION['sec_ua'] === $_SERVER['HTTP_USER_AGENT'].$_SESSION['sec_ua_seed']) {
  118. return true;
  119. }
  120. return false;
  121. }
  122. /**
  123. * Clear the security token from the session
  124. * @return void
  125. */
  126. public static function clear_token () {
  127. $_SESSION['sec_token'] = null;
  128. unset($_SESSION['sec_token']);
  129. }
  130. /**
  131. * This function sets a random token to be included in a form as a hidden field
  132. * and saves it into the user's session. Returns an HTML form element
  133. * This later prevents Cross-Site Request Forgeries by checking that the user is really
  134. * the one that sent this form in knowingly (this form hasn't been generated from
  135. * another website visited by the user at the same time).
  136. * Check the token with check_token()
  137. * @return string Hidden-type input ready to insert into a form
  138. */
  139. public static function get_HTML_token () {
  140. $token = md5(uniqid(rand(),TRUE));
  141. $string = '<input type="hidden" name="sec_token" value="'.$token.'"/>';
  142. $_SESSION['sec_token'] = $token;
  143. return $string;
  144. }
  145. /**
  146. * This function sets a random token to be included in a form as a hidden field
  147. * and saves it into the user's session.
  148. * This later prevents Cross-Site Request Forgeries by checking that the user is really
  149. * the one that sent this form in knowingly (this form hasn't been generated from
  150. * another website visited by the user at the same time).
  151. * Check the token with check_token()
  152. * @return string Token
  153. */
  154. public static function get_token () {
  155. $token = md5(uniqid(rand(),TRUE));
  156. $_SESSION['sec_token'] = $token;
  157. return $token;
  158. }
  159. /**
  160. * Gets the user agent in the session to later check it with check_ua() to prevent
  161. * most cases of session hijacking.
  162. * @return void
  163. */
  164. public static function get_ua () {
  165. $_SESSION['sec_ua_seed'] = uniqid(rand(),TRUE);
  166. $_SESSION['sec_ua'] = $_SERVER['HTTP_USER_AGENT'].$_SESSION['sec_ua_seed'];
  167. }
  168. /**
  169. * This function filters a variable to the type given, with the options given
  170. * @param mixed The variable to be filtered
  171. * @param string The type of variable we expect (bool,int,float,string)
  172. * @param array Additional options
  173. * @return bool True if variable was filtered and added to the current object, false otherwise
  174. */
  175. public static function filter ($var,$type='string',$options=array()) {
  176. //This function is not finished! Do not use!
  177. $result = false;
  178. //get variable name and value
  179. $args = func_get_args();
  180. $names =array_keys($args);
  181. $name = $names[0];
  182. $value = $args[$name];
  183. switch ($type) {
  184. case 'bool':
  185. $result = (bool) $var;
  186. break;
  187. case 'int':
  188. $result = (int) $var;
  189. break;
  190. case 'float':
  191. $result = (float) $var;
  192. break;
  193. case 'string/html':
  194. $result = self::remove_XSS($var);
  195. break;
  196. case 'string/db':
  197. $result = Database::escape_string($var);
  198. break;
  199. case 'array':
  200. //an array variable shouldn't be given to the filter
  201. return false;
  202. default:
  203. return false;
  204. }
  205. if (!empty($option['save'])) {
  206. $this->clean[$name]=$result;
  207. }
  208. return $result;
  209. }
  210. /**
  211. * This function returns a variable from the clean array. If the variable doesn't exist,
  212. * it returns null
  213. * @param string Variable name
  214. * @return mixed Variable or NULL on error
  215. */
  216. public static function get ($varname) {
  217. if (isset(self::$clean[$varname])) {
  218. return self::$clean[$varname];
  219. }
  220. return NULL;
  221. }
  222. /**
  223. * This function tackles the XSS injections.
  224. * Filtering for XSS is very easily done by using the htmlentities() function.
  225. * This kind of filtering prevents JavaScript snippets to be understood as such.
  226. * @param mixed The variable to filter for XSS, this params can be a string or an array (example : array(x,y))
  227. * @param integer The user status,constant allowed(STUDENT,COURSEMANAGER,ANONYMOUS,COURSEMANAGERLOWSECURITY)
  228. * @return mixed Filtered string or array
  229. */
  230. public static function remove_XSS ($var,$user_status=ANONYMOUS) {
  231. static $purifier = array();
  232. if (!isset($purifier[$user_status])) {
  233. $purifier[$user_status] = new HTMLPurifier(null, $user_status);
  234. }
  235. if (is_array($var)) {
  236. return $purifier[$user_status]->purifyArray($var);
  237. } else {
  238. return $purifier[$user_status]->purify($var);
  239. }
  240. }
  241. }