Yii 安全性

  • XSS 攻擊
    Yii 的教學文章提到很多做法,基本上都是使用 CHtmlPurifier 來過濾,只是做的時間點不同,有的是save之前,有的是display之前,建議寫在 Model 的 rules 使用 filter 濾掉,不要每次打開頁面時在view裡頭做,浪費效能。

Model

public function rules(){
    return array(
        array('text','filter','filter'=>array($obj=new CHtmlPurifier(), 'purify'))
    );
}

config/main.php
加上 httponly 避免 cookie 被 javascript 讀取

'components'=>array(           
    'user'=>array(
        // enable cookie-based authentication
        'class' => 'WebUser',
        'allowAutoLogin' => true,
        'identityCookie' => array('domain' => 'www.abc.com', 'path' => '/', 'httpOnly' => true),
        'loginUrl' => array('site/top2login'),
    ),
    'session' => array(
        'cookieParams' => array(
            'httponly' => true,  //o小寫
        ),
    ),
),

 

  • SQL Injections
    若是使用 model 本身的方法來操作,並不需要特別注意這個問題,因為Yii 自己會進行處理,風險通常來自於自己寫SQL時,針對這點處理方式如下
$sql = "SELECT CONCAT(prefix, title) AS title, author_id, post_id, date "
    . "FROM t_comment "
    . "WHERE (date > :date OR date IS NULL) AND title LIKE :text"
 
$command = Yii::app()->db->createCommand($sql);
$results = $command->execute(array(':date' => $date, ':text' => "%{$text}%"));

使用 model 搭配 SQL 的變數處理

$comments = Comment::model->findAllBySql($sql, array(':date' => $date, ':text' => "%{$text}%"));

 

  • Cross-site Request Forgery (CSRF)
    !! 使用 Yii cookie 組件來操作 cookie,不要使用 $_COOKIES
    !! 使用 CHtml::form 建立表單,不要自己寫 Html form tag

config/main.php

'request'=>array(
    'enableCsrfValidation'=>true,  //CHtml::form
    'enableCookieValidation'=>true,//CHttpCookie
    'csrfCookie'=>array(
        'httpOnly'=>true,  //O大寫
    ),
),

 

參考
http://www.yiiframework.com/doc/guide/1.1/zh_cn/topics.security

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *