security.lib.php 8.7 KB

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