PageRenderTime 29ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Utility/Security.php

https://gitlab.com/wewo/evina-cake
PHP | 384 lines | 184 code | 35 blank | 165 comment | 31 complexity | 6ba4f4ad66cff11ccc620692a58ddcd8 MD5 | raw file
  1. <?php
  2. /**
  3. * Core Security
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @package Cake.Utility
  15. * @since CakePHP(tm) v .0.10.0.1233
  16. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  17. */
  18. App::uses('CakeText', 'Utility');
  19. /**
  20. * Security Library contains utility methods related to security
  21. *
  22. * @package Cake.Utility
  23. */
  24. class Security {
  25. /**
  26. * Default hash method
  27. *
  28. * @var string
  29. */
  30. public static $hashType = null;
  31. /**
  32. * Default cost
  33. *
  34. * @var string
  35. */
  36. public static $hashCost = '10';
  37. /**
  38. * Get allowed minutes of inactivity based on security level.
  39. *
  40. * @deprecated 3.0.0 Exists for backwards compatibility only, not used by the core
  41. * @return int Allowed inactivity in minutes
  42. */
  43. public static function inactiveMins() {
  44. switch (Configure::read('Security.level')) {
  45. case 'high':
  46. return 10;
  47. case 'medium':
  48. return 100;
  49. case 'low':
  50. default:
  51. return 300;
  52. }
  53. }
  54. /**
  55. * Generate authorization hash.
  56. *
  57. * @return string Hash
  58. */
  59. public static function generateAuthKey() {
  60. return Security::hash(CakeText::uuid());
  61. }
  62. /**
  63. * Validate authorization hash.
  64. *
  65. * @param string $authKey Authorization hash
  66. * @return bool Success
  67. */
  68. public static function validateAuthKey($authKey) {
  69. return true;
  70. }
  71. /**
  72. * Create a hash from string using given method or fallback on next available method.
  73. *
  74. * #### Using Blowfish
  75. *
  76. * - Creating Hashes: *Do not supply a salt*. Cake handles salt creation for
  77. * you ensuring that each hashed password will have a *unique* salt.
  78. * - Comparing Hashes: Simply pass the originally hashed password as the salt.
  79. * The salt is prepended to the hash and php handles the parsing automagically.
  80. * For convenience the `BlowfishPasswordHasher` class is available for use with
  81. * the AuthComponent.
  82. * - Do NOT use a constant salt for blowfish!
  83. *
  84. * Creating a blowfish/bcrypt hash:
  85. *
  86. * ```
  87. * $hash = Security::hash($password, 'blowfish');
  88. * ```
  89. *
  90. * @param string $string String to hash
  91. * @param string $type Method to use (sha1/sha256/md5/blowfish)
  92. * @param mixed $salt If true, automatically prepends the application's salt
  93. * value to $string (Security.salt). If you are using blowfish the salt
  94. * must be false or a previously generated salt.
  95. * @return string Hash
  96. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/security.html#Security::hash
  97. */
  98. public static function hash($string, $type = null, $salt = false) {
  99. if (empty($type)) {
  100. $type = static::$hashType;
  101. }
  102. $type = strtolower($type);
  103. if ($type === 'blowfish') {
  104. return static::_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. static::$hashType = $hash;
  136. }
  137. /**
  138. * Sets the cost for they blowfish hash method.
  139. *
  140. * @param int $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. static::$hashCost = $cost;
  153. }
  154. /**
  155. * Runs $text through a XOR cipher.
  156. *
  157. * *Note* This is not a cryptographically strong method and should not be used
  158. * for sensitive data. Additionally this method does *not* work in environments
  159. * where suhosin is enabled.
  160. *
  161. * Instead you should use Security::rijndael() when you need strong
  162. * encryption.
  163. *
  164. * @param string $text Encrypted string to decrypt, normal string to encrypt
  165. * @param string $key Key to use
  166. * @return string Encrypted/Decrypted string
  167. * @deprecated 3.0.0 Will be removed in 3.0.
  168. */
  169. public static function cipher($text, $key) {
  170. if (empty($key)) {
  171. trigger_error(__d('cake_dev', 'You cannot use an empty key for %s', 'Security::cipher()'), E_USER_WARNING);
  172. return '';
  173. }
  174. srand(Configure::read('Security.cipherSeed'));
  175. $out = '';
  176. $keyLength = strlen($key);
  177. for ($i = 0, $textLength = strlen($text); $i < $textLength; $i++) {
  178. $j = ord(substr($key, $i % $keyLength, 1));
  179. while ($j--) {
  180. rand(0, 255);
  181. }
  182. $mask = rand(0, 255);
  183. $out .= chr(ord(substr($text, $i, 1)) ^ $mask);
  184. }
  185. srand();
  186. return $out;
  187. }
  188. /**
  189. * Encrypts/Decrypts a text using the given key using rijndael method.
  190. *
  191. * Prior to 2.3.1, a fixed initialization vector was used. This was not
  192. * secure. This method now uses a random iv, and will silently upgrade values when
  193. * they are re-encrypted.
  194. *
  195. * @param string $text Encrypted string to decrypt, normal string to encrypt
  196. * @param string $key Key to use as the encryption key for encrypted data.
  197. * @param string $operation Operation to perform, encrypt or decrypt
  198. * @return string Encrypted/Decrypted string
  199. */
  200. public static function rijndael($text, $key, $operation) {
  201. if (empty($key)) {
  202. trigger_error(__d('cake_dev', 'You cannot use an empty key for %s', 'Security::rijndael()'), E_USER_WARNING);
  203. return '';
  204. }
  205. if (empty($operation) || !in_array($operation, array('encrypt', 'decrypt'))) {
  206. trigger_error(__d('cake_dev', 'You must specify the operation for Security::rijndael(), either encrypt or decrypt'), E_USER_WARNING);
  207. return '';
  208. }
  209. if (strlen($key) < 32) {
  210. trigger_error(__d('cake_dev', 'You must use a key larger than 32 bytes for Security::rijndael()'), E_USER_WARNING);
  211. return '';
  212. }
  213. $algorithm = MCRYPT_RIJNDAEL_256;
  214. $mode = MCRYPT_MODE_CBC;
  215. $ivSize = mcrypt_get_iv_size($algorithm, $mode);
  216. $cryptKey = substr($key, 0, 32);
  217. if ($operation === 'encrypt') {
  218. $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
  219. return $iv . '$$' . mcrypt_encrypt($algorithm, $cryptKey, $text, $mode, $iv);
  220. }
  221. // Backwards compatible decrypt with fixed iv
  222. if (substr($text, $ivSize, 2) !== '$$') {
  223. $iv = substr($key, strlen($key) - 32, 32);
  224. return rtrim(mcrypt_decrypt($algorithm, $cryptKey, $text, $mode, $iv), "\0");
  225. }
  226. $iv = substr($text, 0, $ivSize);
  227. $text = substr($text, $ivSize + 2);
  228. return rtrim(mcrypt_decrypt($algorithm, $cryptKey, $text, $mode, $iv), "\0");
  229. }
  230. /**
  231. * Generates a pseudo random salt suitable for use with php's crypt() function.
  232. * The salt length should not exceed 27. The salt will be composed of
  233. * [./0-9A-Za-z]{$length}.
  234. *
  235. * @param int $length The length of the returned salt
  236. * @return string The generated salt
  237. */
  238. protected static function _salt($length = 22) {
  239. $salt = str_replace(
  240. array('+', '='),
  241. '.',
  242. base64_encode(sha1(uniqid(Configure::read('Security.salt'), true), true))
  243. );
  244. return substr($salt, 0, $length);
  245. }
  246. /**
  247. * One way encryption using php's crypt() function. To use blowfish hashing see ``Security::hash()``
  248. *
  249. * @param string $password The string to be encrypted.
  250. * @param mixed $salt false to generate a new salt or an existing salt.
  251. * @return string The hashed string or an empty string on error.
  252. */
  253. protected static function _crypt($password, $salt = false) {
  254. if ($salt === false) {
  255. $salt = static::_salt(22);
  256. $salt = vsprintf('$2a$%02d$%s', array(static::$hashCost, $salt));
  257. }
  258. $invalidCipher = (
  259. strpos($salt, '$2y$') !== 0 &&
  260. strpos($salt, '$2x$') !== 0 &&
  261. strpos($salt, '$2a$') !== 0
  262. );
  263. if ($salt === true || $invalidCipher || strlen($salt) < 29) {
  264. trigger_error(__d(
  265. 'cake_dev',
  266. 'Invalid salt: %s for %s Please visit http://www.php.net/crypt and read the appropriate section for building %s salts.',
  267. array($salt, 'blowfish', 'blowfish')
  268. ), E_USER_WARNING);
  269. return '';
  270. }
  271. return crypt($password, $salt);
  272. }
  273. /**
  274. * Encrypt a value using AES-256.
  275. *
  276. * *Caveat* You cannot properly encrypt/decrypt data with trailing null bytes.
  277. * Any trailing null bytes will be removed on decryption due to how PHP pads messages
  278. * with nulls prior to encryption.
  279. *
  280. * @param string $plain The value to encrypt.
  281. * @param string $key The 256 bit/32 byte key to use as a cipher key.
  282. * @param string $hmacSalt The salt to use for the HMAC process. Leave null to use Security.salt.
  283. * @return string Encrypted data.
  284. * @throws CakeException On invalid data or key.
  285. */
  286. public static function encrypt($plain, $key, $hmacSalt = null) {
  287. static::_checkKey($key, 'encrypt()');
  288. if ($hmacSalt === null) {
  289. $hmacSalt = Configure::read('Security.salt');
  290. }
  291. // Generate the encryption and hmac key.
  292. $key = substr(hash('sha256', $key . $hmacSalt), 0, 32);
  293. $algorithm = MCRYPT_RIJNDAEL_128;
  294. $mode = MCRYPT_MODE_CBC;
  295. $ivSize = mcrypt_get_iv_size($algorithm, $mode);
  296. $iv = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM);
  297. $ciphertext = $iv . mcrypt_encrypt($algorithm, $key, $plain, $mode, $iv);
  298. $hmac = hash_hmac('sha256', $ciphertext, $key);
  299. return $hmac . $ciphertext;
  300. }
  301. /**
  302. * Check the encryption key for proper length.
  303. *
  304. * @param string $key Key to check.
  305. * @param string $method The method the key is being checked for.
  306. * @return void
  307. * @throws CakeException When key length is not 256 bit/32 bytes
  308. */
  309. protected static function _checkKey($key, $method) {
  310. if (strlen($key) < 32) {
  311. throw new CakeException(__d('cake_dev', 'Invalid key for %s, key must be at least 256 bits (32 bytes) long.', $method));
  312. }
  313. }
  314. /**
  315. * Decrypt a value using AES-256.
  316. *
  317. * @param string $cipher The ciphertext to decrypt.
  318. * @param string $key The 256 bit/32 byte key to use as a cipher key.
  319. * @param string $hmacSalt The salt to use for the HMAC process. Leave null to use Security.salt.
  320. * @return string Decrypted data. Any trailing null bytes will be removed.
  321. * @throws CakeException On invalid data or key.
  322. */
  323. public static function decrypt($cipher, $key, $hmacSalt = null) {
  324. static::_checkKey($key, 'decrypt()');
  325. if (empty($cipher)) {
  326. throw new CakeException(__d('cake_dev', 'The data to decrypt cannot be empty.'));
  327. }
  328. if ($hmacSalt === null) {
  329. $hmacSalt = Configure::read('Security.salt');
  330. }
  331. // Generate the encryption and hmac key.
  332. $key = substr(hash('sha256', $key . $hmacSalt), 0, 32);
  333. // Split out hmac for comparison
  334. $macSize = 64;
  335. $hmac = substr($cipher, 0, $macSize);
  336. $cipher = substr($cipher, $macSize);
  337. $compareHmac = hash_hmac('sha256', $cipher, $key);
  338. if ($hmac !== $compareHmac) {
  339. return false;
  340. }
  341. $algorithm = MCRYPT_RIJNDAEL_128;
  342. $mode = MCRYPT_MODE_CBC;
  343. $ivSize = mcrypt_get_iv_size($algorithm, $mode);
  344. $iv = substr($cipher, 0, $ivSize);
  345. $cipher = substr($cipher, $ivSize);
  346. $plain = mcrypt_decrypt($algorithm, $key, $cipher, $mode, $iv);
  347. return rtrim($plain, "\0");
  348. }
  349. }