PageRenderTime 56ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Utility/Security.php

https://gitlab.com/grlopez90/servipro
PHP | 417 lines | 205 code | 36 blank | 176 comment | 36 complexity | b25e8af5f79ba7d2888bec800c7f333b 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. * @deprecated 2.8.1 This method was removed in 3.0.0
  59. */
  60. public static function generateAuthKey() {
  61. return Security::hash(CakeText::uuid());
  62. }
  63. /**
  64. * Validate authorization hash.
  65. *
  66. * @param string $authKey Authorization hash
  67. * @return bool Success
  68. * @deprecated 2.8.1 This method was removed in 3.0.0
  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 `BlowfishPasswordHasher` class 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. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/security.html#Security::hash
  99. */
  100. public static function hash($string, $type = null, $salt = false) {
  101. if (empty($type)) {
  102. $type = static::$hashType;
  103. }
  104. $type = strtolower($type);
  105. if ($type === 'blowfish') {
  106. return static::_crypt($string, $salt);
  107. }
  108. if ($salt) {
  109. if (!is_string($salt)) {
  110. $salt = Configure::read('Security.salt');
  111. }
  112. $string = $salt . $string;
  113. }
  114. if (!$type || $type === 'sha1') {
  115. if (function_exists('sha1')) {
  116. return sha1($string);
  117. }
  118. $type = 'sha256';
  119. }
  120. if ($type === 'sha256' && function_exists('mhash')) {
  121. return bin2hex(mhash(MHASH_SHA256, $string));
  122. }
  123. if (function_exists('hash')) {
  124. return hash($type, $string);
  125. }
  126. return md5($string);
  127. }
  128. /**
  129. * Sets the default hash method for the Security object. This affects all objects using
  130. * Security::hash().
  131. *
  132. * @param string $hash Method to use (sha1/sha256/md5/blowfish)
  133. * @return void
  134. * @see Security::hash()
  135. */
  136. public static function setHash($hash) {
  137. static::$hashType = $hash;
  138. }
  139. /**
  140. * Sets the cost for they blowfish hash method.
  141. *
  142. * @param int $cost Valid values are 4-31
  143. * @return void
  144. */
  145. public static function setCost($cost) {
  146. if ($cost < 4 || $cost > 31) {
  147. trigger_error(__d(
  148. 'cake_dev',
  149. 'Invalid value, cost must be between %s and %s',
  150. array(4, 31)
  151. ), E_USER_WARNING);
  152. return null;
  153. }
  154. static::$hashCost = $cost;
  155. }
  156. /**
  157. * Get random bytes from a secure source.
  158. *
  159. * This method will fall back to an insecure source an trigger a warning
  160. * if it cannot find a secure source of random data.
  161. *
  162. * @param int $length The number of bytes you want.
  163. * @return string Random bytes in binary.
  164. */
  165. public static function randomBytes($length) {
  166. if (function_exists('random_bytes')) {
  167. return random_bytes($length);
  168. }
  169. if (function_exists('openssl_random_pseudo_bytes')) {
  170. return openssl_random_pseudo_bytes($length);
  171. }
  172. trigger_error(
  173. 'You do not have a safe source of random data available. ' .
  174. 'Install either the openssl extension, or paragonie/random_compat. ' .
  175. 'Falling back to an insecure random source.',
  176. E_USER_WARNING
  177. );
  178. $bytes = '';
  179. $byteLength = 0;
  180. while ($byteLength < $length) {
  181. $bytes .= static::hash(CakeText::uuid() . uniqid(mt_rand(), true), 'sha512', true);
  182. $byteLength = strlen($bytes);
  183. }
  184. return substr($bytes, 0, $length);
  185. }
  186. /**
  187. * Runs $text through a XOR cipher.
  188. *
  189. * *Note* This is not a cryptographically strong method and should not be used
  190. * for sensitive data. Additionally this method does *not* work in environments
  191. * where suhosin is enabled.
  192. *
  193. * Instead you should use Security::rijndael() when you need strong
  194. * encryption.
  195. *
  196. * @param string $text Encrypted string to decrypt, normal string to encrypt
  197. * @param string $key Key to use
  198. * @return string Encrypted/Decrypted string
  199. * @deprecated 3.0.0 Will be removed in 3.0.
  200. */
  201. public static function cipher($text, $key) {
  202. if (empty($key)) {
  203. trigger_error(__d('cake_dev', 'You cannot use an empty key for %s', 'Security::cipher()'), E_USER_WARNING);
  204. return '';
  205. }
  206. srand((int)Configure::read('Security.cipherSeed'));
  207. $out = '';
  208. $keyLength = strlen($key);
  209. for ($i = 0, $textLength = strlen($text); $i < $textLength; $i++) {
  210. $j = ord(substr($key, $i % $keyLength, 1));
  211. while ($j--) {
  212. rand(0, 255);
  213. }
  214. $mask = rand(0, 255);
  215. $out .= chr(ord(substr($text, $i, 1)) ^ $mask);
  216. }
  217. srand();
  218. return $out;
  219. }
  220. /**
  221. * Encrypts/Decrypts a text using the given key using rijndael method.
  222. *
  223. * Prior to 2.3.1, a fixed initialization vector was used. This was not
  224. * secure. This method now uses a random iv, and will silently upgrade values when
  225. * they are re-encrypted.
  226. *
  227. * @param string $text Encrypted string to decrypt, normal string to encrypt
  228. * @param string $key Key to use as the encryption key for encrypted data.
  229. * @param string $operation Operation to perform, encrypt or decrypt
  230. * @return string Encrypted/Decrypted string
  231. */
  232. public static function rijndael($text, $key, $operation) {
  233. if (empty($key)) {
  234. trigger_error(__d('cake_dev', 'You cannot use an empty key for %s', 'Security::rijndael()'), E_USER_WARNING);
  235. return '';
  236. }
  237. if (empty($operation) || !in_array($operation, array('encrypt', 'decrypt'))) {
  238. trigger_error(__d('cake_dev', 'You must specify the operation for Security::rijndael(), either encrypt or decrypt'), E_USER_WARNING);
  239. return '';
  240. }
  241. if (strlen($key) < 32) {
  242. trigger_error(__d('cake_dev', 'You must use a key larger than 32 bytes for Security::rijndael()'), E_USER_WARNING);
  243. return '';
  244. }
  245. $algorithm = MCRYPT_RIJNDAEL_256;
  246. $mode = MCRYPT_MODE_CBC;
  247. $ivSize = mcrypt_get_iv_size($algorithm, $mode);
  248. $cryptKey = substr($key, 0, 32);
  249. if ($operation === 'encrypt') {
  250. $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
  251. return $iv . '$$' . mcrypt_encrypt($algorithm, $cryptKey, $text, $mode, $iv);
  252. }
  253. // Backwards compatible decrypt with fixed iv
  254. if (substr($text, $ivSize, 2) !== '$$') {
  255. $iv = substr($key, strlen($key) - 32, 32);
  256. return rtrim(mcrypt_decrypt($algorithm, $cryptKey, $text, $mode, $iv), "\0");
  257. }
  258. $iv = substr($text, 0, $ivSize);
  259. $text = substr($text, $ivSize + 2);
  260. return rtrim(mcrypt_decrypt($algorithm, $cryptKey, $text, $mode, $iv), "\0");
  261. }
  262. /**
  263. * Generates a pseudo random salt suitable for use with php's crypt() function.
  264. * The salt length should not exceed 27. The salt will be composed of
  265. * [./0-9A-Za-z]{$length}.
  266. *
  267. * @param int $length The length of the returned salt
  268. * @return string The generated salt
  269. */
  270. protected static function _salt($length = 22) {
  271. $salt = str_replace(
  272. array('+', '='),
  273. '.',
  274. base64_encode(sha1(uniqid(Configure::read('Security.salt'), true), true))
  275. );
  276. return substr($salt, 0, $length);
  277. }
  278. /**
  279. * One way encryption using php's crypt() function. To use blowfish hashing see ``Security::hash()``
  280. *
  281. * @param string $password The string to be encrypted.
  282. * @param mixed $salt false to generate a new salt or an existing salt.
  283. * @return string The hashed string or an empty string on error.
  284. */
  285. protected static function _crypt($password, $salt = false) {
  286. if ($salt === false || $salt === null || $salt === '') {
  287. $salt = static::_salt(22);
  288. $salt = vsprintf('$2a$%02d$%s', array(static::$hashCost, $salt));
  289. }
  290. $invalidCipher = (
  291. strpos($salt, '$2y$') !== 0 &&
  292. strpos($salt, '$2x$') !== 0 &&
  293. strpos($salt, '$2a$') !== 0
  294. );
  295. if ($salt === true || $invalidCipher || strlen($salt) < 29) {
  296. trigger_error(__d(
  297. 'cake_dev',
  298. 'Invalid salt: %s for %s Please visit http://www.php.net/crypt and read the appropriate section for building %s salts.',
  299. array($salt, 'blowfish', 'blowfish')
  300. ), E_USER_WARNING);
  301. return '';
  302. }
  303. return crypt($password, $salt);
  304. }
  305. /**
  306. * Encrypt a value using AES-256.
  307. *
  308. * *Caveat* You cannot properly encrypt/decrypt data with trailing null bytes.
  309. * Any trailing null bytes will be removed on decryption due to how PHP pads messages
  310. * with nulls prior to encryption.
  311. *
  312. * @param string $plain The value to encrypt.
  313. * @param string $key The 256 bit/32 byte key to use as a cipher key.
  314. * @param string $hmacSalt The salt to use for the HMAC process. Leave null to use Security.salt.
  315. * @return string Encrypted data.
  316. * @throws CakeException On invalid data or key.
  317. */
  318. public static function encrypt($plain, $key, $hmacSalt = null) {
  319. static::_checkKey($key, 'encrypt()');
  320. if ($hmacSalt === null) {
  321. $hmacSalt = Configure::read('Security.salt');
  322. }
  323. // Generate the encryption and hmac key.
  324. $key = substr(hash('sha256', $key . $hmacSalt), 0, 32);
  325. $algorithm = MCRYPT_RIJNDAEL_128;
  326. $mode = MCRYPT_MODE_CBC;
  327. $ivSize = mcrypt_get_iv_size($algorithm, $mode);
  328. $iv = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM);
  329. $ciphertext = $iv . mcrypt_encrypt($algorithm, $key, $plain, $mode, $iv);
  330. $hmac = hash_hmac('sha256', $ciphertext, $key);
  331. return $hmac . $ciphertext;
  332. }
  333. /**
  334. * Check the encryption key for proper length.
  335. *
  336. * @param string $key Key to check.
  337. * @param string $method The method the key is being checked for.
  338. * @return void
  339. * @throws CakeException When key length is not 256 bit/32 bytes
  340. */
  341. protected static function _checkKey($key, $method) {
  342. if (strlen($key) < 32) {
  343. throw new CakeException(__d('cake_dev', 'Invalid key for %s, key must be at least 256 bits (32 bytes) long.', $method));
  344. }
  345. }
  346. /**
  347. * Decrypt a value using AES-256.
  348. *
  349. * @param string $cipher The ciphertext to decrypt.
  350. * @param string $key The 256 bit/32 byte key to use as a cipher key.
  351. * @param string $hmacSalt The salt to use for the HMAC process. Leave null to use Security.salt.
  352. * @return string Decrypted data. Any trailing null bytes will be removed.
  353. * @throws CakeException On invalid data or key.
  354. */
  355. public static function decrypt($cipher, $key, $hmacSalt = null) {
  356. static::_checkKey($key, 'decrypt()');
  357. if (empty($cipher)) {
  358. throw new CakeException(__d('cake_dev', 'The data to decrypt cannot be empty.'));
  359. }
  360. if ($hmacSalt === null) {
  361. $hmacSalt = Configure::read('Security.salt');
  362. }
  363. // Generate the encryption and hmac key.
  364. $key = substr(hash('sha256', $key . $hmacSalt), 0, 32);
  365. // Split out hmac for comparison
  366. $macSize = 64;
  367. $hmac = substr($cipher, 0, $macSize);
  368. $cipher = substr($cipher, $macSize);
  369. $compareHmac = hash_hmac('sha256', $cipher, $key);
  370. if ($hmac !== $compareHmac) {
  371. return false;
  372. }
  373. $algorithm = MCRYPT_RIJNDAEL_128;
  374. $mode = MCRYPT_MODE_CBC;
  375. $ivSize = mcrypt_get_iv_size($algorithm, $mode);
  376. $iv = substr($cipher, 0, $ivSize);
  377. $cipher = substr($cipher, $ivSize);
  378. $plain = mcrypt_decrypt($algorithm, $key, $cipher, $mode, $iv);
  379. return rtrim($plain, "\0");
  380. }
  381. }