Security.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. * @since CakePHP(tm) v .0.10.0.1233
  17. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  18. */
  19. namespace Cake\Utility;
  20. use Cake\Core\Configure;
  21. use Cake\Error;
  22. /**
  23. * Security Library contains utility methods related to security
  24. *
  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. * Generate authorization hash.
  41. *
  42. * @return string Hash
  43. */
  44. public static function generateAuthKey() {
  45. return Security::hash(String::uuid());
  46. }
  47. /**
  48. * Validate authorization hash.
  49. *
  50. * @param string $authKey Authorization hash
  51. * @return boolean Success
  52. */
  53. public static function validateAuthKey($authKey) {
  54. return true;
  55. }
  56. /**
  57. * Create a hash from string using given method or fallback on next available method.
  58. *
  59. * #### Using Blowfish
  60. *
  61. * - Creating Hashes: *Do not supply a salt*. Cake handles salt creation for
  62. * you ensuring that each hashed password will have a *unique* salt.
  63. * - Comparing Hashes: Simply pass the originally hashed password as the salt.
  64. * The salt is prepended to the hash and php handles the parsing automagically.
  65. * For convenience the BlowfishAuthenticate adapter is available for use with
  66. * the AuthComponent.
  67. * - Do NOT use a constant salt for blowfish!
  68. *
  69. * Creating a blowfish/bcrypt hash:
  70. *
  71. * {{{
  72. * $hash = Security::hash($password, 'blowfish');
  73. * }}}
  74. *
  75. * @param string $string String to hash
  76. * @param string $type Method to use (sha1/sha256/md5/blowfish)
  77. * @param mixed $salt If true, automatically prepends the application's salt
  78. * value to $string (Security.salt). If you are using blowfish the salt
  79. * must be false or a previously generated salt.
  80. * @return string Hash
  81. */
  82. public static function hash($string, $type = null, $salt = false) {
  83. if (empty($type)) {
  84. $type = static::$hashType;
  85. }
  86. $type = strtolower($type);
  87. if ($type === 'blowfish') {
  88. return static::_crypt($string, $salt);
  89. }
  90. if ($salt) {
  91. if (!is_string($salt)) {
  92. $salt = Configure::read('Security.salt');
  93. }
  94. $string = $salt . $string;
  95. }
  96. if (!$type || $type === 'sha1') {
  97. if (function_exists('sha1')) {
  98. return sha1($string);
  99. }
  100. $type = 'sha256';
  101. }
  102. if ($type === 'sha256' && function_exists('mhash')) {
  103. return bin2hex(mhash(MHASH_SHA256, $string));
  104. }
  105. if (function_exists('hash')) {
  106. return hash($type, $string);
  107. }
  108. return md5($string);
  109. }
  110. /**
  111. * Sets the default hash method for the Security object. This affects all objects using
  112. * Security::hash().
  113. *
  114. * @param string $hash Method to use (sha1/sha256/md5/blowfish)
  115. * @return void
  116. * @see Security::hash()
  117. */
  118. public static function setHash($hash) {
  119. static::$hashType = $hash;
  120. }
  121. /**
  122. * Sets the cost for they blowfish hash method.
  123. *
  124. * @param integer $cost Valid values are 4-31
  125. * @return void
  126. * @throws Cake\Error\Exception When cost is invalid.
  127. */
  128. public static function setCost($cost) {
  129. if ($cost < 4 || $cost > 31) {
  130. throw new Error\Exception(__d(
  131. 'cake_dev',
  132. 'Invalid value, cost must be between %s and %s',
  133. array(4, 31)
  134. ));
  135. }
  136. static::$hashCost = $cost;
  137. }
  138. /**
  139. * Encrypts/Decrypts a text using the given key using rijndael method.
  140. *
  141. * @param string $text Encrypted string to decrypt, normal string to encrypt
  142. * @param string $key Key to use as the encryption key for encrypted data.
  143. * @param string $operation Operation to perform, encrypt or decrypt
  144. * @throws Cake\Error\Exception When there are errors.
  145. * @return string Encrypted/Decrypted string
  146. */
  147. public static function rijndael($text, $key, $operation) {
  148. if (empty($key)) {
  149. throw new Error\Exception(__d('cake_dev', 'You cannot use an empty key for %s', 'Security::rijndael()'));
  150. }
  151. if (empty($operation) || !in_array($operation, array('encrypt', 'decrypt'))) {
  152. throw new Error\Exception(__d('cake_dev', 'You must specify the operation for %s, either encrypt or decrypt', 'Security::rijndael()'));
  153. }
  154. if (strlen($key) < 32) {
  155. throw new Error\Exception(__d('cake_dev', 'You must use a key larger than 32 bytes for %s', 'Security::rijndael()'));
  156. }
  157. $algorithm = MCRYPT_RIJNDAEL_256;
  158. $mode = MCRYPT_MODE_CBC;
  159. $ivSize = mcrypt_get_iv_size($algorithm, $mode);
  160. $cryptKey = substr($key, 0, 32);
  161. if ($operation === 'encrypt') {
  162. $iv = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM);
  163. return $iv . '$$' . mcrypt_encrypt($algorithm, $cryptKey, $text, $mode, $iv);
  164. }
  165. $iv = substr($text, 0, $ivSize);
  166. $text = substr($text, $ivSize + 2);
  167. return rtrim(mcrypt_decrypt($algorithm, $cryptKey, $text, $mode, $iv), "\0");
  168. }
  169. /**
  170. * Generates a pseudo random salt suitable for use with php's crypt() function.
  171. * The salt length should not exceed 27. The salt will be composed of
  172. * [./0-9A-Za-z]{$length}.
  173. *
  174. * @param integer $length The length of the returned salt
  175. * @return string The generated salt
  176. */
  177. protected static function _salt($length = 22) {
  178. $salt = str_replace(
  179. array('+', '='),
  180. '.',
  181. base64_encode(sha1(uniqid(Configure::read('Security.salt'), true), true))
  182. );
  183. return substr($salt, 0, $length);
  184. }
  185. /**
  186. * One way encryption using php's crypt() function. To use blowfish hashing see ``Security::hash()``
  187. *
  188. * @param string $password The string to be encrypted.
  189. * @param mixed $salt false to generate a new salt or an existing salt.
  190. * @return string The hashed string or an empty string on error.
  191. * @throws Cake\Error\Exception on invalid salt values.
  192. */
  193. protected static function _crypt($password, $salt = false) {
  194. if ($salt === false) {
  195. $salt = static::_salt(22);
  196. $salt = vsprintf('$2a$%02d$%s', array(static::$hashCost, $salt));
  197. }
  198. if ($salt === true || strpos($salt, '$2a$') !== 0 || strlen($salt) < 29) {
  199. throw new Error\Exception(__d(
  200. 'cake_dev',
  201. 'Invalid salt: %s for %s Please visit http://www.php.net/crypt and read the appropriate section for building %s salts.',
  202. array($salt, 'blowfish', 'blowfish')
  203. ));
  204. }
  205. return crypt($password, $salt);
  206. }
  207. /**
  208. * Encrypt a value using AES-256.
  209. *
  210. * *Caveat* You cannot properly encrypt/decrypt data with trailing null bytes.
  211. * Any trailing null bytes will be removed on decryption due to how PHP pads messages
  212. * with nulls prior to encryption.
  213. *
  214. * @param string $plain The value to encrypt.
  215. * @param string $key The 256 bit/32 byte key to use as a cipher key.
  216. * @param string $hmacSalt The salt to use for the HMAC process. Leave null to use Security.salt.
  217. * @return string Encrypted data.
  218. * @throws Cake\Error\Exception On invalid data or key.
  219. */
  220. public static function encrypt($plain, $key, $hmacSalt = null) {
  221. self::_checkKey($key, 'encrypt()');
  222. if (strlen($plain) === 0) {
  223. throw new Error\Exception(__d('cake_dev', 'The data to encrypt cannot be empty.'));
  224. }
  225. if ($hmacSalt === null) {
  226. $hmacSalt = Configure::read('Security.salt');
  227. }
  228. // Generate the encryption and hmac key.
  229. $key = substr(hash('sha256', $key . $hmacSalt), 0, 32);
  230. $algorithm = MCRYPT_RIJNDAEL_128;
  231. $mode = MCRYPT_MODE_CBC;
  232. $ivSize = mcrypt_get_iv_size($algorithm, $mode);
  233. $iv = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM);
  234. $ciphertext = $iv . mcrypt_encrypt($algorithm, $key, $plain, $mode, $iv);
  235. $hmac = hash_hmac('sha256', $ciphertext, $key);
  236. return $hmac . $ciphertext;
  237. }
  238. /**
  239. * Check the encryption key for proper length.
  240. *
  241. * @param string $key
  242. * @param string $method The method the key is being checked for.
  243. * @return void
  244. * @throws Cake\Error\Exception When key length is not 256 bit/32 bytes
  245. */
  246. protected static function _checkKey($key, $method) {
  247. if (strlen($key) < 32) {
  248. throw new Error\Exception(__d('cake_dev', 'Invalid key for %s, key must be at least 256 bits (32 bytes) long.', $method));
  249. }
  250. }
  251. /**
  252. * Decrypt a value using AES-256.
  253. *
  254. * @param string $cipher The ciphertext to decrypt.
  255. * @param string $key The 256 bit/32 byte key to use as a cipher key.
  256. * @param string $hmacSalt The salt to use for the HMAC process. Leave null to use Security.salt.
  257. * @return string Decrypted data. Any trailing null bytes will be removed.
  258. * @throws Cake\Error\Exception On invalid data or key.
  259. */
  260. public static function decrypt($cipher, $key, $hmacSalt = null) {
  261. self::_checkKey($key, 'decrypt()');
  262. if (empty($cipher)) {
  263. throw new Error\Exception(__d('cake_dev', 'The data to decrypt cannot be empty.'));
  264. }
  265. if ($hmacSalt === null) {
  266. $hmacSalt = Configure::read('Security.salt');
  267. }
  268. // Generate the encryption and hmac key.
  269. $key = substr(hash('sha256', $key . $hmacSalt), 0, 32);
  270. // Split out hmac for comparison
  271. $macSize = 64;
  272. $hmac = substr($cipher, 0, $macSize);
  273. $cipher = substr($cipher, $macSize);
  274. $compareHmac = hash_hmac('sha256', $cipher, $key);
  275. if ($hmac !== $compareHmac) {
  276. return false;
  277. }
  278. $algorithm = MCRYPT_RIJNDAEL_128;
  279. $mode = MCRYPT_MODE_CBC;
  280. $ivSize = mcrypt_get_iv_size($algorithm, $mode);
  281. $iv = substr($cipher, 0, $ivSize);
  282. $cipher = substr($cipher, $ivSize);
  283. $plain = mcrypt_decrypt($algorithm, $key, $cipher, $mode, $iv);
  284. return rtrim($plain, "\0");
  285. }
  286. }