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

Qiang Xue committed
8
namespace yii\helpers;
Qiang Xue committed
9

Qiang Xue committed
10
use Yii;
Qiang Xue committed
11
use yii\base\Exception;
Qiang Xue committed
12
use yii\base\InvalidConfigException;
Qiang Xue committed
13 14 15
use yii\base\InvalidParamException;

/**
Qiang Xue committed
16
 * SecurityHelper provides a set of methods to handle common security-related tasks.
Qiang Xue committed
17
 *
Qiang Xue committed
18
 * In particular, SecurityHelper supports the following features:
Qiang Xue committed
19
 *
Qiang Xue committed
20 21 22
 * - Encryption/decryption: [[encrypt()]] and [[decrypt()]]
 * - Data tampering prevention: [[hashData()]] and [[validateData()]]
 * - Password validation: [[generatePasswordHash()]] and [[validatePassword()]]
Qiang Xue committed
23
 *
Qiang Xue committed
24 25 26
 * Additionally, SecurityHelper provides [[getSecretKey()]] to support generating
 * named secret keys. These secret keys, once generated, will be stored in a file
 * and made available in future requests.
Qiang Xue committed
27
 *
Qiang Xue committed
28
 * @author Qiang Xue <qiang.xue@gmail.com>
Qiang Xue committed
29 30 31
 * @author Tom Worster <fsb@thefsb.org>
 * @since 2.0
 */
Qiang Xue committed
32
class SecurityHelper
Qiang Xue committed
33
{
Qiang Xue committed
34 35 36 37 38 39
	/**
	 * Encrypts data.
	 * @param string $data data to be encrypted.
	 * @param string $key the encryption secret key
	 * @return string the encrypted data
	 * @throws Exception if PHP Mcrypt extension is not loaded or failed to be initialized
Qiang Xue committed
40
	 * @see decrypt()
Qiang Xue committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
	 */
	public static function encrypt($data, $key)
	{
		$module = static::openCryptModule();
		$key = StringHelper::substr($key, 0, mcrypt_enc_get_key_size($module));
		srand();
		$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($module), MCRYPT_RAND);
		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.
	 * @param string $key the decryption secret key
	 * @return string the decrypted data
	 * @throws Exception if PHP Mcrypt extension is not loaded or failed to be initialized
Qiang Xue committed
61
	 * @see encrypt()
Qiang Xue committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
	 */
	public static function decrypt($data, $key)
	{
		$module = static::openCryptModule();
		$key = StringHelper::substr($key, 0, mcrypt_enc_get_key_size($module));
		$ivSize = mcrypt_enc_get_iv_size($module);
		$iv = StringHelper::substr($data, 0, $ivSize);
		mcrypt_generic_init($module, $key, $iv);
		$decrypted = mdecrypt_generic($module, StringHelper::substr($data, $ivSize, StringHelper::strlen($data)));
		mcrypt_generic_deinit($module);
		mcrypt_module_close($module);
		return rtrim($decrypted, "\0");
	}

	/**
Qiang Xue committed
77 78 79 80 81 82 83 84
	 * 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()
Qiang Xue committed
85
	 */
Qiang Xue committed
86
	public static function hashData($data, $key, $algorithm = 'sha256')
Qiang Xue committed
87
	{
Qiang Xue committed
88
		return hash_hmac($algorithm, $data, $key) . $data;
Qiang Xue committed
89 90 91
	}

	/**
Qiang Xue committed
92 93 94 95 96 97 98 99 100
	 * 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()
Qiang Xue committed
101
	 */
Qiang Xue committed
102
	public static function validateData($data, $key, $algorithm = 'sha256')
Qiang Xue committed
103
	{
Qiang Xue committed
104 105 106 107 108 109
		$hashSize = StringHelper::strlen(hash_hmac($algorithm, 'test', $key));
		$n = StringHelper::strlen($data);
		if ($n >= $hashSize) {
			$hash = StringHelper::substr($data, 0, $hashSize);
			$data2 = StringHelper::substr($data, $hashSize, $n - $hashSize);
			return $hash === hash_hmac($algorithm, $data2, $key) ? $data2 : false;
Qiang Xue committed
110 111 112 113 114
		} else {
			return false;
		}
	}

Qiang Xue committed
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
	/**
	 * Returns a secret key associated with the specified name.
	 * If the secret key does not exist, a random key will be generated
	 * and saved in the file "keys.php" under the application's runtime directory
	 * 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;
		$keyFile = Yii::$app->getRuntimePath() . '/keys.php';
		if ($keys === null) {
			$keys = is_file($keyFile) ? require($keyFile) : array();
		}
		if (!isset($keys[$name])) {
			// generate a 32-char random key
			$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
			$keys[$name] = substr(str_shuffle(str_repeat($chars, 5)), 0, $length);
			file_put_contents($keyFile, "<?php\nreturn " . var_export($keys, true) . ";\n");
		}
		return $keys[$name];
	}

Qiang Xue committed
140 141 142 143 144 145 146 147 148 149 150
	/**
	 * 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.');
		}
Qiang Xue committed
151
		$module = @mcrypt_module_open('rijndael-256', '', MCRYPT_MODE_CBC, '');
Qiang Xue committed
152 153 154 155 156 157
		if ($module === false) {
			throw new Exception('Failed to initialize the mcrypt module.');
		}
		return $module;
	}

Qiang Xue committed
158
	/**
Qiang Xue committed
159 160 161 162 163 164 165 166 167 168
	 * 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)
	 * $hash = SecurityHelper::hashPassword($password);
	 * // ...save $hash in database...
Qiang Xue committed
169
	 *
Qiang Xue committed
170 171 172 173 174 175 176
	 * // during login, validate if the password entered is correct using $hash fetched from database
	 * if (PasswordHelper::verifyPassword($password, $hash) {
	 *     // password is good
	 * } else {
	 *     // password is bad
	 * }
	 * ~~~
Qiang Xue committed
177 178 179 180 181 182 183 184 185 186 187 188
	 *
	 * @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.
Qiang Xue committed
189
	 * @see validatePassword()
Qiang Xue committed
190
	 */
Qiang Xue committed
191
	public static function generatePasswordHash($password, $cost = 13)
Qiang Xue committed
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
	{
		$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.
Qiang Xue committed
209
	 * @see generatePasswordHash()
Qiang Xue committed
210
	 */
Qiang Xue committed
211
	public static function validatePassword($password, $hash)
Qiang Xue committed
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
	{
		if (!is_string($password) || $password === '') {
			throw new InvalidParamException('Password must be a string and cannot be empty.');
		}

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

		$test = crypt($password, $hash);
		$n = strlen($test);
		if (strlen($test) < 32 || $n !== strlen($hash)) {
			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.
	 * @throws InvalidParamException if the cost parameter is not between 4 and 30
	 */
	protected static function generateSalt($cost = 13)
	{
		$cost = (int)$cost;
		if ($cost < 4 || $cost > 30) {
			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;
	}
}