Home  >  Article  >  Backend Development  >  Analysis of csrf verification principle and token caching solution of Yii2 framework

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

little bottle
little bottleforward
2019-04-25 15:20:012241browse

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>

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;
}

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 ? &#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;
}

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);
    }
}

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(&#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;
}

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!

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