Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #87: security helper converted into component and improved #4089

Merged
merged 19 commits into from Jun 28, 2014
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
db0beb6
'yii\base\Security' component created.
klimov-paul Jun 27, 2014
54ac875
Component 'security' added tp the base application
klimov-paul Jun 27, 2014
2bab625
'Security' helper usage switched to 'security' application component.
klimov-paul Jun 27, 2014
63c7a4c
Docs regarding `Security` component usage updated.
klimov-paul Jun 27, 2014
e6f7d9b
Security helper files removed
klimov-paul Jun 27, 2014
c86db26
Notes about `Security` class refactoring added to CHANGELOG.md and UP…
klimov-paul Jun 27, 2014
47f8eaf
Doc comments at `yii\base\Security` fixed
klimov-paul Jun 27, 2014
0daf67d
Extra namespace at docs removed
klimov-paul Jun 27, 2014
4a47a59
Upgrade not about `Security` component adjusted
klimov-paul Jun 27, 2014
4768dcd
Method `Security::compareString()` extracted
klimov-paul Jun 27, 2014
8465962
Fallback for `Security::generateRandomKey()` added
klimov-paul Jun 27, 2014
4063502
Option `Security::deriveKeyStrategy` added
klimov-paul Jun 27, 2014
4ce4707
Option `Security::passwordHashStrategy` added
klimov-paul Jun 27, 2014
772667f
Doc comments at `Security` updated
klimov-paul Jun 27, 2014
5a42985
Option `Security::useDeriveKeyUniqueSalt` added
klimov-paul Jun 27, 2014
25a3637
Upgrade note about `Security` updated
klimov-paul Jun 27, 2014
052ae83
Option `Security::autoGenerateSecretKey` added
klimov-paul Jun 27, 2014
69abbc7
Fallback at `Security::generateRandomKey()` removed
klimov-paul Jun 28, 2014
84cbf19
Doc comments at `Security::generateRandomKey()` adjusted
klimov-paul Jun 28, 2014
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 5 additions & 5 deletions apps/advanced/common/models/User.php
Expand Up @@ -3,7 +3,7 @@

use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use Yii;
use yii\web\IdentityInterface;

/**
Expand Down Expand Up @@ -147,7 +147,7 @@ public function validateAuthKey($authKey)
*/
public function validatePassword($password)
{
return Security::validatePassword($password, $this->password_hash);
return Yii::$app->getSecurity()->validatePassword($password, $this->password_hash);
}

/**
Expand All @@ -157,23 +157,23 @@ public function validatePassword($password)
*/
public function setPassword($password)
{
$this->password_hash = Security::generatePasswordHash($password);
$this->password_hash = Yii::$app->getSecurity()->generatePasswordHash($password);
}

/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Security::generateRandomKey();
$this->auth_key = Yii::$app->getSecurity()->generateRandomKey();
}

/**
* Generates new password reset token
*/
public function generatePasswordResetToken()
{
$this->password_reset_token = Security::generateRandomKey() . '_' . time();
$this->password_reset_token = Yii::$app->getSecurity()->generateRandomKey() . '_' . time();
}

/**
Expand Down
8 changes: 3 additions & 5 deletions apps/advanced/common/tests/templates/fixtures/user.php
@@ -1,21 +1,19 @@
<?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;
},
Expand Down
1 change: 0 additions & 1 deletion docs/guide-es/intro-upgrade-from-v1.md
Expand Up @@ -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.

Expand Down
1 change: 0 additions & 1 deletion docs/guide-fr/intro-upgrade-from-v1.md
Expand Up @@ -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.

Expand Down
1 change: 0 additions & 1 deletion docs/guide-pt-BR/intro-upgrade-from-v1.md
Expand Up @@ -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.

Expand Down
1 change: 0 additions & 1 deletion docs/guide-ru/intro-upgrade-from-v1.md
Expand Up @@ -344,7 +344,6 @@ public function behaviors()
* [[yii\helpers\StringHelper]]
* [[yii\helpers\FileHelper]]
* [[yii\helpers\Json]]
* [[yii\helpers\Security]]

Более детальная информация представлена в разделе [Хелперы](helper-overview.md).

Expand Down
1 change: 0 additions & 1 deletion docs/guide-zh-CN/intro-upgrade-from-v1.md
Expand Up @@ -317,7 +317,6 @@ Yii 2.0 很多常用的静态助手类,包括:
* [[yii\helpers\StringHelper]]
* [[yii\helpers\FileHelper]]
* [[yii\helpers\Json]]
* [[yii\helpers\Security]]

请参考 [助手一览](helper-overview.md) 章节来了解更多。

Expand Down
1 change: 0 additions & 1 deletion docs/guide/intro-upgrade-from-v1.md
Expand Up @@ -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.

Expand Down
4 changes: 2 additions & 2 deletions docs/guide/security-authentication.md
Expand Up @@ -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;
}
Expand Down
15 changes: 7 additions & 8 deletions docs/guide/security-passwords.md
Expand Up @@ -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.
Expand All @@ -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
Expand All @@ -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.
Expand All @@ -57,15 +56,15 @@ 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
```

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
Expand All @@ -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);
```


Expand Down
6 changes: 2 additions & 4 deletions extensions/faker/README.md
Expand Up @@ -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;
},
];
Expand Down
1 change: 1 addition & 0 deletions framework/CHANGELOG.md
Expand Up @@ -65,6 +65,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)
Expand Down
18 changes: 18 additions & 0 deletions framework/UPGRADE.md
Expand Up @@ -72,3 +72,21 @@ Upgrade from Yii 2.0 Beta

* `mail` component was renamed to `mailer`, `yii\log\EmailTarget::$mail` was renamed to `yii\log\EmailTarget::$mailer`.
Please update all references in the code and config files.

* 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,
],
// ...
],
// ...
];
```
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could add another note:

You may configure two components 'legacySecurity' and 'security' with different configurations to use the legacy component to deal with values encrypted with the old class.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes but insert "and re-encrypt/re-hash using the 'security' component" at end.

11 changes: 11 additions & 0 deletions framework/base/Application.php
Expand Up @@ -30,6 +30,7 @@
* 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.
Expand Down Expand Up @@ -591,6 +592,15 @@ public function getAssetManager()
return $this->get('assetManager');
}

/**
* Returns the security component.
* @return \yii\base\Security security component
*/
public function getSecurity()
{
return $this->get('security');
}

/**
* Returns the core application components.
* @see set
Expand All @@ -605,6 +615,7 @@ public function coreComponents()
'mailer' => ['class' => 'yii\swiftmailer\Mailer'],
'urlManager' => ['class' => 'yii\web\UrlManager'],
'assetManager' => ['class' => 'yii\web\AssetManager'],
'security' => ['class' => 'yii\base\Security'],
];
}

Expand Down