@ -73,16 +73,7 @@ class Security extends Component
* Set as high as possible to hinder dictionary password attacks.
*/
public $derivationIterations = 100000;
/**
* @var string strategy, which should be used to generate password hash.
* Available strategies:
* - 'password_hash' - use of PHP `password_hash()` function with PASSWORD_DEFAULT algorithm.
* This option is recommended, but it requires PHP version >= 5.5.0
* - 'crypt' - use PHP `crypt()` function.
* @deprecated since version 2.0.7, [[generatePasswordHash()]] ignores [[passwordHashStrategy]] and
* uses `password_hash()` when available or `crypt()` when not.
*/
public $passwordHashStrategy;
/**
* @var int Default cost used for password hashing.
* Allowed value is between 4 and 31.
@ -240,13 +231,13 @@ class Security extends Component
}
$authKey = $this->hkdf($this->kdfHash, $key, null, $this->authKeyInfo, $keySize);
$data = $this->validateData(StringHelper::byteSubstr($data, $keySize, null ), $authKey);
$data = $this->validateData(StringHelper::byteSubstr($data, $keySize), $authKey);
if ($data === false) {
return false;
}
$iv = StringHelper::byteSubstr($data, 0, $blockSize);
$encrypted = StringHelper::byteSubstr($data, $blockSize, null );
$encrypted = StringHelper::byteSubstr($data, $blockSize);
$decrypted = openssl_decrypt($encrypted, $this->cipher, $key, OPENSSL_RAW_DATA, $iv);
if ($decrypted === false) {
@ -328,47 +319,9 @@ class Security extends Component
*/
public function pbkdf2($algo, $password, $salt, $iterations, $length = 0)
{
if (function_exists('hash_pbkdf2')) {
$outputKey = hash_pbkdf2($algo, $password, $salt, $iterations, $length, true);
if ($outputKey === false) {
throw new InvalidArgumentException('Invalid parameters to hash_pbkdf2()');
}
return $outputKey;
}
// todo: is there a nice way to reduce the code repetition in hkdf() and pbkdf2()?
$test = @hash_hmac($algo, '', '', true);
if (!$test) {
throw new InvalidArgumentException('Failed to generate HMAC with hash algorithm: ' . $algo);
}
if (is_string($iterations) & & preg_match('{^\d{1,16}$}', $iterations)) {
$iterations = (int) $iterations;
}
if (!is_int($iterations) || $iterations < 1 ) {
throw new InvalidArgumentException('Invalid iterations');
}
if (is_string($length) & & preg_match('{^\d{1,16}$}', $length)) {
$length = (int) $length;
}
if (!is_int($length) || $length < 0 ) {
throw new InvalidArgumentException('Invalid length');
}
$hashLength = StringHelper::byteLength($test);
$blocks = $length !== 0 ? ceil($length / $hashLength) : 1;
$outputKey = '';
for ($j = 1; $j < = $blocks; $j++) {
$hmac = hash_hmac($algo, $salt . pack('N', $j), $password, true);
$xorsum = $hmac;
for ($i = 1; $i < $iterations; $i++) {
$hmac = hash_hmac($algo, $hmac, $password, true);
$xorsum ^= $hmac;
}
$outputKey .= $xorsum;
}
if ($length !== 0) {
$outputKey = StringHelper::byteSubstr($outputKey, 0, $length);
$outputKey = hash_pbkdf2($algo, $password, $salt, $iterations, $length, true);
if ($outputKey === false) {
throw new InvalidArgumentException('Invalid parameters to hash_pbkdf2()');
}
return $outputKey;
}
@ -422,7 +375,7 @@ class Security extends Component
$hashLength = StringHelper::byteLength($test);
if (StringHelper::byteLength($data) >= $hashLength) {
$hash = StringHelper::byteSubstr($data, 0, $hashLength);
$pureData = StringHelper::byteSubstr($data, $hashLength, null );
$pureData = StringHelper::byteSubstr($data, $hashLength);
$calculatedHash = hash_hmac($this->macHash, $pureData, $key, $rawHash);
@ -433,9 +386,6 @@ class Security extends Component
return false;
}
private $_useLibreSSL;
private $_randomFile;
/**
* Generates specified number of random bytes.
* Note that output may not be ASCII.
@ -456,92 +406,7 @@ class Security extends Component
throw new InvalidArgumentException('First parameter ($length) must be greater than 0');
}
// always use random_bytes() if it is available
if (function_exists('random_bytes')) {
return random_bytes($length);
}
// The recent LibreSSL RNGs are faster and likely better than /dev/urandom.
// Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL.
// https://bugs.php.net/bug.php?id=71143
if ($this->_useLibreSSL === null) {
$this->_useLibreSSL = defined('OPENSSL_VERSION_TEXT')
& & preg_match('{^LibreSSL (\d\d?)\.(\d\d?)\.(\d\d?)$}', OPENSSL_VERSION_TEXT, $matches)
& & (10000 * $matches[1]) + (100 * $matches[2]) + $matches[3] >= 20105;
}
// Since 5.4.0, openssl_random_pseudo_bytes() reads from CryptGenRandom on Windows instead
// of using OpenSSL library. LibreSSL is OK everywhere but don't use OpenSSL on non-Windows.
if ($this->_useLibreSSL
|| (
DIRECTORY_SEPARATOR !== '/'
& & substr_compare(PHP_OS, 'win', 0, 3, true) === 0
& & function_exists('openssl_random_pseudo_bytes')
)
) {
$key = openssl_random_pseudo_bytes($length, $cryptoStrong);
if ($cryptoStrong === false) {
throw new Exception(
'openssl_random_pseudo_bytes() set $crypto_strong false. Your PHP setup is insecure.'
);
}
if ($key !== false & & StringHelper::byteLength($key) === $length) {
return $key;
}
}
// mcrypt_create_iv() does not use libmcrypt. Since PHP 5.3.7 it directly reads
// CryptGenRandom on Windows. Elsewhere it directly reads /dev/urandom.
if (function_exists('mcrypt_create_iv')) {
$key = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
if (StringHelper::byteLength($key) === $length) {
return $key;
}
}
// If not on Windows, try to open a random device.
if ($this->_randomFile === null & & DIRECTORY_SEPARATOR === '/') {
// urandom is a symlink to random on FreeBSD.
$device = PHP_OS === 'FreeBSD' ? '/dev/random' : '/dev/urandom';
// Check random device for special character device protection mode. Use lstat()
// instead of stat() in case an attacker arranges a symlink to a fake device.
$lstat = @lstat($device);
if ($lstat !== false & & ($lstat['mode'] & 0170000) === 020000) {
$this->_randomFile = fopen($device, 'rb') ?: null;
if (is_resource($this->_randomFile)) {
// Reduce PHP stream buffer from default 8192 bytes to optimize data
// transfer from the random device for smaller values of $length.
// This also helps to keep future randoms out of user memory space.
$bufferSize = 8;
if (function_exists('stream_set_read_buffer')) {
stream_set_read_buffer($this->_randomFile, $bufferSize);
}
}
}
}
if (is_resource($this->_randomFile)) {
$buffer = '';
$stillNeed = $length;
while ($stillNeed > 0) {
$someBytes = fread($this->_randomFile, $stillNeed);
if ($someBytes === false) {
break;
}
$buffer .= $someBytes;
$stillNeed -= StringHelper::byteLength($someBytes);
if ($stillNeed === 0) {
// Leaving file pointer open in order to make next generation faster by reusing it.
return $buffer;
}
}
fclose($this->_randomFile);
$this->_randomFile = null;
}
throw new Exception('Unable to generate a random key');
return random_bytes($length);
}
/**
@ -605,19 +470,7 @@ class Security extends Component
$cost = $this->passwordHashCost;
}
if (function_exists('password_hash')) {
/* @noinspection PhpUndefinedConstantInspection */
return password_hash($password, PASSWORD_DEFAULT, ['cost' => $cost]);
}
$salt = $this->generateSalt($cost);
$hash = crypt($password, $salt);
// strlen() is safe since crypt() returns only ascii
if (!is_string($hash) || strlen($hash) !== 60) {
throw new Exception('Unknown error occurred while generating hash.');
}
return $hash;
return password_hash($password, PASSWORD_DEFAULT, ['cost' => $cost]);
}
/**
@ -635,73 +488,19 @@ class Security extends Component
throw new InvalidArgumentException('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 InvalidArgumentException('Hash is invalid.');
}
if (function_exists('password_verify')) {
return password_verify($password, $hash);
}
$test = crypt($password, $hash);
$n = strlen($test);
if ($n !== 60) {
return false;
}
return $this->compareString($test, $hash);
}
/**
* 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 int $cost the cost parameter
* @return string the random salt value.
* @throws InvalidArgumentException if the cost parameter is out of the range of 4 to 31.
*/
protected function generateSalt($cost = 13)
{
$cost = (int) $cost;
if ($cost < 4 | | $ cost > 31) {
throw new InvalidArgumentException('Cost must be between 4 and 31.');
}
// Get a 20-byte random string
$rand = $this->generateRandomKey(20);
// Form the prefix that specifies Blowfish (bcrypt) 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;
return password_verify($password, $hash);
}
/**
* Performs string comparison using timing attack resistant approach.
* @see http://codereview.stackexchange.com/questions/13512
*
* @param string $expected string to compare.
* @param string $actual user-supplied string.
* @return bool whether strings are equal.
*/
public function compareString($expected, $actual)
{
$expected .= "\0";
$actual .= "\0";
$expectedLength = StringHelper::byteLength($expected);
$actualLength = StringHelper::byteLength($actual);
$diff = $expectedLength - $actualLength;
for ($i = 0; $i < $actualLength; $i++) {
$diff |= (ord($actual[$i]) ^ ord($expected[$i % $expectedLength]));
}
return $diff === 0;
return hash_equals($expected, $actual);
}
/**