BaseSecurity.php 11.9 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

8
namespace yii\helpers;
Qiang Xue committed
9 10 11 12 13 14 15

use Yii;
use yii\base\Exception;
use yii\base\InvalidConfigException;
use yii\base\InvalidParamException;

/**
16
 * BaseSecurity provides concrete implementation for [[Security]].
Qiang Xue committed
17
 *
18
 * Do not use BaseSecurity. Use [[Security]] instead.
Qiang Xue committed
19 20 21 22 23
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Tom Worster <fsb@thefsb.org>
 * @since 2.0
 */
24
class BaseSecurity
Qiang Xue committed
25
{
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
	/**
	 * Uses AES, block size is 128-bit (16 bytes).
	 */
	const CRYPT_BLOCK_SIZE = 16;

	/**
	 * Uses AES-192, key size is 192-bit (24 bytes).
	 */
	const CRYPT_KEY_SIZE = 24;

	/**
	 * Uses SHA-256.
	 */
	const DERIVATION_HASH = 'sha256';

	/**
	 * Uses 1000 iterations.
	 */
	const DERIVATION_ITERATIONS = 1000;

Qiang Xue committed
46 47 48
	/**
	 * Encrypts data.
	 * @param string $data data to be encrypted.
49
	 * @param string $password the encryption password
Qiang Xue committed
50 51 52 53
	 * @return string the encrypted data
	 * @throws Exception if PHP Mcrypt extension is not loaded or failed to be initialized
	 * @see decrypt()
	 */
54
	public static function encrypt($data, $password)
Qiang Xue committed
55 56
	{
		$module = static::openCryptModule();
57
		$data = static::addPadding($data);
Qiang Xue committed
58 59
		srand();
		$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($module), MCRYPT_RAND);
60
		$key = static::deriveKey($password, $iv);
Qiang Xue committed
61 62 63 64 65 66 67 68 69 70
		mcrypt_generic_init($module, $key, $iv);
		$encrypted = $iv . mcrypt_generic($module, $data);
		mcrypt_generic_deinit($module);
		mcrypt_module_close($module);
		return $encrypted;
	}

	/**
	 * Decrypts data
	 * @param string $data data to be decrypted.
71
	 * @param string $password the decryption password
Qiang Xue committed
72 73 74 75
	 * @return string the decrypted data
	 * @throws Exception if PHP Mcrypt extension is not loaded or failed to be initialized
	 * @see encrypt()
	 */
76
	public static function decrypt($data, $password)
Qiang Xue committed
77
	{
78 79 80
		if ($data === null) {
			return null;
		}
Qiang Xue committed
81 82
		$module = static::openCryptModule();
		$ivSize = mcrypt_enc_get_iv_size($module);
83
		$iv = StringHelper::byteSubstr($data, 0, $ivSize);
84
		$key = static::deriveKey($password, $iv);
Qiang Xue committed
85
		mcrypt_generic_init($module, $key, $iv);
86
		$decrypted = mdecrypt_generic($module, StringHelper::byteSubstr($data, $ivSize, StringHelper::byteLength($data)));
Qiang Xue committed
87 88
		mcrypt_generic_deinit($module);
		mcrypt_module_close($module);
89 90 91 92 93 94 95 96 97 98
		return static::stripPadding($decrypted);
	}

	/**
	* Adds a padding to the given data (PKCS #7).
	* @param string $data the data to pad
	* @return string the padded data
	*/
	protected static function addPadding($data)
	{
99
		$pad = self::CRYPT_BLOCK_SIZE - (StringHelper::byteLength($data) % self::CRYPT_BLOCK_SIZE);
100 101 102 103 104 105 106 107 108 109
		return $data . str_repeat(chr($pad), $pad);
	}

	/**
	* Strips the padding from the given data.
	* @param string $data the data to trim
	* @return string the trimmed data
	*/
	protected static function stripPadding($data)
	{
110
		$end = StringHelper::byteSubstr($data, -1, NULL);
111
		$last = ord($end);
112
		$n = StringHelper::byteLength($data) - $last;
113 114
		if (StringHelper::byteSubstr($data, $n, NULL) == str_repeat($end, $last)) {
			return StringHelper::byteSubstr($data, 0, $n);
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
		}
		return false;
	}

	/**
	* Derives a key from the given password (PBKDF2).
	* @param string $password the source password
	* @param string $salt the random salt
	* @return string the derived key
	*/
	protected static function deriveKey($password, $salt)
	{
		if (function_exists('hash_pbkdf2')) {
			return hash_pbkdf2(self::DERIVATION_HASH, $password, $salt, self::DERIVATION_ITERATIONS, self::CRYPT_KEY_SIZE, true);
		}
		$hmac = hash_hmac(self::DERIVATION_HASH, $salt . pack('N', 1), $password, true);
		$xorsum  = $hmac;
		for ($i = 1; $i < self::DERIVATION_ITERATIONS; $i++) {
			$hmac = hash_hmac(self::DERIVATION_HASH, $hmac, $password, true);
			$xorsum ^= $hmac;
		}
		return substr($xorsum, 0, self::CRYPT_KEY_SIZE);
Qiang Xue committed
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
	}

	/**
	 * Prefixes data with a keyed hash value so that it can later be detected if it is tampered.
	 * @param string $data the data to be protected
	 * @param string $key the secret key to be used for generating hash
	 * @param string $algorithm the hashing algorithm (e.g. "md5", "sha1", "sha256", etc.). Call PHP "hash_algos()"
	 * function to see the supported hashing algorithms on your system.
	 * @return string the data prefixed with the keyed hash
	 * @see validateData()
	 * @see getSecretKey()
	 */
	public static function hashData($data, $key, $algorithm = 'sha256')
	{
		return hash_hmac($algorithm, $data, $key) . $data;
	}

	/**
	 * Validates if the given data is tampered.
	 * @param string $data the data to be validated. The data must be previously
	 * generated by [[hashData()]].
	 * @param string $key the secret key that was previously used to generate the hash for the data in [[hashData()]].
	 * @param string $algorithm the hashing algorithm (e.g. "md5", "sha1", "sha256", etc.). Call PHP "hash_algos()"
	 * function to see the supported hashing algorithms on your system. This must be the same
	 * as the value passed to [[hashData()]] when generating the hash for the data.
	 * @return string the real data with the hash stripped off. False if the data is tampered.
	 * @see hashData()
	 */
	public static function validateData($data, $key, $algorithm = 'sha256')
	{
167 168
		$hashSize = StringHelper::byteLength(hash_hmac($algorithm, 'test', $key));
		$n = StringHelper::byteLength($data);
Qiang Xue committed
169
		if ($n >= $hashSize) {
170 171
			$hash = StringHelper::byteSubstr($data, 0, $hashSize);
			$data2 = StringHelper::byteSubstr($data, $hashSize, $n - $hashSize);
Qiang Xue committed
172 173 174 175 176 177 178 179 180
			return $hash === hash_hmac($algorithm, $data2, $key) ? $data2 : false;
		} else {
			return false;
		}
	}

	/**
	 * Returns a secret key associated with the specified name.
	 * If the secret key does not exist, a random key will be generated
Qiang Xue committed
181
	 * and saved in the file "keys.json" under the application's runtime directory
Qiang Xue committed
182 183 184 185 186 187 188 189
	 * so that the same secret key can be returned in future requests.
	 * @param string $name the name that is associated with the secret key
	 * @param integer $length the length of the key that should be generated if not exists
	 * @return string the secret key associated with the specified name
	 */
	public static function getSecretKey($name, $length = 32)
	{
		static $keys;
Qiang Xue committed
190
		$keyFile = Yii::$app->getRuntimePath() . '/keys.json';
Qiang Xue committed
191
		if ($keys === null) {
Alexander Makarov committed
192
			$keys = [];
193
			if (is_file($keyFile)) {
Qiang Xue committed
194
				$keys = json_decode(file_get_contents($keyFile), true);
davert committed
195
			}
Qiang Xue committed
196 197
		}
		if (!isset($keys[$name])) {
198
			$keys[$name] = static::generateRandomKey($length);
Qiang Xue committed
199
			file_put_contents($keyFile, json_encode($keys));
Qiang Xue committed
200 201 202 203
		}
		return $keys[$name];
	}

204
	/**
205
	 * Generates a random key. The key may contain uppercase and lowercase latin letters, digits, underscore, dash and dot.
206 207 208 209 210 211
	 * @param integer $length the length of the key that should be generated
	 * @return string the generated random key
	 */
	public static function generateRandomKey($length = 32)
	{
		if (function_exists('openssl_random_pseudo_bytes')) {
212
			$key = strtr(base64_encode(openssl_random_pseudo_bytes($length, $strong)), '+/=', '_-.');
213 214 215 216
			if ($strong) {
				return substr($key, 0, $length);
			}
		}
217
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-.';
218 219 220
		return substr(str_shuffle(str_repeat($chars, 5)), 0, $length);
	}

Qiang Xue committed
221 222 223 224 225 226 227 228 229 230 231
	/**
	 * Opens the mcrypt module.
	 * @return resource the mcrypt module handle.
	 * @throws InvalidConfigException if mcrypt extension is not installed
	 * @throws Exception if mcrypt initialization fails
	 */
	protected static function openCryptModule()
	{
		if (!extension_loaded('mcrypt')) {
			throw new InvalidConfigException('The mcrypt PHP extension is not installed.');
		}
ekerazha committed
232
		// AES uses a 128-bit block size
ekerazha committed
233
		$module = @mcrypt_module_open('rijndael-128', '', 'cbc', '');
Qiang Xue committed
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
		if ($module === false) {
			throw new Exception('Failed to initialize the mcrypt module.');
		}
		return $module;
	}

	/**
	 * Generates a secure hash from a password and a random salt.
	 *
	 * The generated hash can be stored in database (e.g. `CHAR(64) CHARACTER SET latin1` on MySQL).
	 * Later when a password needs to be validated, the hash can be fetched and passed
	 * to [[validatePassword()]]. For example,
	 *
	 * ~~~
	 * // generates the hash (usually done during user registration or when the password is changed)
249
	 * $hash = Security::generatePasswordHash($password);
Qiang Xue committed
250 251 252
	 * // ...save $hash in database...
	 *
	 * // during login, validate if the password entered is correct using $hash fetched from database
253
	 * if (Security::validatePassword($password, $hash) {
Qiang Xue committed
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
	 *     // password is good
	 * } else {
	 *     // password is bad
	 * }
	 * ~~~
	 *
	 * @param string $password The password to be hashed.
	 * @param integer $cost Cost parameter used by the Blowfish hash algorithm.
	 * The higher the value of cost,
	 * the longer it takes to generate the hash and to verify a password against it. Higher cost
	 * therefore slows down a brute-force attack. For best protection against brute for attacks,
	 * set it to the highest value that is tolerable on production servers. The time taken to
	 * compute the hash doubles for every increment by one of $cost. So, for example, if the
	 * hash takes 1 second to compute when $cost is 14 then then the compute time varies as
	 * 2^($cost - 14) seconds.
	 * @throws Exception on bad password parameter or cost parameter
	 * @return string The password hash string, ASCII and not longer than 64 characters.
	 * @see validatePassword()
	 */
	public static function generatePasswordHash($password, $cost = 13)
	{
		$salt = static::generateSalt($cost);
		$hash = crypt($password, $salt);

		if (!is_string($hash) || strlen($hash) < 32) {
			throw new Exception('Unknown error occurred while generating hash.');
		}

		return $hash;
	}

	/**
	 * Verifies a password against a hash.
	 * @param string $password The password to verify.
	 * @param string $hash The hash to verify the password against.
	 * @return boolean whether the password is correct.
	 * @throws InvalidParamException on bad password or hash parameters or if crypt() with Blowfish hash is not available.
	 * @see generatePasswordHash()
	 */
	public static function validatePassword($password, $hash)
	{
		if (!is_string($password) || $password === '') {
			throw new InvalidParamException('Password must be a string and cannot be empty.');
		}

Qiang Xue committed
299
		if (!preg_match('/^\$2[axy]\$(\d\d)\$[\.\/0-9A-Za-z]{22}/', $hash, $matches) || $matches[1] < 4 || $matches[1] > 30) {
Qiang Xue committed
300 301 302 303 304
			throw new InvalidParamException('Hash is invalid.');
		}

		$test = crypt($password, $hash);
		$n = strlen($test);
Vladimir committed
305
		if ($n < 32 || $n !== strlen($hash)) {
Qiang Xue committed
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
			return false;
		}

		// Use a for-loop to compare two strings to prevent timing attacks. See:
		// http://codereview.stackexchange.com/questions/13512
		$check = 0;
		for ($i = 0; $i < $n; ++$i) {
			$check |= (ord($test[$i]) ^ ord($hash[$i]));
		}

		return $check === 0;
	}

	/**
	 * Generates a salt that can be used to generate a password hash.
	 *
	 * The PHP [crypt()](http://php.net/manual/en/function.crypt.php) built-in function
	 * requires, for the Blowfish hash algorithm, a salt string in a specific format:
	 * "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters
	 * from the alphabet "./0-9A-Za-z".
	 *
	 * @param integer $cost the cost parameter
	 * @return string the random salt value.
Crypt committed
329
	 * @throws InvalidParamException if the cost parameter is not between 4 and 31
Qiang Xue committed
330 331 332 333
	 */
	protected static function generateSalt($cost = 13)
	{
		$cost = (int)$cost;
334
		if ($cost < 4 || $cost > 31) {
Qiang Xue committed
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
			throw new InvalidParamException('Cost must be between 4 and 31.');
		}

		// Get 20 * 8bits of pseudo-random entropy from mt_rand().
		$rand = '';
		for ($i = 0; $i < 20; ++$i) {
			$rand .= chr(mt_rand(0, 255));
		}

		// Add the microtime for a little more entropy.
		$rand .= microtime();
		// Mix the bits cryptographically into a 20-byte binary string.
		$rand = sha1($rand, true);
		// Form the prefix that specifies Blowfish algorithm and cost parameter.
		$salt = sprintf("$2y$%02d$", $cost);
		// Append the random salt data in the required base64 format.
		$salt .= str_replace('+', '.', substr(base64_encode($rand), 0, 22));
		return $salt;
	}
ekerazha committed
354
}