PageRenderTime 13ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/users/tools.php

http://showslow.googlecode.com/
PHP | 71 lines | 47 code | 9 blank | 15 comment | 5 complexity | ceda20a1506fe75c145ab1f00f1bfcdc MD5 | raw file
  1. <?php
  2. /*
  3. * Various tools used within UserBase
  4. */
  5. class UserTools
  6. {
  7. // CSRF prevention variables
  8. public static $CSRF_NONCE;
  9. /*
  10. * Escapes strings making it safe to include user data in HTML output
  11. */
  12. public static function escape($string)
  13. {
  14. return htmlentities($string, ENT_COMPAT, 'UTF-8');
  15. }
  16. public static function preventCSRF() {
  17. $storage = new MrClay_CookieStorage(array(
  18. 'secret' => UserConfig::$SESSION_SECRET,
  19. 'mode' => MrClay_CookieStorage::MODE_ENCRYPT,
  20. 'path' => UserConfig::$SITEROOTURL,
  21. 'httponly' => true
  22. ));
  23. /*
  24. * Preventing CSRFs in all POST requests by double-posting cookies
  25. */
  26. if (count($_POST) > 0) {
  27. if (!array_key_exists('CSRF_NONCE', $_POST)) {
  28. error_log('POST request in admin interface without CSRF nonce. Make sure form includes CSRF_NONCE hidden field.');
  29. header('HTTP/1.0 403 POST request origin check failed', true, 403);
  30. exit;
  31. }
  32. $passed_nonce = $storage->fetch(UserConfig::$csrf_nonce_key);
  33. if ($passed_nonce != $_POST['CSRF_NONCE']) {
  34. error_log('[Possible CSRF attach] POST request with wrong nonce!!!');
  35. header('HTTP/1.0 403 POST request origin check failed', true, 403);
  36. exit;
  37. }
  38. }
  39. self::$CSRF_NONCE = base64_encode(mcrypt_create_iv(50, MCRYPT_DEV_URANDOM));
  40. $storage->store(UserConfig::$csrf_nonce_key, self::$CSRF_NONCE);
  41. }
  42. public static function renderCSRFNonce() {
  43. ?><input type="hidden" name="CSRF_NONCE" value="<?php echo self::escape(self::$CSRF_NONCE); ?>"/>
  44. <?php
  45. }
  46. /**
  47. * Debug wrapper for simplified debugging, call it like this:
  48. *
  49. * UserTools::debug('... some message ...');
  50. */
  51. public static function debug($message) {
  52. if (UserConfig::$DEBUG) {
  53. $trace = debug_backtrace();
  54. error_log('[DEBUG] ' . $message .
  55. ' (' . $trace[1]['function'] .
  56. '(' . var_export($trace[1]['args'], true) . ')' .
  57. ' on line ' . $trace[0]['line'] .
  58. ' in ' . $trace[0]['file'] .
  59. ')');
  60. }
  61. }
  62. }