当前位置:编程学习 > 网站相关 >>

How to write secure Yii applications

目录

[-]

  1. General principles
  2. Validating the user input
    1. How it works
    2. Client-side validation
    3. How Yii can help
      1. Validating through a model
        1. To go further
      2. Validating in a controller
        1. Side note on the last example
      3. HTML output and XSS
        1. Example
        2. How Yii can help
          1. Plain text
          2. Rich text HTML
            1. To go further
          3. Special cases URLs CSS etc
            1. URL
          4. CSS
          5. JavaScript
        3. SQL Injections
          1. How it works
          2. How Yii can help
            1. Use a PHP syntax instead of raw SQL
            2. Prepared statements
              1. Side note on LIKE conditions
              2. Side note on positional parameters
              3. Side note on performance
            3. When prepared statements arent enough
          3. Summary on SQL injection
        4. Cross-site Request Forgery CSRF
        5. Configure the web server
          1. Set up different environments
          2. For a Yii application
          3. For every PHP project
        6. Authorization
        7. Authentication
          1. Password strength
          2. Encrypting passwords
        8. Useful Tools
 

http://www.yiiframework.com/wiki/275/how-to-write-secure-yii-applications

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

http://yjlblog.com/yii%e6%a1%86%e6%9e%b6%e5%bc%80%e5%8f%91%e5%ae%89%e5%85%a8%e8%80%83%e8%99%91/

warning:   While this security guide  tries to be quite complete, is not exhaustive.  If security matters for you, you ought to check several other references.

General principles ¶

  • Validate the user input (see below for details).
  • Protect (escape) your application output according to context (see below for a few output types, mostly HTML and SQL).
  • Test your application in debug mode.
    Set the constant YII_DEBUG to true (by default, it is defined in index.php) and put alongside error_reporting(E_ALL);. Then errors and warnings will stop the execution and Yii will display the message, the source code and the call stack. Even an undefined key in an array (which is just a "E_NOTICE" level) can cause security problems.
  • Disable the debug mode in production.
    Make sure your error messages don't contain sensitive information.
  • Whenever possible, filter by white-list instead of by black-list, i.e. allow only data that is in an authorized list.
  • In production, keep logs. Parse them regularly for warnings and errors.
    There are two levels of logs : application logs (handled by Yii) and server logs (handled by PHP and usually Apache). Yii logs are described inThe Definitive Guide to Yii, Logging. PHP logs are usually on by default. Please check your server configuration and your rights on the file system for accessing these log files.

Validating the user input ¶

How it works ¶

If a user can add its birth date to its profile, you have to make sure he gives a valid date. It's not only helpful to prevent mistypes, it also provides better security. Verifying the input is in the form "1951-01-25" will forbid dangerous texts that try to attack your database's SQL or your website's HTML. Validation is not a perfect protection, but it's an excellent first step.

Client-side validation ¶

Validating a form with JavaScript has absolutely no impact on the security! It should only be meant as a way to enhance the interface and its comfort of use.

The HTML restriction are the same. For instance, if a page has a form containing:

<input type="hidden" name="id" value="1" />
<input type="text" name="date" size="10" />
<select name="list"><option>1option><option>2option>select>

The data received in the PHP application can contain anything. The "id", "date" and "list" fields can be big strings or arrays. For example, a user can modify the HTML source of the page to replace both fields by text areas.

How Yii can help ¶

Yii provides specific ways that can be used instead or along the usual PHP ways. For reference, the recommended way without Yii is mostly to use type casts and theFilter extension.

Validating through a model

Most of the times, the user input will be sent to a model. Models will generally extendCFormModel or CActiveRecord. Both of them derive from the classCModel. This class has a methodrules() that declares how the validation will process. The additional tests can be done with behaviors or thebeforeValidate() method.

The controller:


// In the controller
$model = new Comment;
$model->attributes = $_POST['Comment'];
if ($model->save()) { // validates and save
    $this->redirect(array('view', 'id' => $model->id));
} else {
    // Could not validate, or could not save
}

The model:


// In the model
class Comment extends CActiveRecord
{
    public function rules()
    {
        return array(
            array('parent', 'numerical', 'integerOnly' => true),
            array('strangedata', 'customValidateForStrangedata'),
            array('description', 'length', 'max' => 255),
        );
    }
 
    // extended validation, run before the rules set above
    protected function beforeValidate()
        if (!empty($this->description) && substr_count($this->description, '"') % 2 !== 0) {
            $this->addError("description", "Odd number of quotes");
            // return false; // stop validation
        }
        return parent::beforeValidate();
    }
 
    /** @return boolean Continue the validation process? */
    protected function customValidateForStrangedata($attribute, $params)
    {
        $this->addError($attribute, "validation failed");
        return false;
    }

You should pay extra care to your validation. It keeps your data clean, and that not only useful for security. Many kind of rules are already declared, and you can add your own. You can also apply some rules only in a given context, e.g. validate a field only when the record is modified ("up

补充:综合编程 , 安全编程 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,