Home Backend Development PHP Tutorial Analysis of csrf verification principle and token caching solution of Yii2 framework

Analysis of csrf verification principle and token caching solution of Yii2 framework

Apr 25, 2019 pm 03:20 PM
yii 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(&#39;Are you sure?&#39;)">Delete</a>
Copy after login

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 = [&#39;vote&#39;,&#39;like&#39;,&#39;delete&#39;,&#39;download&#39;];
    if(in_array($currentAction,$accessActions)) {
        $action->controller->enableCsrfValidation = true;
    }
    parent::beforeAction($action);
    return true;
}
Copy after login

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;
}
Copy after login

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 ? &#39; &#39; : $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&#39;t need to be very random
        $chars = &#39;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-.&#39;;
        $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(&#39;+&#39;, &#39;.&#39;, base64_encode($mask . $this->xorTokens($token, $mask)));
    }

    return $this->_csrfToken;
}
Copy after login

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(&#39;yii&#39;, &#39;Unable to verify your data submission.&#39;));
        }
        return true;
    }
    
    return false;
}
public function validateCsrfToken($token = null)
{
    $method = $this->getMethod();
    if (!$this->enableCsrfValidation || in_array($method, [&#39;GET&#39;, &#39;HEAD&#39;, &#39;OPTIONS&#39;], 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);
    }
}
Copy after login

Get client incoming

$this->getBodyParam($this->csrfParam)
Copy after login

Then validateCsrfTokenInternal

private function validateCsrfTokenInternal($token, $trueToken)
{
    if (!is_string($token)) {
        return false;
    }
    $token = base64_decode(str_replace(&#39;.&#39;, &#39;+&#39;, $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;
}
Copy after login

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
Copy after login

so when decrypting

token=mask^token1=mask^(token^mask)
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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 ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use Yii framework in PHP How to use Yii framework in PHP Jun 27, 2023 pm 07:00 PM

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,

Unit testing in Yii framework: ensuring code quality Unit testing in Yii framework: ensuring code quality Jun 21, 2023 am 10:57 AM

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.

RESTful API development in Yii framework RESTful API development in Yii framework Jun 21, 2023 pm 12:34 PM

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 Yii framework Steps to implement web page caching and page chunking using Yii framework Jul 30, 2023 am 09:22 AM

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

Create a game guide website using Yii framework Create a game guide website using Yii framework Jun 21, 2023 pm 01:45 PM

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.

Encrypt and decrypt sensitive data using Yii framework middleware Encrypt and decrypt sensitive data using Yii framework middleware Jul 28, 2023 pm 07:12 PM

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 your application Yii Framework Middleware: Add logging and debugging capabilities to your application Jul 28, 2023 pm 08:49 PM

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.

How to use controllers to handle Ajax requests in the Yii framework How to use controllers to handle Ajax requests in the Yii framework Jul 28, 2023 pm 07:37 PM

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

See all articles