


Analysis of csrf verification principle and token caching solution of Yii2 framework
This article is mainly divided into three parts. First, we briefly introduce csrf, then focus on analyzing the verification principle of the yii framework based on the source code, and finally propose a feasible solution for token caching caused by page caching. The knowledge points involved will be attached as an appendix at the end of the article. Interested friends can find out.
1.CSRF description
CSRF stands for "Cross-Site Request Forgery" and is an attack launched within the user's legitimate SESSION. Hackers embed malicious web request code in web pages and lure victims to access the page. When the page is accessed, the request is initiated in the victim's legal identity without the victim's knowledge, and the hacker's expected actions are performed. . The following HTML code provides a "delete product" function:
<a href="http://www.shop.com/delProducts.php?id=100" "javascript:return confirm('Are you sure?')">Delete</a>
Assuming that the programmer does not perform corresponding legality verification on the "delete product" request in the background, as long as the user accesses If this link is used, the corresponding product will be deleted. Then the hacker can deceive the victim into visiting a web page with the following malicious code, and then delete the corresponding product without the victim's knowledge.
2.yii’s csrf verification principle/vendor/yiisoft/yii2/web/Request.php is abbreviated as Request.php
/vendor /yiisoft/yii2/web/Controller.php is abbreviated as Controller.php
Enable csrf verification
Set enableCsrfValidation to true in the controller , then all operations in the controller will enable verification. The usual approach is to set enableCsrfValidation to false, and set some sensitive operations to true to enable partial verification.
public $enableCsrfValidation = false; /** * @param \yii\base\Action $action * @return bool * @desc: 局部开启csrf验证(重要的表单提交必须加入验证,加入$accessActions即可 */ public function beforeAction($action){ $currentAction = $action->id; $accessActions = ['vote','like','delete','download']; if(in_array($currentAction,$accessActions)) { $action->controller->enableCsrfValidation = true; } parent::beforeAction($action); return true; }
Generate token field
In Request.php
First obtain it through the security component Security A 32-bit random string and stored in a cookie or session. This is the native token.
/** * Generates an unmasked random token used to perform CSRF validation. * @return string the random token for CSRF validation. */ protected function generateCsrfToken() { $token = Yii::$app->getSecurity()->generateRandomString(); if ($this->enableCsrfCookie) { $cookie = $this->createCsrfCookie($token); Yii::$app->getResponse()->getCookies()->add($cookie); } else { Yii::$app->getSession()->set($this->csrfParam, $token); } return $token; }
Then through a series of encryption replacement operations, the encrypted _csrfToken is generated. This is The token passed to the browser. First randomly generate the CSRF_MASK_LENGTH (default is 8 bits in Yii2) length string mask
Perform the following operation on the mask and token str_replace(' ' , '.', base64_encode($mask . $this->xorTokens($token, $mask))); $this->xorTokens($arg1,$arg2)
is a fill-first XOR operation
/** * Returns the XOR result of two strings. * If the two strings are of different lengths, the shorter one will be padded to the length of the longer one. * @param string $token1 * @param string $token2 * @return string the XOR result */ private function xorTokens($token1, $token2) { $n1 = StringHelper::byteLength($token1); $n2 = StringHelper::byteLength($token2); if ($n1 > $n2) { $token2 = str_pad($token2, $n1, $token2); } elseif ($n1 < $n2) { $token1 = str_pad($token1, $n2, $n1 === 0 ? ' ' : $token1); } return $token1 ^ $token2; } public function getCsrfToken($regenerate = false) { if ($this->_csrfToken === null || $regenerate) { if ($regenerate || ($token = $this->loadCsrfToken()) === null) { $token = $this->generateCsrfToken(); } // the mask doesn't need to be very random $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-.'; $mask = substr(str_shuffle(str_repeat($chars, 5)), 0, static::CSRF_MASK_LENGTH); // The + sign may be decoded as blank space later, which will fail the validation $this->_csrfToken = str_replace('+', '.', base64_encode($mask . $this->xorTokens($token, $mask))); } return $this->_csrfToken; }
Verification token
Call the validateCsrfToken method in request.php in controller.php
/** * @inheritdoc */ public function beforeAction($action) { if (parent::beforeAction($action)) { if ($this->enableCsrfValidation && Yii::$app->getErrorHandler()->exception === null && !Yii::$app->getRequest()->validateCsrfToken()) { throw new BadRequestHttpException(Yii::t('yii', 'Unable to verify your data submission.')); } return true; } return false; } public function validateCsrfToken($token = null) { $method = $this->getMethod(); if (!$this->enableCsrfValidation || in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) { return true; } $trueToken = $this->loadCsrfToken();//如果开启了enableCsrfCookie,CsrfToken就从cookie里取,否者从session里取(更安全) if ($token !== null) { return $this->validateCsrfTokenInternal($token, $trueToken); } else { return $this->validateCsrfTokenInternal($this->getBodyParam($this->csrfParam), $trueToken) || $this->validateCsrfTokenInternal($this->getCsrfTokenFromHeader(), $trueToken); } }
Get client incoming
$this->getBodyParam($this->csrfParam)
Then validateCsrfTokenInternal
private function validateCsrfTokenInternal($token, $trueToken) { if (!is_string($token)) { return false; } $token = base64_decode(str_replace('.', '+', $token)); $n = StringHelper::byteLength($token); if ($n <= static::CSRF_MASK_LENGTH) { return false; } $mask = StringHelper::byteSubstr($token, 0, static::CSRF_MASK_LENGTH); $token = StringHelper::byteSubstr($token, static::CSRF_MASK_LENGTH, $n - static::CSRF_MASK_LENGTH); $token = $this->xorTokens($mask, $token); return $token === $trueToken; }
Used for encryption str_replace(' ', '.', base64_encode(mask.mask.this->xorTokens(token,token,mask)));
Decryption 1. First replace . with 2. Then base64_decode and then take out mask and mask respectively according to the length. this->xorTokens(token,token,mask) ; For the convenience of explanation this->xorTokens(this->xorTokens(token, $mask) is called token1 and then perform the XOR operation of mask and token1 to get token Note that when encrypting
token1=token^mask
so when decrypting
token=mask^token1=mask^(token^mask)
3.Token caching solution
When the entire page is cached, the token is also cached, causing verification to fail. A common solution is to re-obtain the token before each submission, so that the verification can pass.
Appendix:
str_pad()
, this function returns the result after the input is padded to the specified length from the left end, the right end, or both ends at the same time. If the optional pad_string parameter is not specified, the input will be filled with space characters, otherwise it will be filled with pad_string to the specified length;
str_shuffle()
function Shuffle a string using any possible sorting scheme.
Because the encryption and decryption of yii2 csrf verification involves the XOR operation
, so you need to first add the relevant string XOR operation in PHP Knowledge, if you don’t need it, you can skip it
^If the XOR operation is different, it will return 1, otherwise it will return 0. In the PHP language, it is often used for encryption operations, and decryption is also directly used^ When performing string operations, the ascii code of the character is converted into binary to perform single character operations
1. For single characters and single characters, the results can be directly calculated as shown in the table a^b
2. For multiple strings of the same length such as ab^cd in the table, calculate the result corresponding to a^c and the characters corresponding to the result corresponding to b^d connect them
Related tutorials: PHP video tutorial
The above is the detailed content of Analysis of csrf verification principle and token caching solution of Yii2 framework. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

With the rapid development of web applications, modern web development has become an important skill. Many frameworks and tools are available for developing efficient web applications, among which the Yii framework is a very popular framework. Yii is a high-performance, component-based PHP framework that uses the latest design patterns and technologies, provides powerful tools and components, and is ideal for building complex web applications. In this article, we will discuss how to use Yii framework to build web applications. Install Yii framework first,

As software development becomes increasingly complex, ensuring code quality becomes increasingly important. In the Yii framework, unit testing is a very powerful tool that can ensure the correctness and stability of the code. In this article, we will take a deep dive into unit testing in the Yii framework and introduce how to use the Yii framework for unit testing. What is unit testing? Unit testing is a software testing method, usually used to test the correctness of a module, function or method. Unit tests are usually written by developers to ensure the correctness and stability of the code.

Yii is a high-performance MVC framework based on PHP. It provides a very rich set of tools and functions to support the rapid and efficient development of web applications. Among them, the RESTful API function of the Yii framework has attracted more and more attention and love from developers, because using the Yii framework can easily build high-performance and easily scalable RESTful interfaces, providing strong support for the development of web applications. . Introduction to RESTfulAPI RESTfulAPI is a

Steps to implement web page caching and page chunking using the Yii framework Introduction: During the web development process, in order to improve the performance and user experience of the website, it is often necessary to cache and chunk the page. The Yii framework provides powerful caching and layout functions, which can help developers quickly implement web page caching and page chunking. This article will introduce how to use the Yii framework to implement web page caching and page chunking. 1. Turn on web page caching. In the Yii framework, web page caching can be turned on through the configuration file. Open the main configuration file co

In recent years, with the rapid development of the game industry, more and more players have begun to look for game strategies to help them pass the game. Therefore, creating a game guide website can make it easier for players to obtain game guides, and at the same time, it can also provide players with a better gaming experience. When creating such a website, we can use the Yii framework for development. The Yii framework is a web application development framework based on the PHP programming language. It has the characteristics of high efficiency, security, and strong scalability, and can help us create a game guide more quickly and efficiently.

Encrypting and decrypting sensitive data using Yii framework middleware Introduction: In modern Internet applications, privacy and data security are very important issues. To ensure that users' sensitive data is not accessible to unauthorized visitors, we need to encrypt this data. The Yii framework provides us with a simple and effective way to implement the functions of encrypting and decrypting sensitive data. In this article, we’ll cover how to achieve this using the Yii framework’s middleware. Introduction to Yii framework Yii framework is a high-performance PHP framework.

Yii framework middleware: Add logging and debugging capabilities to applications [Introduction] When developing web applications, we usually need to add some additional features to improve the performance and stability of the application. The Yii framework provides the concept of middleware that enables us to perform some additional tasks before and after the application handles the request. This article will introduce how to use the middleware function of the Yii framework to implement logging and debugging functions. [What is middleware] Middleware refers to the processing of requests and responses before and after the application processes the request.

In the Yii framework, controllers play an important role in processing requests. In addition to handling regular page requests, controllers can also be used to handle Ajax requests. This article will introduce how to handle Ajax requests in the Yii framework and provide code examples. In the Yii framework, processing Ajax requests can be carried out through the following steps: The first step is to create a controller (Controller) class. You can inherit the basic controller class yiiwebCo provided by the Yii framework
