Commit bb01c1cc by Alexander Makarov

Merge branch 'master' into rbac-phpmanager-adjusment

Conflicts: framework/UPGRADE.md
parents 3eee7b8e 648b9b70
......@@ -3,7 +3,7 @@ namespace common\models;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use Yii;
use yii\web\IdentityInterface;
/**
......@@ -147,7 +147,7 @@ class User extends ActiveRecord implements IdentityInterface
*/
public function validatePassword($password)
{
return Security::validatePassword($password, $this->password_hash);
return Yii::$app->getSecurity()->validatePassword($password, $this->password_hash);
}
/**
......@@ -157,7 +157,7 @@ class User extends ActiveRecord implements IdentityInterface
*/
public function setPassword($password)
{
$this->password_hash = Security::generatePasswordHash($password);
$this->password_hash = Yii::$app->getSecurity()->generatePasswordHash($password);
}
/**
......@@ -165,7 +165,7 @@ class User extends ActiveRecord implements IdentityInterface
*/
public function generateAuthKey()
{
$this->auth_key = Security::generateRandomKey();
$this->auth_key = Yii::$app->getSecurity()->generateRandomKey();
}
/**
......@@ -173,7 +173,7 @@ class User extends ActiveRecord implements IdentityInterface
*/
public function generatePasswordResetToken()
{
$this->password_reset_token = Security::generateRandomKey() . '_' . time();
$this->password_reset_token = Yii::$app->getSecurity()->generateRandomKey() . '_' . time();
}
/**
......
<?php
use yii\helpers\Security;
return [
'username' => 'userName',
'auth_key' => function ($fixture, $faker, $index) {
$fixture['auth_key'] = Security::generateRandomKey();
$fixture['auth_key'] = Yii::$app->getSecurity()->generateRandomKey();
return $fixture;
},
'password_hash' => function ($fixture, $faker, $index) {
$fixture['password_hash'] = Security::generatePasswordHash('password_' . $index);
$fixture['password_hash'] = Yii::$app->getSecurity()->generatePasswordHash('password_' . $index);
return $fixture;
},
'password_reset_token' => function ($fixture, $faker, $index) {
$fixture['password_reset_token'] = Security::generateRandomKey() . '_' . time();
$fixture['password_reset_token'] = Yii::$app->getSecurity()->generateRandomKey() . '_' . time();
return $fixture;
},
......
......@@ -350,7 +350,6 @@ Yii 2.0 introduce muchos helpers estáticos comúnmente utilizados, incluyendo:
* [[yii\helpers\StringHelper]]
* [[yii\helpers\FileHelper]]
* [[yii\helpers\Json]]
* [[yii\helpers\Security]]
Por favor, consulta la sección [Información General de Helpers](helper-overview.md) para más detalles.
......
......@@ -348,7 +348,6 @@ Yii 2.0 introduit de nombreuses assistants couramment utilisés, sous la forme d
* [[yii\helpers\StringHelper]]
* [[yii\helpers\FileHelper]]
* [[yii\helpers\Json]]
* [[yii\helpers\Security]]
Merci de lire la partie [Assistants](helper-overview.md) pour plus de détails.
......
......@@ -398,7 +398,6 @@ O Yii 2.0 introduz muitas classes de helper estáticas comumente usadas, incluin
* [[yii\helpers\StringHelper]]
* [[yii\helpers\FileHelper]]
* [[yii\helpers\Json]]
* [[yii\helpers\Security]]
Por favor consulte a seção [Visão Geral](helper-overview.md) dos helpers para mais detalhes.
......
......@@ -344,7 +344,6 @@ public function behaviors()
* [[yii\helpers\StringHelper]]
* [[yii\helpers\FileHelper]]
* [[yii\helpers\Json]]
* [[yii\helpers\Security]]
Более детальная информация представлена в разделе [Хелперы](helper-overview.md).
......
......@@ -317,7 +317,6 @@ Yii 2.0 很多常用的静态助手类,包括:
* [[yii\helpers\StringHelper]]
* [[yii\helpers\FileHelper]]
* [[yii\helpers\Json]]
* [[yii\helpers\Security]]
请参考 [助手一览](helper-overview.md) 章节来了解更多。
......
......@@ -349,7 +349,6 @@ Yii 2.0 introduces many commonly used static helper classes, including.
* [[yii\helpers\StringHelper]]
* [[yii\helpers\FileHelper]]
* [[yii\helpers\Json]]
* [[yii\helpers\Security]]
Please refer to the [Helper Overview](helper-overview.md) section for more details.
......
......@@ -65,14 +65,14 @@ class User extends ActiveRecord implements IdentityInterface
```
Two of the outlined methods are simple: `findIdentity` is provided with an ID value and returns a model instance associated with that ID. The `getId` method returns the ID itself.
Two of the other methods--`getAuthKey` and `validateAuthKey`--are used to provide extra security to the "remember me" cookie. The `getAuthKey` method should return a string that is unique for each user. You can create reliably create a unique string using `Security::generateRandomKey()`. It's a good idea to also save this as part of the user's record:
Two of the other methods--`getAuthKey` and `validateAuthKey`--are used to provide extra security to the "remember me" cookie. The `getAuthKey` method should return a string that is unique for each user. You can create reliably create a unique string using `Yii::$app->getSecurity()->generateRandomKey()`. It's a good idea to also save this as part of the user's record:
```php
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if ($this->isNewRecord) {
$this->auth_key = Security::generateRandomKey();
$this->auth_key = Yii::$app->getSecurity()->generateRandomKey();
}
return true;
}
......
......@@ -17,7 +17,7 @@ When a user provides a password for the first time (e.g., upon registration), th
```php
$hash = \yii\helpers\Security::generatePasswordHash($password);
$hash = Yii::$app->getSecurity()->generatePasswordHash($password);
```
The hash can then be associated with the corresponding model attribute, so it can be stored in the database for later use.
......@@ -26,8 +26,7 @@ When a user attempts to log in, the submitted password must be verified against
```php
use yii\helpers\Security;
if (Security::validatePassword($password, $hash)) {
if (Yii::$app->getSecurity()->validatePassword($password, $hash)) {
// all good, logging user in
} else {
// wrong password
......@@ -43,7 +42,7 @@ Yii security helper makes generating pseudorandom data simple:
```php
$key = \yii\helpers\Security::generateRandomKey();
$key = Yii::$app->getSecurity()->generateRandomKey();
```
Note that you need to have the `openssl` extension installed in order to generate cryptographically secure random data.
......@@ -57,7 +56,7 @@ For example, we need to store some information in our database but we need to ma
```php
// $data and $secretKey are obtained from the form
$encryptedData = \yii\helpers\Security::encrypt($data, $secretKey);
$encryptedData = Yii::$app->getSecurity()->encrypt($data, $secretKey);
// store $encryptedData to database
```
......@@ -65,7 +64,7 @@ Subsequently when user wants to read the data:
```php
// $secretKey is obtained from user input, $encryptedData is from the database
$data = \yii\helpers\Security::decrypt($encryptedData, $secretKey);
$data = Yii::$app->getSecurity()->decrypt($encryptedData, $secretKey);
```
Confirming data integrity
......@@ -78,14 +77,14 @@ Prefix the data with a hash generated from the secret key and data
```php
// $secretKey our application or user secret, $genuineData obtained from a reliable source
$data = \yii\helpers\Security::hashData($genuineData, $secretKey);
$data = Yii::$app->getSecurity()->hashData($genuineData, $secretKey);
```
Checks if the data integrity has been compromised
```php
// $secretKey our application or user secret, $data obtained from an unreliable source
$data = \yii\helpers\Security::validateData($data, $secretKey);
$data = Yii::$app->getSecurity()->validateData($data, $secretKey);
```
......
......@@ -69,18 +69,16 @@ After you set all needed fields in callback, you need to return $fixture array b
Another example of valid template:
```php
use yii\helpers\Security;
return [
'name' => 'firstName',
'phone' => 'phoneNumber',
'city' => 'city',
'password' => function ($fixture, $faker, $index) {
$fixture['password'] = Security::generatePasswordHash('password_' . $index);
$fixture['password'] = Yii::$app->getSecurity()->generatePasswordHash('password_' . $index);
return $fixture;
},
'auth_key' => function ($fixture, $faker, $index) {
$fixture['auth_key'] = Security::generateRandomKey();
$fixture['auth_key'] = Yii::$app->getSecurity()->generateRandomKey();
return $fixture;
},
];
......
......@@ -66,6 +66,7 @@ Yii Framework 2 Change Log
- Bug: URL encoding for the route parameter added to `\yii\web\UrlManager` (klimov-paul)
- Bug: Fixed the bug that requesting protected or private action methods would cause 500 error instead of 404 (qiangxue)
- Bug: Fixed Object of class Imagick could not be converted to string in CaptchaAction (eXprojects, cebe)
- Enh #87: Helper `yii\helpers\Security` converted into application component, cryptographic strength improved (klimov-paul)
- Enh #422: Added Support for BIT(M) data type default values in Schema (cebe)
- Enh #1452: Added `Module::getInstance()` to allow accessing the module instance from anywhere within the module (qiangxue)
- Enh #2264: `CookieCollection::has()` will return false for expired or removed cookies (qiangxue)
......
......@@ -119,4 +119,26 @@ echo "Done!\n";
```
Run it once, delete `rbac.php`. If you've configured `authFile` property, remove the line from config and instead
configure `itemsFile`, `assignmentsFile` and `rulesFile`.
\ No newline at end of file
configure `itemsFile`, `assignmentsFile` and `rulesFile`.
* Static helper `yii\helpers\Security` has been converted into an application component. You should change all usage of
its methods to a new syntax, for example: instead of `yii\helpers\Security::hashData()` use `Yii::$app->getSecurity()->hashData()`.
Default encryption and hash parameters has been upgraded. If you need to decrypt/validate data that was encrypted/hashed
before, use the following configuration of the 'security' component:
```
return [
'components' => [
'security' => [
'cryptBlockSize' => 16,
'cryptKeySize' => 24,
'derivationIterations' => 1000,
'deriveKeyStrategy' => 'hmac', // for PHP version < 5.5.0
//'deriveKeyStrategy' => 'pbkdf2', // for PHP version >= 5.5.0
'useDeriveKeyUniqueSalt' => false,
'autoGenerateSecretKey' => true,
],
// ...
],
// ...
];
```
\ No newline at end of file
......@@ -30,6 +30,7 @@ use Yii;
* read-only.
* @property string $runtimePath The directory that stores runtime files. Defaults to the "runtime"
* subdirectory under [[basePath]].
* @property \yii\base\Security $security The security application component.
* @property string $timeZone The time zone used by this application.
* @property string $uniqueId The unique ID of the module. This property is read-only.
* @property \yii\web\UrlManager $urlManager The URL manager for this application. This property is read-only.
......@@ -592,6 +593,15 @@ abstract class Application extends Module
}
/**
* Returns the security component.
* @return \yii\base\Security security component
*/
public function getSecurity()
{
return $this->get('security');
}
/**
* Returns the core application components.
* @see set
*/
......@@ -605,6 +615,7 @@ abstract class Application extends Module
'mailer' => ['class' => 'yii\swiftmailer\Mailer'],
'urlManager' => ['class' => 'yii\web\UrlManager'],
'assetManager' => ['class' => 'yii\web\AssetManager'],
'security' => ['class' => 'yii\base\Security'],
];
}
......
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
use yii\helpers\StringHelper;
use Yii;
/**
* Security provides a set of methods to handle common security-related tasks.
*
* In particular, Security supports the following features:
*
* - Encryption/decryption: [[encrypt()]] and [[decrypt()]]
* - Data tampering prevention: [[hashData()]] and [[validateData()]]
* - Password validation: [[generatePasswordHash()]] and [[validatePassword()]]
*
* Additionally, Security 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.
*
* This component provides several configuration parameters, which allow tuning your own balance
* between high security and high performance.
*
* Tip: you may add several `Security` components with different configurations to your application,
* this allows usage of different encryption strategies for different use cases or migrate encrypted data
* from outdated strategy to the new one.
*
* Note: this class requires 'mcrypt' PHP extension available, for the highest security level PHP version >= 5.5.0 required.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Tom Worster <fsb@thefsb.org>
* @author Klimov Paul <klimov.paul@gmail.com>
* @since 2.0
*/
class Security extends Component
{
/**
* @var integer crypt block size in bytes.
* For AES-128, AES-192, block size is 128-bit (16 bytes).
* For AES-256, block size is 256-bit (32 bytes).
* Recommended value: 32
*/
public $cryptBlockSize = 32;
/**
* @var integer crypt key size in bytes.
* For AES-192, key size is 192-bit (24 bytes).
* For AES-256, key size is 256-bit (32 bytes).
* Recommended value: 32
*/
public $cryptKeySize = 32;
/**
* @var string derivation hash algorithm name.
* Recommended value: 'sha256'
*/
public $derivationHash = 'sha256';
/**
* @var integer derivation iterations count.
* Recommended value: 1000000
*/
public $derivationIterations = 1000000;
/**
* @var string strategy, which should be used to derive a key for encryption.
* Available strategies:
* - 'pbkdf2' - PBKDF2 key derivation. This option is recommended, but it requires PHP version >= 5.5.0
* - 'hmac' - HMAC hash key derivation.
*/
public $deriveKeyStrategy = 'hmac';
/**
* @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.
*/
public $passwordHashStrategy = 'crypt';
/**
* @var boolean whether to generate unique salt while deriving encryption key.
* If enabled (recommended) this option increases encrypted text length, but provide more security.
* If disabled this option reduces encrypted text length, but also reduces security.
*/
public $useDeriveKeyUniqueSalt = true;
/**
* @var array list of predefined secret keys in format: keyVerboseName => keyValue
* While retrieving secret keys [[getSecretKey()]] method usage is recommended.
*/
public $secretKeys = [];
/**
* @var boolean whether to automatically generate secret key, if it is missing at [[secretKeys]] list
* while being requested via [[getSecretKey()]].
* Usage of this feature is not recommended - it is better to explicitly define list of secret keys.
* However, you may enable this option while project is in development stage to simplify generating of the keys
* list for the future explicit configuration.
* Generated keys can be found under 'runtime' application directory in 'keys.json' file.
*/
public $autoGenerateSecretKey = false;
/**
* Encrypts data.
* @param string $data data to be encrypted.
* @param string $password the encryption password
* @return string the encrypted data
* @throws Exception if PHP Mcrypt extension is not loaded or failed to be initialized
* @see decrypt()
*/
public function encrypt($data, $password)
{
$module = $this->openCryptModule();
$data = $this->addPadding($data);
$ivSize = mcrypt_enc_get_iv_size($module);
$iv = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM);
if ($this->useDeriveKeyUniqueSalt) {
$keySalt = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM);
$encrypted = $keySalt;
} else {
$keySalt = $iv;
$encrypted = '';
}
$key = $this->deriveKey($password, $keySalt);
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 $password the decryption password
* @return string the decrypted data
* @throws Exception if PHP Mcrypt extension is not loaded or failed to be initialized
* @see encrypt()
*/
public function decrypt($data, $password)
{
if ($data === null) {
return null;
}
$module = $this->openCryptModule();
$ivSize = mcrypt_enc_get_iv_size($module);
$iv = StringHelper::byteSubstr($data, 0, $ivSize);
$keySalt = $iv;
$encrypted = StringHelper::byteSubstr($data, $ivSize, StringHelper::byteLength($data));
if ($this->useDeriveKeyUniqueSalt) {
$iv = StringHelper::byteSubstr($encrypted, 0, $ivSize);
$encrypted = StringHelper::byteSubstr($encrypted, $ivSize, StringHelper::byteLength($encrypted));
}
$key = $this->deriveKey($password, $keySalt);
mcrypt_generic_init($module, $key, $iv);
$decrypted = mdecrypt_generic($module, $encrypted);
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
return $this->stripPadding($decrypted);
}
/**
* Adds a padding to the given data (PKCS #7).
* @param string $data the data to pad
* @return string the padded data
*/
protected function addPadding($data)
{
$pad = $this->cryptBlockSize - (StringHelper::byteLength($data) % $this->cryptBlockSize);
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 function stripPadding($data)
{
$end = StringHelper::byteSubstr($data, -1, null);
$last = ord($end);
$n = StringHelper::byteLength($data) - $last;
if (StringHelper::byteSubstr($data, $n, null) === str_repeat($end, $last)) {
return StringHelper::byteSubstr($data, 0, $n);
}
return false;
}
/**
* Derives a key from the given password (PBKDF2).
* @param string $password the source password
* @param string $salt the random salt
* @throws InvalidConfigException if unsupported derive key strategy is configured.
* @return string the derived key
*/
protected function deriveKey($password, $salt)
{
switch ($this->deriveKeyStrategy) {
case 'pbkdf2':
return $this->deriveKeyPbkdf2($password, $salt);
case 'hmac':
return $this->deriveKeyHmac($password, $salt);
default:
throw new InvalidConfigException("Unknown derive key strategy '{$this->deriveKeyStrategy}'");
}
}
/**
* Derives a key from the given password using PBKDF2.
* @param string $password the source password
* @param string $salt the random salt
* @throws InvalidConfigException if environment does not allows PBKDF2.
* @return string the derived key
*/
protected function deriveKeyPbkdf2($password, $salt)
{
if (function_exists('hash_pbkdf2')) {
return hash_pbkdf2($this->derivationHash, $password, $salt, $this->derivationIterations, $this->cryptKeySize, true);
} else {
throw new InvalidConfigException('Derive key strategy "pbkdf2" requires PHP >= 5.5.0, either upgrade your environment or use another strategy.');
}
}
/**
* Derives a key from the given password using HMAC.
* @param string $password the source password
* @param string $salt the random salt
* @return string the derived key
*/
protected function deriveKeyHmac($password, $salt)
{
$hmac = hash_hmac($this->derivationHash, $salt . pack('N', 1), $password, true);
$xorsum = $hmac;
for ($i = 1; $i < $this->derivationIterations; $i++) {
$hmac = hash_hmac($this->derivationHash, $hmac, $password, true);
$xorsum ^= $hmac;
}
return substr($xorsum, 0, $this->cryptKeySize);
}
/**
* 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 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 function validateData($data, $key, $algorithm = 'sha256')
{
$hashSize = StringHelper::byteLength(hash_hmac($algorithm, 'test', $key));
$n = StringHelper::byteLength($data);
if ($n >= $hashSize) {
$hash = StringHelper::byteSubstr($data, 0, $hashSize);
$pureData = StringHelper::byteSubstr($data, $hashSize, $n - $hashSize);
$calculatedHash = hash_hmac($algorithm, $pureData, $key);
if ($this->compareString($hash, $calculatedHash)) {
return $pureData;
} else {
return false;
}
} else {
return false;
}
}
/**
* Returns a secret key associated with the specified name.
* If the secret key does not exist and [[autoGenerateSecretKey]] enabled,
* a random key will be generated and saved in the file "keys.json" 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
* @throws InvalidParamException if secret key not exist and its generation is not allowed
* @return string the secret key associated with the specified name
*/
public function getSecretKey($name, $length = 32)
{
if (!array_key_exists($name, $this->secretKeys)) {
if (!$this->autoGenerateSecretKey) {
throw new InvalidParamException("Unknown secret key '{$name}'");
}
$keyFile = Yii::$app->getRuntimePath() . '/keys.json';
if (is_file($keyFile)) {
$keys = json_decode(file_get_contents($keyFile), true);
$this->secretKeys = array_merge($keys, $this->secretKeys);
}
if (!isset($this->secretKeys[$name])) {
$this->secretKeys[$name] = $this->generateRandomKey($length);
file_put_contents($keyFile, json_encode($this->secretKeys));
}
}
return $this->secretKeys[$name];
}
/**
* Generates a random key. The key may contain uppercase and lowercase latin letters, digits, underscore, dash and dot.
* Note: for delivering high security key, this method requires PHP 'mcrypt' extension.
* @param integer $length the length of the key that should be generated
* @return string the generated random key
*/
public function generateRandomKey($length = 32)
{
return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
}
/**
* 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 function openCryptModule()
{
if (!extension_loaded('mcrypt')) {
throw new InvalidConfigException('The mcrypt PHP extension is not installed.');
}
// AES version depending on crypt block size
$algorithmName = 'rijndael-' . ($this->cryptBlockSize * 8);
$module = @mcrypt_module_open($algorithmName, '', 'cbc', '');
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)
* $hash = Yii::$app->getSecurity()->generatePasswordHash($password);
* // ...save $hash in database...
*
* // during login, validate if the password entered is correct using $hash fetched from database
* if (Yii::$app->getSecurity()->validatePassword($password, $hash) {
* // 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 function generatePasswordHash($password, $cost = 13)
{
switch ($this->passwordHashStrategy) {
case 'password_hash':
if (!function_exists('password_hash')) {
throw new InvalidConfigException('Password hash key strategy "password_hash" requires PHP >= 5.5.0, either upgrade your environment or use another strategy.');
}
return password_hash($password, PASSWORD_DEFAULT, ['cost' => $cost]);
case 'crypt':
$salt = $this->generateSalt($cost);
$hash = crypt($password, $salt);
if (!is_string($hash) || strlen($hash) < 32) {
throw new Exception('Unknown error occurred while generating hash.');
}
return $hash;
default:
throw new InvalidConfigException("Unknown password hash strategy '{$this->passwordHashStrategy}'");
}
}
/**
* 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.
* @throws InvalidConfigException on unsupported password hash strategy is configured.
* @see generatePasswordHash()
*/
public function validatePassword($password, $hash)
{
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.');
}
switch ($this->passwordHashStrategy) {
case 'password_hash':
if (!function_exists('password_verify')) {
throw new InvalidConfigException('Password hash key strategy "password_hash" requires PHP >= 5.5.0, either upgrade your environment or use another strategy.');
}
return password_verify($password, $hash);
case 'crypt':
$test = crypt($password, $hash);
$n = strlen($test);
if ($n < 32 || $n !== strlen($hash)) {
return false;
}
return $this->compareString($test, $hash);
default:
throw new InvalidConfigException("Unknown password hash strategy '{$this->passwordHashStrategy}'");
}
}
/**
* 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 31
*/
protected function generateSalt($cost = 13)
{
$cost = (int) $cost;
if ($cost < 4 || $cost > 31) {
throw new InvalidParamException('Cost must be between 4 and 31.');
}
// Get 20 * 8bits of random entropy
$rand = $this->generateRandomKey(20);
// Add the microtime for a little more entropy.
$rand .= microtime(true);
// 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;
}
/**
* Performs string comparison using timing attack resistant approach.
* @see http://codereview.stackexchange.com/questions/13512
* @param string $expected string to compare.
* @param string $actual string to compare.
* @return boolean whether strings are equal.
*/
protected function compareString($expected, $actual)
{
// timing attack resistant approach:
$diff = 0;
for ($i = 0; $i < StringHelper::byteLength($actual); $i++) {
$diff |= (ord($actual[$i]) ^ ord($expected[$i]));
}
return $diff === 0;
}
}
\ No newline at end of file
......@@ -41,6 +41,7 @@ return [
'yii\base\Object' => YII_PATH . '/base/Object.php',
'yii\base\Request' => YII_PATH . '/base/Request.php',
'yii\base\Response' => YII_PATH . '/base/Response.php',
'yii\base\Security' => YII_PATH . '/base/Security.php',
'yii\base\Theme' => YII_PATH . '/base/Theme.php',
'yii\base\UnknownClassException' => YII_PATH . '/base/UnknownClassException.php',
'yii\base\UnknownMethodException' => YII_PATH . '/base/UnknownMethodException.php',
......@@ -167,7 +168,6 @@ return [
'yii\helpers\Inflector' => YII_PATH . '/helpers/Inflector.php',
'yii\helpers\Json' => YII_PATH . '/helpers/Json.php',
'yii\helpers\Markdown' => YII_PATH . '/helpers/Markdown.php',
'yii\helpers\Security' => YII_PATH . '/helpers/Security.php',
'yii\helpers\StringHelper' => YII_PATH . '/helpers/StringHelper.php',
'yii\helpers\Url' => YII_PATH . '/helpers/Url.php',
'yii\helpers\VarDumper' => YII_PATH . '/helpers/VarDumper.php',
......
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\helpers;
use Yii;
use yii\base\Exception;
use yii\base\InvalidConfigException;
use yii\base\InvalidParamException;
/**
* BaseSecurity provides concrete implementation for [[Security]].
*
* Do not use BaseSecurity. Use [[Security]] instead.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Tom Worster <fsb@thefsb.org>
* @since 2.0
*/
class BaseSecurity
{
/**
* 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;
/**
* Encrypts data.
* @param string $data data to be encrypted.
* @param string $password the encryption password
* @return string the encrypted data
* @throws Exception if PHP Mcrypt extension is not loaded or failed to be initialized
* @see decrypt()
*/
public static function encrypt($data, $password)
{
$module = static::openCryptModule();
$data = static::addPadding($data);
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($module), MCRYPT_RAND);
$key = static::deriveKey($password, $iv);
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 $password the decryption password
* @return string the decrypted data
* @throws Exception if PHP Mcrypt extension is not loaded or failed to be initialized
* @see encrypt()
*/
public static function decrypt($data, $password)
{
if ($data === null) {
return null;
}
$module = static::openCryptModule();
$ivSize = mcrypt_enc_get_iv_size($module);
$iv = StringHelper::byteSubstr($data, 0, $ivSize);
$key = static::deriveKey($password, $iv);
mcrypt_generic_init($module, $key, $iv);
$decrypted = mdecrypt_generic($module, StringHelper::byteSubstr($data, $ivSize, StringHelper::byteLength($data)));
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
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)
{
$pad = self::CRYPT_BLOCK_SIZE - (StringHelper::byteLength($data) % self::CRYPT_BLOCK_SIZE);
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)
{
$end = StringHelper::byteSubstr($data, -1, null);
$last = ord($end);
$n = StringHelper::byteLength($data) - $last;
if (StringHelper::byteSubstr($data, $n, null) == str_repeat($end, $last)) {
return StringHelper::byteSubstr($data, 0, $n);
}
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);
}
/**
* 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')
{
$hashSize = StringHelper::byteLength(hash_hmac($algorithm, 'test', $key));
$n = StringHelper::byteLength($data);
if ($n >= $hashSize) {
$hash = StringHelper::byteSubstr($data, 0, $hashSize);
$data2 = StringHelper::byteSubstr($data, $hashSize, $n - $hashSize);
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
* and saved in the file "keys.json" 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.json';
if ($keys === null) {
$keys = [];
if (is_file($keyFile)) {
$keys = json_decode(file_get_contents($keyFile), true);
}
}
if (!isset($keys[$name])) {
$keys[$name] = static::generateRandomKey($length);
file_put_contents($keyFile, json_encode($keys));
}
return $keys[$name];
}
/**
* Generates a random key. The key may contain uppercase and lowercase latin letters, digits, underscore, dash and dot.
* @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')) {
$key = strtr(base64_encode(openssl_random_pseudo_bytes($length, $strong)), '+/=', '_-.');
if ($strong) {
return substr($key, 0, $length);
}
}
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-.';
return substr(str_shuffle(str_repeat($chars, 5)), 0, $length);
}
/**
* 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.');
}
// AES uses a 128-bit block size
$module = @mcrypt_module_open('rijndael-128', '', 'cbc', '');
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)
* $hash = Security::generatePasswordHash($password);
* // ...save $hash in database...
*
* // during login, validate if the password entered is correct using $hash fetched from database
* if (Security::validatePassword($password, $hash) {
* // 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.');
}
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 ($n < 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 31
*/
protected static function generateSalt($cost = 13)
{
$cost = (int) $cost;
if ($cost < 4 || $cost > 31) {
throw new InvalidParamException('Cost must be between 4 and 31.');
}
// Get 20 * 8bits of random entropy
if (function_exists('openssl_random_pseudo_bytes')) {
// https://github.com/yiisoft/yii2/pull/2422
$rand = openssl_random_pseudo_bytes(20);
} else {
$rand = '';
for ($i = 0; $i < 20; ++$i) {
$rand .= chr(mt_rand(0, 255));
}
}
// Add the microtime for a little more entropy.
$rand .= microtime(true);
// 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;
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\helpers;
/**
* Security provides a set of methods to handle common security-related tasks.
*
* In particular, Security supports the following features:
*
* - Encryption/decryption: [[encrypt()]] and [[decrypt()]]
* - Data tampering prevention: [[hashData()]] and [[validateData()]]
* - Password validation: [[generatePasswordHash()]] and [[validatePassword()]]
*
* Additionally, Security 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.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Tom Worster <fsb@thefsb.org>
* @since 2.0
*/
class Security extends BaseSecurity
{
}
......@@ -9,7 +9,6 @@ namespace yii\web;
use Yii;
use yii\base\InvalidConfigException;
use yii\helpers\Security;
use yii\helpers\StringHelper;
/**
......@@ -1188,7 +1187,7 @@ class Request extends \yii\base\Request
if ($this->enableCookieValidation) {
$key = $this->getCookieValidationKey();
foreach ($_COOKIE as $name => $value) {
if (is_string($value) && ($value = Security::validateData($value, $key)) !== false) {
if (is_string($value) && ($value = Yii::$app->getSecurity()->validateData($value, $key)) !== false) {
$cookies[$name] = new Cookie([
'name' => $name,
'value' => @unserialize($value),
......@@ -1218,7 +1217,7 @@ class Request extends \yii\base\Request
public function getCookieValidationKey()
{
if ($this->_cookieValidationKey === null) {
$this->_cookieValidationKey = Security::getSecretKey(__CLASS__ . '/' . Yii::$app->id);
$this->_cookieValidationKey = Yii::$app->getSecurity()->getSecretKey(__CLASS__ . '/' . Yii::$app->id);
}
return $this->_cookieValidationKey;
......@@ -1323,7 +1322,7 @@ class Request extends \yii\base\Request
{
$options = $this->csrfCookie;
$options['name'] = $this->csrfParam;
$options['value'] = Security::generateRandomKey();
$options['value'] = Yii::$app->getSecurity()->generateRandomKey();
return new Cookie($options);
}
......
......@@ -12,7 +12,6 @@ use yii\base\InvalidConfigException;
use yii\base\InvalidParamException;
use yii\helpers\Url;
use yii\helpers\FileHelper;
use yii\helpers\Security;
use yii\helpers\StringHelper;
/**
......@@ -371,7 +370,7 @@ class Response extends \yii\base\Response
foreach ($this->getCookies() as $cookie) {
$value = $cookie->value;
if ($cookie->expire != 1 && isset($validationKey)) {
$value = Security::hashData(serialize($value), $validationKey);
$value = Yii::$app->getSecurity()->hashData(serialize($value), $validationKey);
}
setcookie($cookie->name, $value, $cookie->expire, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httpOnly);
}
......
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yiiunit\framework\base;
use yiiunit\TestCase;
use yii\base\Security;
/**
* @group base
*/
class SecurityTest extends TestCase
{
/**
* @var Security
*/
protected $security;
protected function setUp()
{
parent::setUp();
$this->security = new Security();
$this->security->derivationIterations = 100; // speed up test running
}
// Tests :
public function testHashData()
{
$data = 'known data';
$key = 'secret';
$hashedData = $this->security->hashData($data, $key);
$this->assertFalse($data === $hashedData);
$this->assertEquals($data, $this->security->validateData($hashedData, $key));
$hashedData[strlen($hashedData) - 1] = 'A';
$this->assertFalse($this->security->validateData($hashedData, $key));
}
/**
* Data provider for [[testPasswordHash()]]
* @return array test data
*/
public function dataProviderPasswordHash()
{
return [
[
'crypt',
false
],
[
'password_hash',
!function_exists('password_hash')
],
];
}
/**
* @dataProvider dataProviderPasswordHash
*
* @param string $passwordHashStrategy
* @param boolean $isSkipped
*/
public function testPasswordHash($passwordHashStrategy, $isSkipped)
{
if ($isSkipped) {
$this->markTestSkipped("Unable to test '{$passwordHashStrategy}' password hash strategy");
return;
}
$this->security->passwordHashStrategy = $passwordHashStrategy;
$password = 'secret';
$hash = $this->security->generatePasswordHash($password);
$this->assertTrue($this->security->validatePassword($password, $hash));
$this->assertFalse($this->security->validatePassword('test', $hash));
}
/**
* Data provider for [[testEncrypt()]]
* @return array test data
*/
public function dataProviderEncrypt()
{
return [
[
'hmac',
true,
false,
],
[
'hmac',
false,
false,
],
[
'pbkdf2',
true,
!function_exists('hash_pbkdf2')
],
[
'pbkdf2',
false,
!function_exists('hash_pbkdf2')
],
];
}
/**
* @dataProvider dataProviderEncrypt
*
* @param string $deriveKeyStrategy
* @param boolean $useDeriveKeyUniqueSalt
* @param boolean $isSkipped
*/
public function testEncrypt($deriveKeyStrategy, $useDeriveKeyUniqueSalt, $isSkipped)
{
if ($isSkipped) {
$this->markTestSkipped("Unable to test '{$deriveKeyStrategy}' derive key strategy");
return;
}
$this->security->deriveKeyStrategy = $deriveKeyStrategy;
$this->security->useDeriveKeyUniqueSalt = $useDeriveKeyUniqueSalt;
$data = 'known data';
$key = 'secret';
$encryptedData = $this->security->encrypt($data, $key);
$this->assertFalse($data === $encryptedData);
$decryptedData = $this->security->decrypt($encryptedData, $key);
$this->assertEquals($data, $decryptedData);
}
public function testGetSecretKey()
{
$this->security->autoGenerateSecretKey = false;
$keyName = 'testGet';
$keyValue = 'testGetValue';
$this->security->secretKeys = [
$keyName => $keyValue
];
$this->assertEquals($keyValue, $this->security->getSecretKey($keyName));
$this->setExpectedException('yii\base\InvalidParamException');
$this->security->getSecretKey('notExistingKey');
}
/*public function testGenerateSecretKey()
{
$this->security->autoGenerateSecretKey = true;
$keyValue = $this->security->getSecretKey('test');
$this->assertNotEmpty($keyValue);
}*/
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yiiunit\framework\helpers;
use yiiunit\TestCase;
use yii\helpers\Security;
/**
* @group helpers
*/
class SecurityTest extends TestCase
{
public function testPasswordHash()
{
$password = 'secret';
$hash = Security::generatePasswordHash($password);
$this->assertTrue(Security::validatePassword($password, $hash));
$this->assertFalse(Security::validatePassword('test', $hash));
}
public function testHashData()
{
$data = 'known data';
$key = 'secret';
$hashedData = Security::hashData($data, $key);
$this->assertFalse($data === $hashedData);
$this->assertEquals($data, Security::validateData($hashedData, $key));
$hashedData[strlen($hashedData) - 1] = 'A';
$this->assertFalse(Security::validateData($hashedData, $key));
}
public function testEncrypt()
{
$data = 'known data';
$key = 'secret';
$encryptedData = Security::encrypt($data, $key);
$this->assertFalse($data === $encryptedData);
$decryptedData = Security::decrypt($encryptedData, $key);
$this->assertEquals($data, $decryptedData);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment