search
HomePHP FrameworkThinkPHPSecurity considerations for ThinkPHP
Security considerations for ThinkPHPDec 16, 2019 pm 05:33 PM
thinkphpSafety Precautions

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官网. If there is any infringement, please contact admin@php.cn delete
thinkphp是不是国产框架thinkphp是不是国产框架Sep 26, 2022 pm 05:11 PM

thinkphp是国产框架。ThinkPHP是一个快速、兼容而且简单的轻量级国产PHP开发框架,是为了简化企业级应用开发和敏捷WEB应用开发而诞生的。ThinkPHP从诞生以来一直秉承简洁实用的设计原则,在保持出色的性能和至简的代码的同时,也注重易用性。

一起聊聊thinkphp6使用think-queue实现普通队列和延迟队列一起聊聊thinkphp6使用think-queue实现普通队列和延迟队列Apr 20, 2022 pm 01:07 PM

本篇文章给大家带来了关于thinkphp的相关知识,其中主要介绍了关于使用think-queue来实现普通队列和延迟队列的相关内容,think-queue是thinkphp官方提供的一个消息队列服务,下面一起来看一下,希望对大家有帮助。

thinkphp的mvc分别指什么thinkphp的mvc分别指什么Jun 21, 2022 am 11:11 AM

thinkphp基于的mvc分别是指:1、m是model的缩写,表示模型,用于数据处理;2、v是view的缩写,表示视图,由View类和模板文件组成;3、c是controller的缩写,表示控制器,用于逻辑处理。mvc设计模式是一种编程思想,是一种将应用程序的逻辑层和表现层进行分离的方法。

实例详解thinkphp6使用jwt认证实例详解thinkphp6使用jwt认证Jun 24, 2022 pm 12:57 PM

本篇文章给大家带来了关于thinkphp的相关知识,其中主要介绍了使用jwt认证的问题,下面一起来看一下,希望对大家有帮助。

thinkphp 怎么查询库是否存在thinkphp 怎么查询库是否存在Dec 05, 2022 am 09:40 AM

thinkphp查询库是否存在的方法:1、打开相应的tp文件;2、通过“ $isTable=db()->query('SHOW TABLES LIKE '."'".$data['table_name']."'");if($isTable){...}else{...}”方式验证表是否存在即可。

thinkphp扩展插件有哪些thinkphp扩展插件有哪些Jun 13, 2022 pm 05:45 PM

thinkphp扩展有:1、think-migration,是一种数据库迁移工具;2、think-orm,是一种ORM类库扩展;3、think-oracle,是一种Oracle驱动扩展;4、think-mongo,一种MongoDb扩展;5、think-soar,一种SQL语句优化扩展;6、porter,一种数据库管理工具;7、tp-jwt-auth,一个jwt身份验证扩展包。

一文教你ThinkPHP使用think-queue实现redis消息队列一文教你ThinkPHP使用think-queue实现redis消息队列Jun 28, 2022 pm 03:33 PM

本篇文章给大家带来了关于ThinkPHP的相关知识,其中主要整理了使用think-queue实现redis消息队列的相关问题,下面一起来看一下,希望对大家有帮助。

thinkphp3.2怎么关闭调试模式thinkphp3.2怎么关闭调试模式Apr 25, 2022 am 10:13 AM

在thinkphp3.2中,可以利用define关闭调试模式,该标签用于变量和常量的定义,将入口文件中定义调试模式设为FALSE即可,语法为“define('APP_DEBUG', false);”;开启调试模式将参数值设置为true即可。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment