ThinkPHP3.1 quick start (16) Security

Source: Internet
Author: User
In the development process, in addition to ensuring that the business logic has no security risks, we should fully understand and use the built-in security mechanisms or tools of the framework to ensure the security of applications and servers, next we will summarize the security mechanisms involved in ThinkPHP. In the development process, in addition to ensuring that the business logic has no security risks, we should fully understand and use the built-in security mechanisms or tools of the framework to ensure the security of applications and servers, next we will summarize the security mechanisms involved in ThinkPHP.

System security system security refers to the security deployment policy of the server that ThinkPHP can work. We recommend that you deploy the framework directory and project directory under the non-WEB access directory as allowed, the access mechanism of ThinkPHP fully supports non-WEB directory access of frameworks and projects. you only need to set the entry file and resources (mainly JS, style, and image files) the directory is placed under the WEB directory. Therefore, the recommended deployment directory is as follows:
  1. Index. php project entry file
  2. Public/Project Resource file directory
  3. Js/JS Directory
  4. Css/style file directory
  5. Images/Image file directory
  6. Protected/(protected directory, which can be deployed to a non-WEB directory or set secure access)
  7. ThinkPHP/framework system directory
  8. App/Project directory
  9. Uploads/project Upload Directory
Copy code system security settings If you have configured secure access to the system directory through the deployment policy, skip this section.
If you cannot fully implement the preceding server directory security protection, you do not need to worry about it. ThinkPHP can still ensure the security of your Directory through settings. The core file of the framework has been accessed, and all core files cannot be accessed directly in the URL, therefore, you do not need to worry about exposing information such as your server path due to errors caused by direct access to some files.
For the application directory, the system provides a secure directory access mechanism. you can add the following content to the entry file before the project directory structure is generated for the first time:
  1. Define ('build _ DIR_SECURE ', true );
After you copy the code to run the project, a directory security file is automatically generated for the project's related directories (a blank htm file is generated under the related directories ), you can also customize the security file name DIR_SECURE_FILENAME, which is index.html. if you want to define your security file as default.html, you can use
  1. Define ('dir _ SECURE_FILENAME ', 'default.html ');
The replication code also supports writing multiple security files. for example, if you want to write index.html and index.htm files at the same time to meet different server deployment environments, you can define them as follows:
  1. Define ('dir _ SECURE_FILENAME ', 'index.html,index.htm ');
The default security file of the copied code only writes a blank string. to write other content, you can specify it using the DIR_SECURE_CONTENT parameter. for example:
  1. Define ('dir _ SECURE_CONTENT ', 'deney Access! ');
Copy the code. The following is a complete example of using secure directory writing.
  1. Define ('build _ DIR_SECURE ', true );
  2. Define ('dir _ SECURE_FILENAME ', 'index.html ');
  3. Define ('dir _ SECURE_CONTENT ', 'deney Access! ');
In addition to directory security, the copy code also needs to protect the template file from direct access, because it may expose the field information of the data table in the template file. The solution is to configure the. htaccess file (for Apache servers, refer to modify other servers) and save the following code in the template directory of the project (Tpl by default) as. htaccess.
  1. Order Allow, Deny
  2. Deny from all
Copy the code. if your template file suffix is not html, you can change *. html to the suffix of your template file.

Automatic form security verification and automatic completion of ThinkPHP built-in automatic verification and automatic completion can effectively control the data security of form submission. These two sections have been described in detail in the quick start series and will not be described. Form token ThinkPHP has built-in form token verification function, which can effectively prevent repeated submission of forms and other security protection.
Configuration parameters related to form token verification include:
  1. 'Token _ on' => true, // whether to enable TOKEN verification disabled by default
  2. 'Token _ name' => '_ hash _', // NAME of the hidden field in the form for TOKEN verification
  3. 'Token _ type' => 'md5', // The default TOKEN hash verification rule is md5.
  4. 'Token _ reset' => true, // whether to RESET the TOKEN after the TOKEN verification fails. the default value is true.
If the form token verification function is enabled, the system automatically generates a hidden field named TOKEN_NAME in the template file with the form. The value is a hash string generated in TOKEN_TYPE mode, used for automatic token verification of forms.
The automatically generated hidden fields are located before the Form end mark. if you want to manually control the hidden fields, you can manually add the {__ TOKEN __} identifier on the Form page, the system will automatically replace the output template.
If multiple forms exist on the page, we recommend that you add the {__token __} identifier and ensure that only one form requires TOKEN verification.
If some page outputs do not require form token verification, you can dynamically disable form token verification before the output method in the controller. for example:
  1. C ('token _ on', false );
  2. $ This-> display ();
The copy code model class automatically performs form token verification when creating data objects. if you do not use the create method to create data objects, you must manually call the autoCheckToken method of the model to verify the form token. If false is returned, the form token verification is incorrect. For example:
  1. $ User = M ("User"); // instantiate the User object
  2. // Manually perform token verification
  3. If (! $ User-> autoCheckToken ($ _ POST )){
  4. // Token verification error
  5. }
Copy code form validity check the form validity check is a new form submission field detection mechanism introduced in version 3.1. you no longer need to worry about injecting illegal field data when submitting a form. The validity check of form fields takes effect only when the create method is used to create data objects. There are two methods: 1. you can configure the insertFields and updateFields attributes for the model to add and edit form settings, when you use the create method to create a data object, attributes that are not within the defined scope will be discarded directly to avoid illegal data submission by forms.
The insertFields and updateFields attributes are set using strings (multiple fields are separated by commas) or arrays, for example:
  1. Class UserModel extends Model {
  2. Protected $ insertFields = array ('account', 'password', 'nickname', 'Email ');
  3. Protected $ updateFields = array ('nickname', 'Email ');
  4. }
The field set in the copy code is the actual data table field, which is not affected by field ING.
When we call the create method, the insertFields and updateFields attributes are automatically identified based on the submission type:
  1. D ('user')-> create ();
When the Copy code uses the create method to create a data object, when new user data is added, fields other than 'account', 'password', 'nickname', and 'Email 'are blocked, during editing, fields other than 'nickname' and 'Email 'are blocked.
The following is a string definition method, which is also valid:
  1. Class UserModel extends Model {
  2. Protected $ insertFields = 'account, password, nickname, email ';
  3. Protected $ updateFields = 'Nickname, email ';
  4. }
Copy code 2. if you do not want to define the attributes of insertFields and updateFields, or want to call them dynamically, you can directly call the field method before calling the create method. for example, the implementation has the same effect as the above example:
When adding user data, use:
  1. $ User = M ('user ');
  2. $ User-> field ('account, password, nickname, email ')-> create ();
  3. $ User-> add ();
When copying code and updating user data, use:
  1. $ User = M ('user ');
  2. $ User-> field ('Nick name, email ')-> create ();
  3. $ User-> where ($ map)-> save ();
Copy the code. the fields here are also the actual data table fields. The field method can also use the array method.
If you have many fields, you can also use the field exclusion function, for example:
  1. $ User-> field ('status, create_time ', true)-> create ();
Copy code
It is recommended that you use the variables provided by the system to obtain global system variables, for more information, see global variable filtering in the quick start series. if you are used to directly calling the $ _ GET $ _ POST variable, you can also use the built-in security filtering method for global variables in ThinkPHP. you only need to set the VAR_FILTERS parameter.
For example:
  1. 'Var _ FILTERS '=> 'htmlspecialchars'
Starting from version 3.1.2, the definition function of the security filtering method needs to be adjusted to the reference return method, and can implement recursive filtering of multi-dimensional arrays, for example:
  1. 'Var _ FILTERS '=> 'filter _ VARs'
The filtering method corresponding to the copied code is defined as follows:
  1. Function filter_vars (& $ value ){
  2. $ Value = htmlspecialchars ($ value );
  3. }
Copy code
Data security protection against SQL injection for WEB applications, SQL injection attacks are undoubtedly the primary security issue. The system underlying layer handles a lot of data security and corresponding defense mechanisms, for example:
  1. $ User = M ("User"); // instantiate the User object
  2. $ User-> find ($ _ GET ["id"]);
Copy code
Even if the user inputs some malicious id parameters, the system will forcibly convert them into integers to avoid malicious injection. This is because the system checks the data type forcibly and converts the data format of the data source. In addition, ThinkPHP performs escape_string processing on string-type data.
The common security risk is that your query conditions use string parameters, and some of the variables are dependent on user input from the client. to effectively prevent SQL injection problems, we recommend that:
The query conditions should use arrays as much as possible, which is a safer method;
If you have to use string query conditions, use the preprocessing mechanism. when the where method of query condition preprocessing uses string conditions, the pre-processing (secure filtering) and pre-processing parameters can be input in two ways, for example:
  1. $ Model-> where ("id = % d and username = '% s' and xx =' % f'", array ($ id, $ username, $ xx )) -> select ();
Copy the code or
  1. $ Model-> where ("id = % d and username = '% s' and xx =' % f'", $ id, $ username, $ xx) -> select ();
The query and execute methods for copying code models also support preprocessing, for example:
  1. $ Model-> query ('select * from user where id = % d and status = % d', $ id, $ status );
Copy the code or
  1. $ Model-> query ('select * from user where id = % d and status = % d', array ($ id, $ status ));
The copy code execute method is used in the same way as the query method. XSS (cross-site scripting) attacks can be used to steal Cookie information of other users. to avoid such problems, the following solutions can be used:
Filter all JavaScript scripts directly;
Escape Html metacharacters and use functions such as htmlentities and htmlspecialchars;
The extended function library of the system provides the remove_xss method for XSS security filtering;
Some system variables for URL access have been processed by XSS in the new version.

The upload function of the upload security website is also a very vulnerable Portal. Therefore, security checks on the upload function are particularly necessary.
The upload extension Class Library (ORG. net. uploadFile) provides security support, including checking the file suffix, file type, file size, and the validity of the uploaded image file to ensure that you have enabled these validity checks during the upload operation.

Other security suggestions are also important:
Perform necessary security checks on all public operation methods to prevent users from directly calling them through URLs;
Do not cache pages that require user authentication;
Check user permissions for key operations;
Perform necessary security checks on uploaded files, such as upload paths and illegal formats.
If not necessary, do not enable the directory browsing permission of the server;
Do not generate security risks of business logic (this may be the biggest security problem) when performing full tests on projects );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.