Security.php 8.2 KB

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