Security.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php defined('SYSPATH') OR die('No direct script access.');
  2. /**
  3. * Security helper class.
  4. *
  5. * @package Kohana
  6. * @category Security
  7. * @author Kohana Team
  8. * @copyright (c) 2007-2012 Kohana Team
  9. * @license http://kohanaframework.org/license
  10. */
  11. class Kohana_Security {
  12. /**
  13. * @var string key name used for token storage
  14. */
  15. public static $token_name = 'security_token';
  16. /**
  17. * Generate and store a unique token which can be used to help prevent
  18. * [CSRF](http://wikipedia.org/wiki/Cross_Site_Request_Forgery) attacks.
  19. *
  20. * $token = Security::token();
  21. *
  22. * You can insert this token into your forms as a hidden field:
  23. *
  24. * echo Form::hidden('csrf', Security::token());
  25. *
  26. * And then check it when using [Validation]:
  27. *
  28. * $array->rules('csrf', array(
  29. * 'not_empty' => NULL,
  30. * 'Security::check' => NULL,
  31. * ));
  32. *
  33. * This provides a basic, but effective, method of preventing CSRF attacks.
  34. *
  35. * @param boolean $new force a new token to be generated?
  36. * @return string
  37. * @uses Session::instance
  38. */
  39. public static function token($new = FALSE)
  40. {
  41. $session = Session::instance();
  42. // Get the current token
  43. $token = $session->get(Security::$token_name);
  44. if ($new === TRUE OR ! $token)
  45. {
  46. // Generate a new unique token
  47. $token = sha1(uniqid(NULL, TRUE));
  48. // Store the new token
  49. $session->set(Security::$token_name, $token);
  50. }
  51. return $token;
  52. }
  53. /**
  54. * Check that the given token matches the currently stored security token.
  55. *
  56. * if (Security::check($token))
  57. * {
  58. * // Pass
  59. * }
  60. *
  61. * @param string $token token to check
  62. * @return boolean
  63. * @uses Security::token
  64. */
  65. public static function check($token)
  66. {
  67. return Security::token() === $token;
  68. }
  69. /**
  70. * Remove image tags from a string.
  71. *
  72. * $str = Security::strip_image_tags($str);
  73. *
  74. * @param string $str string to sanitize
  75. * @return string
  76. */
  77. public static function strip_image_tags($str)
  78. {
  79. return preg_replace('#<img\s.*?(?:src\s*=\s*["\']?([^"\'<>\s]*)["\']?[^>]*)?>#is', '$1', $str);
  80. }
  81. /**
  82. * Encodes PHP tags in a string.
  83. *
  84. * $str = Security::encode_php_tags($str);
  85. *
  86. * @param string $str string to sanitize
  87. * @return string
  88. */
  89. public static function encode_php_tags($str)
  90. {
  91. return str_replace(array('<?', '?>'), array('&lt;?', '?&gt;'), $str);
  92. }
  93. } // End security