


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!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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.

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software