Home >PHP Framework >ThinkPHP >Security considerations for ThinkPHP

Security considerations for ThinkPHP

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼forward
2019-12-16 17:33:423994browse

Security considerations for ThinkPHP

This article mainly discusses with you the security precautions of ThinkPHP, which can be used as the recommended security standard practice of ThinkPHP.

First of all, there is no absolute safety. As long as you have enough safety awareness, you can eliminate safety hazards as much as possible. Standard use of the framework can help you avoid some seemingly naive security issues. The security precautions described in this article mainly refer to the security strategy under the production environment. In the case of local development, sometimes security is not the first consideration for debugging.

ThinkPHP, while considering the development experience, still attaches great importance to the underlying security of the framework. Although security vulnerabilities are frequently reported, the official will fix them as soon as possible, and most of the vulnerabilities only need to be developed This can be avoided if users have a certain level of security awareness. This year, we have also established cooperative relationships with several domestic security teams, which will help to discover in advance and promptly correct vulnerabilities or hidden dangers that may be exploited in the framework.

Standardized deployment

Many developers do not pay special attention to this point. Security is an overall issue. If there is a problem in any link, the consequences will be the same. Seriously, the deployed security policy is a basic security issue.

Many developers often do not deploy according to official deployment specifications. Please be sure to point your WEB root directory to the public directory instead of the application root directory, and do not change the location of the entry file at will. Do not place other application files except entry files and resource files under the public directory.

Turn off debugging mode

When deploying to a production environment, make sure you have turned off debugging mode. You can turn off debugging mode by modifying environment variables.

APP_DEBUG=false

Whether it is local development or production environment deployment, it is not recommended to turn on/off debugging mode directly by modifying the configuration file. Instead, you should use environment variables (local development can define .env files) .

After turning off debugging mode, the health status and operation monitoring of the system mainly rely on logs or the monitoring service you use. Therefore, you must develop the habit of regularly checking logs and running status.

Request variable filtering

Never trust user input, this is a wise saying. Filtering request variables as much as possible can effectively prevent most vulnerabilities and hidden dangers.

The method recommended by the framework to obtain request variables is the param method of the Request class (do not use the get or post method to obtain it unless necessary, let alone use the native $_GET/$_POST and other methods to obtain it).

public function index(Request $request)
{
    $name = $request->param('name');
    // 在这里可以根据你的业务需求进行更严谨的过滤
    // 例如 $name = $request->param('name','','htmlentities,strtolower');
    // 或者使用验证器进行专门的验证
}

For request variables with clear types, you can use type cast when using the param method, for example:

public function index(Request $request)
{
    // 强制转换字符串数据
    $name = $request->param('name/s');
    // 强制转换整型数据
    $name = $request->param('id/d');
    // 强制转换浮点型数据
    $name = $request->param('score/f');
}

Or directly use method parameters to obtain the request variables

public function index(string $name)
{
    // 在这里可以根据你的业务需求进行更严谨的过滤
    // 或者使用验证器进行专门的验证
}

If you need to process all data, you can set a global filtering method. Set default_filter filtering rules for different application requirements (no filtering rules by default). Common security filtering functions include stripslashes, htmlentities, htmlspecialchars, strip_tags, etc. Please choose the most appropriate filtering method according to the business scenario.

If you need to obtain multiple data, it is recommended to use the only method to specify the variable name to be obtained to avoid permission issues caused by some malicious data submission.

public function index(Request $request)
{
    // 指定表单数据名称
    $data = $request->only(['name','title']);
}

When you use database or model operations to write data, you can also specify fields to avoid illegal and unwanted fields from being written to the database.

// 模型
User::allowField(['name','title'])
    ->save($data);
// 数据库
Db::name('user')
    ->field(['name','title'])
    ->insert($data);

The model also has a read-only field function that can prevent your data from being modified by the outside.

Upload detection

The upload function of the website is also a very easy entry point to be attacked, so the security check of the upload function is particularly necessary.

The system's think\File class provides security support for file uploads, including legality checks for file suffixes, file types, file sizes, and uploaded image files. Make sure you have enabled these legalities during the upload operation. For sexual examination, please refer to the upload chapter of the manual.

SQL injection

ThinkPHP's query uniformly uses PDO's prepare pre-query and parameter binding mechanism, which can effectively avoid the occurrence of SQL injection. But it does not mean that it is absolutely safe. If you lack good coding standards, you may still be exploited.

One of the simplest principles is not to let users determine your query conditions (or field sorting) and control your query data.

For some string query conditions (including native queries) or special queries (including the ORDER part), manual parameter binding is required.

// 错误的
Db::query("select * from think_user where id=$id AND status=$statis");
// 正确的
Db::query("select * from think_user where id=? AND status=?", [ $id, $status]);
// 正确的
Db::execute("update think_user set name=:name where status=:status", [
    'name'     => 'thinkphp', 
    'status'   => 1
]);

For queries using whereExp and whereRaw methods, you also need to use parameter binding.

Db::name('user')
    ->whereRaw('id > ? AND status = ?',[10, 1])
    ->select();

Use validator

For situations where a large number of forms need to be verified, it is recommended to use the validator function to uniformly verify data compliance. The validation operation of the validator should be processed using the validate method in the controller or routing stage. The data validation function of the model has been canceled in the new version and is no longer recommended. Securely processed data should be passed in when operating the model and database.

XSS attack

跨站脚本攻击(cross-site scripting,简称 XSS),XSS是一种在web应用中的计算机安全漏洞,它允许恶意web用户将代码植入到提供给其它用户使用的页面中。

在渲染输出的页面中,要对一些数据进行安全处理,防止被恶意利用造成XSS攻击,如果是5.1版本的话,所有的输出都已经经过了htmlentities 转义输出,确保安全。如果是5.0版本的话,你可以自定义一个xss过滤函数,在模板文件中对一些关键内容变量进行函数处理。

CSRF

CSRF 跨站请求伪造是 Web 应用中最常见的安全威胁之一,攻击者伪造目标用户的HTTP请求,然后此请求发送到有CSRF漏洞的网站,网站执行此请求后,引发跨站请求伪造攻击。攻击者利用隐蔽的HTTP连接,让目标用户在不注意的情况下单击这个链接,由于是用户自己点击的,而他又是合法用户拥有合法权限,所以目标用户能够在网站内执行特定的HTTP链接,从而达到攻击者的目的。

开启表单令牌验证,尽量开启强制路由并严格规范每个URL请求,定义单独的MISS路由规则。

遵循请求类型的使用规范并做好权限验证,删除操作必须使用DELETE请求,数据更改操作必须使用POST、PUT 或者 PATCH 请求方法,GET请求不应该更改任何数据。

会话劫持

会话劫持是指攻击者利用各种手段来获取目标用户的session id。一旦获取到session id,那么攻击者可以利用目标用户的身份来登录网站,获取目标用户的操作权限。

有效的防护策略包括:

在每次会话启动的时候,调用regenerate方法。

Session::start();
Session::regenerate(true);

更改session配置参数,开启安全选项:

'use_trans_sid' => 0,
'httponly' => true,
'secure' => true,

升级到安全版本

官方会对一些安全隐患和潜在漏洞进行修复,并且发布一个更为安全的版本。请确认你升级到更安全的版本,确保底层的安全和健壮性。

目前各个版本的建议版本如下:

Security considerations for ThinkPHP

业务逻辑安全

这个属于应用层面的安全,很多漏洞源于某个业务逻辑自身的安全隐患,包括没有做合理的数据验证和权限检查,尤其是涉及资金及财务层面的,一定要做更多的安全检查,并且开启事务。一个好的建议是更多的对应用进行分层设计,减少每层的复杂性,独立的分层设计便于提高安全性。

服务器安全

最后一点是运维阶段需要特别注意的,及时更新服务器的安全补丁,确保没有可利用的公开系统漏洞,包括你的数据库系统安(尤其是数据备份工作)。

PHP中文网,有大量免费的ThinkPHP入门教程,欢迎大家学习!

本文转自:https://blog.thinkphp.cn/789333

The above is the detailed content of Security considerations for ThinkPHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:thinkphp.cn. If there is any infringement, please contact admin@php.cn delete