security.lib.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This is the security library for Dokeos.
  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 Dokeos 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 dokeos.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. * @author Yannick Warnier <yannick.warnier@dokeos.com>
  36. */
  37. class Security {
  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 should be (absolute path, with trailing slash, get it from api_get_path(SYS_COURSE_PATH))
  44. * @return bool True if the path is under the checker, false otherwise
  45. */
  46. public static function check_abs_path ($abs_path,$checker_path) {
  47. if (empty($checker_path)) {return false;} //checker path must be set
  48. $true_path=str_replace("\\", "/", realpath($abs_path));
  49. $found = strpos($true_path.'/',$checker_path);
  50. if ($found===0) {
  51. return true;
  52. }
  53. return false;
  54. }
  55. /**
  56. * Checks if the relative path (directory) given is really under the
  57. * checker path (directory)
  58. * @param string Relative path to be checked (relative to the current directory) (with trailing slash)
  59. * @param string Checker path under which the path should be (absolute path, with trailing slash, get it from api_get_path(SYS_COURSE_PATH))
  60. * @return bool True if the path is under the checker, false otherwise
  61. */
  62. public static function check_rel_path ($rel_path,$checker_path) {
  63. if (empty($checker_path)){return false;} //checker path must be set
  64. $current_path = getcwd(); //no trailing slash
  65. if (substr($rel_path,-1,1)!='/') {
  66. $rel_path = '/'.$rel_path;
  67. }
  68. $abs_path = $current_path.$rel_path;
  69. $true_path=str_replace("\\", "/", realpath($abs_path));
  70. $found = strpos($true_path.'/',$checker_path);
  71. if ($found===0) {
  72. return true;
  73. }
  74. return false;
  75. }
  76. /**
  77. * Filters dangerous filenames (*.php[.]?* and .htaccess) and returns it in
  78. * a non-executable form (for PHP and htaccess, this is still vulnerable to
  79. * other languages' files extensions)
  80. * @param string Unfiltered filename
  81. * @param string Filtered filename
  82. */
  83. public static function filter_filename ($filename) {
  84. require_once(api_get_path(LIBRARY_PATH).'fileUpload.lib.php');
  85. return disable_dangerous_file($filename);
  86. }
  87. /**
  88. * This function checks that the token generated in get_token() has been kept (prevents
  89. * Cross-Site Request Forgeries attacks)
  90. * @param string The array in which to get the token ('get' or 'post')
  91. * @return bool True if it's the right token, false otherwise
  92. */
  93. public static function check_token ($array='post') {
  94. switch ($array) {
  95. case 'get':
  96. if (isset($_SESSION['sec_token']) && isset($_GET['sec_token']) && $_SESSION['sec_token'] === $_GET['sec_token']) {
  97. return true;
  98. }
  99. return false;
  100. case 'post':
  101. if (isset($_SESSION['sec_token']) && isset($_POST['sec_token']) && $_SESSION['sec_token'] === $_POST['sec_token']) {
  102. return true;
  103. }
  104. return false;
  105. default:
  106. if (isset($_SESSION['sec_token']) && isset($array) && $_SESSION['sec_token'] === $array) {
  107. return true;
  108. }
  109. return false;
  110. }
  111. return false; //just in case, don't let anything slip
  112. }
  113. /**
  114. * Checks the user agent of the client as recorder by get_ua() to prevent
  115. * most session hijacking attacks.
  116. * @return bool True if the user agent is the same, false otherwise
  117. */
  118. public static function check_ua () {
  119. if (isset($_SESSION['sec_ua']) and $_SESSION['sec_ua'] === $_SERVER['HTTP_USER_AGENT'].$_SESSION['sec_ua_seed']) {
  120. return true;
  121. }
  122. return false;
  123. }
  124. /**
  125. * Clear the security token from the session
  126. * @return void
  127. */
  128. public static function clear_token () {
  129. $_SESSION['sec_token'] = null;
  130. unset($_SESSION['sec_token']);
  131. }
  132. /**
  133. * This function sets a random token to be included in a form as a hidden field
  134. * and saves it into the user's session. Returns an HTML form element
  135. * This later prevents Cross-Site Request Forgeries by checking that the user is really
  136. * the one that sent this form in knowingly (this form hasn't been generated from
  137. * another website visited by the user at the same time).
  138. * Check the token with check_token()
  139. * @return string Hidden-type input ready to insert into a form
  140. */
  141. public static function get_HTML_token () {
  142. $token = md5(uniqid(rand(),TRUE));
  143. $string = '<input type="hidden" name="sec_token" value="'.$token.'"/>';
  144. $_SESSION['sec_token'] = $token;
  145. return $string;
  146. }
  147. /**
  148. * This function sets a random token to be included in a form as a hidden field
  149. * and saves it into the user's session.
  150. * This later prevents Cross-Site Request Forgeries by checking that the user is really
  151. * the one that sent this form in knowingly (this form hasn't been generated from
  152. * another website visited by the user at the same time).
  153. * Check the token with check_token()
  154. * @return string Token
  155. */
  156. public static function get_token () {
  157. $token = md5(uniqid(rand(),TRUE));
  158. $_SESSION['sec_token'] = $token;
  159. return $token;
  160. }
  161. /**
  162. * Gets the user agent in the session to later check it with check_ua() to prevent
  163. * most cases of session hijacking.
  164. * @return void
  165. */
  166. public static function get_ua () {
  167. $_SESSION['sec_ua_seed'] = uniqid(rand(),TRUE);
  168. $_SESSION['sec_ua'] = $_SERVER['HTTP_USER_AGENT'].$_SESSION['sec_ua_seed'];
  169. }
  170. /**
  171. * This function filters a variable to the type given, with the options given
  172. * @param mixed The variable to be filtered
  173. * @param string The type of variable we expect (bool,int,float,string)
  174. * @param array Additional options
  175. * @return bool True if variable was filtered and added to the current object, false otherwise
  176. */
  177. public static function filter ($var,$type='string',$options=array()) {
  178. //This function is not finished! Do not use!
  179. $result = false;
  180. //get variable name and value
  181. $args = func_get_args();
  182. $names =array_keys($args);
  183. $name = $names[0];
  184. $value = $args[$name];
  185. switch ($type) {
  186. case 'bool':
  187. $result = (bool) $var;
  188. break;
  189. case 'int':
  190. $result = (int) $var;
  191. break;
  192. case 'float':
  193. $result = (float) $var;
  194. break;
  195. case 'string/html':
  196. $result = self::remove_XSS($var);
  197. break;
  198. case 'string/db':
  199. $result = Database::escape_string($var);
  200. break;
  201. case 'array':
  202. //an array variable shouldn't be given to the filter
  203. return false;
  204. default:
  205. return false;
  206. }
  207. if (!empty($option['save'])) {
  208. $this->clean[$name]=$result;
  209. }
  210. return $result;
  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. 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 mixed The variable to filter for XSS, this params can be a string or an array (example : array(x,y))
  229. * @param integer The user status,constant allowed(STUDENT,COURSEMANAGER,ANONYMOUS,COURSEMANAGERLOWSECURITY)
  230. * @return mixed Filtered string or array
  231. */
  232. public static function remove_XSS ($var,$user_status=ANONYMOUS) {
  233. $purifier = new HTMLPurifier(null,$user_status);
  234. if (is_array($var)) {
  235. return $purifier->purifyArray($var);
  236. } else {
  237. return $purifier->purify($var);
  238. }
  239. }
  240. }