Security.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. <?php
  2. /**
  3. * Core Security
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package Cake.Utility
  16. * @since CakePHP(tm) v .0.10.0.1233
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. App::uses('String', 'Utility');
  20. /**
  21. * Security Library contains utility methods related to security
  22. *
  23. * @package Cake.Utility
  24. */
  25. class Security {
  26. /**
  27. * Default hash method
  28. *
  29. * @var string
  30. */
  31. public static $hashType = null;
  32. /**
  33. * Default cost
  34. *
  35. * @var string
  36. */
  37. public static $hashCost = '10';
  38. /**
  39. * Get allowed minutes of inactivity based on security level.
  40. *
  41. * @deprecated Exists for backwards compatibility only, not used by the core
  42. * @return integer Allowed inactivity in minutes
  43. */
  44. public static function inactiveMins() {
  45. switch (Configure::read('Security.level')) {
  46. case 'high':
  47. return 10;
  48. case 'medium':
  49. return 100;
  50. case 'low':
  51. default:
  52. return 300;
  53. }
  54. }
  55. /**
  56. * Generate authorization hash.
  57. *
  58. * @return string Hash
  59. */
  60. public static function generateAuthKey() {
  61. return Security::hash(String::uuid());
  62. }
  63. /**
  64. * Validate authorization hash.
  65. *
  66. * @param string $authKey Authorization hash
  67. * @return boolean Success
  68. */
  69. public static function validateAuthKey($authKey) {
  70. return true;
  71. }
  72. /**
  73. * Create a hash from string using given method or fallback on next available method.
  74. *
  75. * #### Using Blowfish
  76. *
  77. * - Creating Hashes: *Do not supply a salt*. Cake handles salt creation for
  78. * you ensuring that each hashed password will have a *unique* salt.
  79. * - Comparing Hashes: Simply pass the originally hashed password as the salt.
  80. * The salt is prepended to the hash and php handles the parsing automagically.
  81. * For convenience the BlowfishAuthenticate adapter is available for use with
  82. * the AuthComponent.
  83. * - Do NOT use a constant salt for blowfish!
  84. *
  85. * Creating a blowfish/bcrypt hash:
  86. *
  87. * {{{
  88. * $hash = Security::hash($password, 'blowfish');
  89. * }}}
  90. *
  91. * @param string $string String to hash
  92. * @param string $type Method to use (sha1/sha256/md5/blowfish)
  93. * @param mixed $salt If true, automatically appends the application's salt
  94. * value to $string (Security.salt). If you are using blowfish the salt
  95. * must be false or a previously generated salt.
  96. * @return string Hash
  97. */
  98. public static function hash($string, $type = null, $salt = false) {
  99. if (empty($type)) {
  100. $type = self::$hashType;
  101. }
  102. $type = strtolower($type);
  103. if ($type === 'blowfish') {
  104. return self::_crypt($string, $salt);
  105. }
  106. if ($salt) {
  107. if (!is_string($salt)) {
  108. $salt = Configure::read('Security.salt');
  109. }
  110. $string = $salt . $string;
  111. }
  112. if (!$type || $type == 'sha1') {
  113. if (function_exists('sha1')) {
  114. return sha1($string);
  115. }
  116. $type = 'sha256';
  117. }
  118. if ($type == 'sha256' && function_exists('mhash')) {
  119. return bin2hex(mhash(MHASH_SHA256, $string));
  120. }
  121. if (function_exists('hash')) {
  122. return hash($type, $string);
  123. }
  124. return md5($string);
  125. }
  126. /**
  127. * Sets the default hash method for the Security object. This affects all objects using
  128. * Security::hash().
  129. *
  130. * @param string $hash Method to use (sha1/sha256/md5/blowfish)
  131. * @return void
  132. * @see Security::hash()
  133. */
  134. public static function setHash($hash) {
  135. self::$hashType = $hash;
  136. }
  137. /**
  138. * Sets the cost for they blowfish hash method.
  139. *
  140. * @param integer $cost Valid values are 4-31
  141. * @return void
  142. */
  143. public static function setCost($cost) {
  144. if ($cost < 4 || $cost > 31) {
  145. trigger_error(__d(
  146. 'cake_dev',
  147. 'Invalid value, cost must be between %s and %s',
  148. array(4, 31)
  149. ), E_USER_WARNING);
  150. return null;
  151. }
  152. self::$hashCost = $cost;
  153. }
  154. /**
  155. * Encrypts/Decrypts a text using the given key.
  156. *
  157. * @param string $text Encrypted string to decrypt, normal string to encrypt
  158. * @param string $key Key to use
  159. * @return string Encrypted/Decrypted string
  160. */
  161. public static function cipher($text, $key) {
  162. if (empty($key)) {
  163. trigger_error(__d('cake_dev', 'You cannot use an empty key for Security::cipher()'), E_USER_WARNING);
  164. return '';
  165. }
  166. srand(Configure::read('Security.cipherSeed'));
  167. $out = '';
  168. $keyLength = strlen($key);
  169. for ($i = 0, $textLength = strlen($text); $i < $textLength; $i++) {
  170. $j = ord(substr($key, $i % $keyLength, 1));
  171. while ($j--) {
  172. rand(0, 255);
  173. }
  174. $mask = rand(0, 255);
  175. $out .= chr(ord(substr($text, $i, 1)) ^ $mask);
  176. }
  177. srand();
  178. return $out;
  179. }
  180. /**
  181. * Encrypts/Decrypts a text using the given key using rijndael method.
  182. *
  183. * @param string $text Encrypted string to decrypt, normal string to encrypt
  184. * @param string $key Key to use
  185. * @param string $operation Operation to perform, encrypt or decrypt
  186. * @return string Encrypted/Descrypted string
  187. */
  188. public static function rijndael($text, $key, $operation) {
  189. if (empty($key)) {
  190. trigger_error(__d('cake_dev', 'You cannot use an empty key for Security::rijndael()'), E_USER_WARNING);
  191. return '';
  192. }
  193. if (empty($operation) || !in_array($operation, array('encrypt', 'decrypt'))) {
  194. trigger_error(__d('cake_dev', 'You must specify the operation for Security::rijndael(), either encrypt or decrypt'), E_USER_WARNING);
  195. return '';
  196. }
  197. if (strlen($key) < 32) {
  198. trigger_error(__d('cake_dev', 'You must use a key larger than 32 bytes for Security::rijndael()'), E_USER_WARNING);
  199. return '';
  200. }
  201. $algorithm = 'rijndael-256';
  202. $mode = 'cbc';
  203. $cryptKey = substr($key, 0, 32);
  204. $iv = substr($key, strlen($key) - 32, 32);
  205. if ($operation === 'encrypt') {
  206. return mcrypt_encrypt($algorithm, $cryptKey, $text, $mode, $iv);
  207. }
  208. return rtrim(mcrypt_decrypt($algorithm, $cryptKey, $text, $mode, $iv), "\0");
  209. }
  210. /**
  211. * Generates a pseudo random salt suitable for use with php's crypt() function.
  212. * The salt length should not exceed 27. The salt will be composed of
  213. * [./0-9A-Za-z]{$length}.
  214. *
  215. * @param integer $length The length of the returned salt
  216. * @return string The generated salt
  217. */
  218. protected static function _salt($length = 22) {
  219. $salt = str_replace(
  220. array('+', '='),
  221. '.',
  222. base64_encode(sha1(uniqid(Configure::read('Security.salt'), true), true))
  223. );
  224. return substr($salt, 0, $length);
  225. }
  226. /**
  227. * One way encryption using php's crypt() function. To use blowfish hashing see ``Security::hash()``
  228. *
  229. * @param string $password The string to be encrypted.
  230. * @param mixed $salt false to generate a new salt or an existing salt.
  231. * @return string The hashed string or an empty string on error.
  232. */
  233. protected static function _crypt($password, $salt = false) {
  234. if ($salt === false) {
  235. $salt = self::_salt(22);
  236. $salt = vsprintf('$2a$%02d$%s', array(self::$hashCost, $salt));
  237. }
  238. if ($salt === true || strpos($salt, '$2a$') !== 0 || strlen($salt) < 29) {
  239. trigger_error(__d(
  240. 'cake_dev',
  241. 'Invalid salt: %s for %s Please visit http://www.php.net/crypt and read the appropriate section for building %s salts.',
  242. array($salt, 'blowfish', 'blowfish')
  243. ), E_USER_WARNING);
  244. return '';
  245. }
  246. return crypt($password, $salt);
  247. }
  248. }