使われているのは phpass というパスワードハッシングフレームワークです (PHPフレームワーク関連なら CodeIgniter のライブラリ Tank_Auth にも採用されていますね) 。パスワードのセキュリティについて自分はあまり詳しくないので、以下に役に立ちそうなリンクを載せておきます。
- なぜPHPアプリにセキュリティホールが多いのか?
- ハッシュとソルト、ストレッチングを正しく理解する。「本当は怖いパスワードの話」
- SlideShare 徳丸本に学ぶ 安全なPHPアプリ開発の鉄則2011
- Ustream 徳丸本に学ぶ 安全なPHPアプリ開発の鉄則 2011
- CakePHP Authコンポーネントでパスワード・ハッシュをストレッチングするには?
- パスワードにストレッチングは必要か。
- Rails(Web)アプリケーションのセキュリティ(パスワードハッシュstretch編)
上記のリンクを参考にしつつ、今回紹介されている Wiki の記事と照らし合わせて、ユーザ登録と、ログイン機能を実装していきます。
まず こちら から最新バージョンの phpass を DL、解凍して、protected/extensions 下に設置。続いて、protected/config/main.php に以下を追加。
(Yii の Wiki の記事とは異なり params の部分は array() を一つ省いています)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
... | |
'import' => array( | |
... | |
'ext.PasswordHash', | |
), | |
... | |
'params' => array( | |
'iteration_count_log2' => 12, | |
'portable_hashes' => false, | |
), | |
... |
portable_hashes は true の場合、ハッシュ関数に md5 が使われ、false の場合、CRYPT_BLOWFISH, CRYPE_EXT_DESC, md5の順に試されます。
では、ログイン機能から作ってみます。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class UserIdentity extends CUserIdentity | |
{ | |
private $id; | |
public function authenticate() | |
{ | |
$model = User::model()->findByAttributes(array( | |
'username' => $this->username, | |
)); | |
$ph = new PasswordHash( | |
Yii::app()->params['iteration_count_log2'], | |
Yii::app()->params['portable_hashes'] | |
); | |
if (!$model) { | |
$this->errorCode = self::ERROR_USERNAME_INVALID; | |
} else if (!$ph->CheckPassword($this->password, $model->password)) { | |
$this->errorCode = self::ERROR_PASSWORD_INVALID; | |
} else { | |
$this->id = $model->id; | |
$this->errorCode = self::ERROR_NONE; | |
} | |
return !$this->errorCode; | |
} | |
public function getId() | |
{ | |
return $this->id; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class User extends CActiveRecord | |
{ | |
public $password2; | |
... | |
public function rules() | |
{ | |
return array( | |
... | |
array('password', 'compare', 'compareAttribute'=>'password2', 'message'=>'{attribute} とパスワード(確認)が一致しません。', 'on'=>'register'), | |
... | |
); | |
} | |
protected function beforeSave() | |
{ | |
$ph = new PasswordHash( | |
Yii::app()->params['iteration_count_log2'], | |
Yii::app()->params['portable_hashes'] | |
); | |
$this->password = $ph->HashPassword($this->password); | |
... | |
return parent::beforeSave(); | |
} | |
} |
0 件のコメント:
コメントを投稿