yii2的csrf验证原理分析及token缓存解决方案

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

csrf token生成

vendor\yiisoft\yii2\web\Request.php

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

getCsrfToken方法首先会用loadCsrfToken方法尝试加载已存在的token,假诺没有则用generateCsrfToken方法再生成一个,并透过一连处理,得到终极的前台请求时引导的csrf
token。

protected function loadCsrfToken()
{
    if ($this->enableCsrfCookie) {
        return $this->getCookies()->getValue($this->csrfParam);
    } else {
        return Yii::$app->getSession()->get($this->csrfParam);
    }
}

loadCsrfToken方法会尝试从cookie或session中加载已经存在的token,enableCsrfCookie默认为true,所以一般会从cookie中得到

public function getCookies()
{
    if ($this->_cookies === null) {
        $this->_cookies = new CookieCollection($this->loadCookies(), [
            'readOnly' => true,
        ]);
    }

    return $this->_cookies;
}

那里又调用了loadCookies方法

protected function loadCookies()
    {
        $cookies = [];
        if ($this->enableCookieValidation) {
            if ($this->cookieValidationKey == '') {
                throw new InvalidConfigException(get_class($this) . '::cookieValidationKey must be configured with a secret key.');
            }
            foreach ($_COOKIE as $name => $value) {
                if (!is_string($value)) {
                    continue;
                }
                $data = Yii::$app->getSecurity()->validateData($value, $this->cookieValidationKey);
                if ($data === false) {
                    continue;
                }
                $data = @unserialize($data);
                if (is_array($data) && isset($data[0], $data[1]) && $data[0] === $name) {
                    $cookies[$name] = new Cookie([
                        'name' => $name,
                        'value' => $data[1],
                        'expire' => null,
                    ]);
                }
            }
        } else {
            foreach ($_COOKIE as $name => $value) {
                $cookies[$name] = new Cookie([
                    'name' => $name,
                    'value' => $value,
                    'expire' => null,
                ]);
            }
        }

        return $cookies;
    }

此间就是分析验证$_老板KIE中的数据。

三、总结

Yii2的做法就是儒生成一个无限制token,存入cookie中,同时在呼吁中指引随机变化的csrf
token,也是基于以前的随意token而转变的,验证的时候对cookie和csrf
token进行剖析,得到随机token举行对照,从而判断请求是不是合法。
最终,本文只是对大致的流水线举行了分析,具体的细节还请查看源码。

csrf token生成

vendor\yiisoft\yii2\web\Request.php

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

getCsrfToken方法首先会用loadCsrfToken方法尝试加载已存在的token,假设没有则用generateCsrfToken方法再生成一个,并因而持续处理,获得最终的前台请求时指引的csrf
token。

protected function loadCsrfToken()
{
    if ($this->enableCsrfCookie) {
        return $this->getCookies()->getValue($this->csrfParam);
    } else {
        return Yii::$app->getSession()->get($this->csrfParam);
    }
}

loadCsrfToken方法会尝试从cookie或session中加载已经存在的token,enableCsrfCookie默许为true,所以一般会从cookie中得到

public function getCookies()
{
    if ($this->_cookies === null) {
        $this->_cookies = new CookieCollection($this->loadCookies(), [
            'readOnly' => true,
        ]);
    }

    return $this->_cookies;
}

此处又调用了loadCookies方法

protected function loadCookies()
    {
        $cookies = [];
        if ($this->enableCookieValidation) {
            if ($this->cookieValidationKey == '') {
                throw new InvalidConfigException(get_class($this) . '::cookieValidationKey must be configured with a secret key.');
            }
            foreach ($_COOKIE as $name => $value) {
                if (!is_string($value)) {
                    continue;
                }
                $data = Yii::$app->getSecurity()->validateData($value, $this->cookieValidationKey);
                if ($data === false) {
                    continue;
                }
                $data = @unserialize($data);
                if (is_array($data) && isset($data[0], $data[1]) && $data[0] === $name) {
                    $cookies[$name] = new Cookie([
                        'name' => $name,
                        'value' => $data[1],
                        'expire' => null,
                    ]);
                }
            }
        } else {
            foreach ($_COOKIE as $name => $value) {
                $cookies[$name] = new Cookie([
                    'name' => $name,
                    'value' => $value,
                    'expire' => null,
                ]);
            }
        }

        return $cookies;
    }

那边就是分析验证$_高管KIE中的数据。

CSRF全称为“Cross-Site Request
Forgery”,是在用户合法的SESSION内发起的攻击。黑客通过在网页中放到Web恶意请求代码,并引诱被害人访问该页面,当页面被访问后,请求在被害人不知情的场地下以事主的法定地位发起,并施行黑客所梦想的动作。以下HTML代码提供了一个“删除产品”的功能:

一、CSRF

即Cross-site request
forgery跨站请求伪造,是指有人冒用你的身价进行局地恶心操作。
诸如您登录了网站A,网站A在你的处理器安装了cookie用以标识身份和景色,然后您又走访了网站B,那时候网站B就能够以假乱真你的身价在A网站开展操作,因为网站B在呼吁网站A时,浏览器会自行发送此前安装的cookie消息,让网站A误以为照旧是您在举行操作。
对此csrf的预防,一般都会放在服务器端举行,那么我们来看下Yii2中是何等举办预防的。

一、CSRF

即Cross-site request
forgery跨站请求伪造,是指有人冒充你的身价举行局地恶心操作。
譬如说您登录了网站A,网站A在你的处理器安装了cookie用以标识身份和情状,然后您又走访了网站B,那时候网站B就可以伪造你的身份在A网站开展操作,因为网站B在呼吁网站A时,浏览器会活动发送从前设置的cookie音信,让网站A误以为依旧是你在举办操作。
对此csrf的防护,一般都会放在服务器端举办,那么大家来看下Yii2中是什么开展预防的。

一、CSRF

即Cross-site request
forgery跨站请求伪造,是指有人作假你的身价举办部分黑心操作。
比如您登录了网站A,网站A在你的处理器安装了cookie用以标识身份和情景,然后您又走访了网站B,那时候网站B就可以伪造你的身份在A网站开展操作,因为网站B在央浼网站A时,浏览器会活动发送往日设置的cookie音信,让网站A误以为照旧是您在进展操作。
对于csrf的防护,一般都会放在服务器端举办,那么大家来看下Yii2中是什么样开展防患的。

1.CSRF描述

二、Yii2 CSRF

第一表明一(Wissu)下,我设置的是Yii2尖端模版。

csrf验证

vendor\yiisoft\yii2\web\Request.php

public function validateCsrfToken($token = null)
{
    $method = $this->getMethod();
    // only validate CSRF token on non-"safe" methods http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1
    if (!$this->enableCsrfValidation || in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) {
        return true;
    }

    $trueToken = $this->loadCsrfToken();

    if ($token !== null) {
        return $this->validateCsrfTokenInternal($token, $trueToken);
    } else {
        return $this->validateCsrfTokenInternal($this->getBodyParam($this->csrfParam), $trueToken)
            || $this->validateCsrfTokenInternal($this->getCsrfTokenFromHeader(), $trueToken);
    }
}

那边先验证一下伸手形式,接着获取cookie中的token,然后用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;
}

剖析呼吁指引的csrf token 举行相比较并重回结果。

csrf验证

vendor\yiisoft\yii2\web\Request.php

public function validateCsrfToken($token = null)
{
    $method = $this->getMethod();
    // only validate CSRF token on non-"safe" methods http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1
    if (!$this->enableCsrfValidation || in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) {
        return true;
    }

    $trueToken = $this->loadCsrfToken();

    if ($token !== null) {
        return $this->validateCsrfTokenInternal($token, $trueToken);
    } else {
        return $this->validateCsrfTokenInternal($this->getBodyParam($this->csrfParam), $trueToken)
            || $this->validateCsrfTokenInternal($this->getCsrfTokenFromHeader(), $trueToken);
    }
}

此间先验证一下伸手格局,接着获取cookie中的token,然后用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;
}

分析呼吁引导的csrf token 进行对照并赶回结果。

加密时用的是 str_replace('+', '.', base64_encode(mask.mask.this->xorTokens(token,token,mask))); 解密
1.率先要把.替换成+ 2.然后base64_decode 再
依照长度分别取出mask和mask和this->xorTokens(token,token,mask) ;
为了表达方便 this−>xorTokens(this−>xorTokens(token, $mask)
那里名为 token1 然后 进行mask和token1的异或运算,即得token
注意在加密时

csrf验证

vendor\yiisoft\yii2\web\Request.php

public function validateCsrfToken($token = null)
{
    $method = $this->getMethod();
    // only validate CSRF token on non-"safe" methods http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1
    if (!$this->enableCsrfValidation || in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) {
        return true;
    }

    $trueToken = $this->loadCsrfToken();

    if ($token !== null) {
        return $this->validateCsrfTokenInternal($token, $trueToken);
    } else {
        return $this->validateCsrfTokenInternal($this->getBodyParam($this->csrfParam), $trueToken)
            || $this->validateCsrfTokenInternal($this->getCsrfTokenFromHeader(), $trueToken);
    }
}

此地先验证一下呼吁格局,接着获取cookie中的token,然后用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;
}

解析呼吁率领的csrf token 举行对照并回到结果。

cookies设置

vendor\yiisoft\yii2\web\Response.php

protected function sendCookies()
{
    if ($this->_cookies === null) {
        return;
    }
    $request = Yii::$app->getRequest();
    if ($request->enableCookieValidation) {
        if ($request->cookieValidationKey == '') {
            throw new InvalidConfigException(get_class($request) . '::cookieValidationKey must be configured with a secret key.');
        }
        $validationKey = $request->cookieValidationKey;
    }
    foreach ($this->getCookies() as $cookie) {
        $value = $cookie->value;
        if ($cookie->expire != 1  && isset($validationKey)) {
            $value = Yii::$app->getSecurity()->hashData(serialize([$cookie->name, $value]), $validationKey);
        }
        setcookie($cookie->name, $value, $cookie->expire, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httpOnly);
    }
}

send库克ies方法应用cookieValidationKey对cookie举办一多重处理,重假如为了得到的时候举办验证,防止cookie被歪曲。

public function getCookies()
{
    if ($this->_cookies === null) {
        $this->_cookies = new CookieCollection;
    }
    return $this->_cookies;
}

此处的get库克ies方法跟request中的分化,并不会从$_COOKIE中获取,_cookies属性在request中的generateCsrfToken方法中有举行安装

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

二、Yii2 CSRF

先是说惠氏(WYETH)下,我设置的是Yii2高等模版。

附录:

cookies设置

vendor\yiisoft\yii2\web\Response.php

protected function sendCookies()
{
    if ($this->_cookies === null) {
        return;
    }
    $request = Yii::$app->getRequest();
    if ($request->enableCookieValidation) {
        if ($request->cookieValidationKey == '') {
            throw new InvalidConfigException(get_class($request) . '::cookieValidationKey must be configured with a secret key.');
        }
        $validationKey = $request->cookieValidationKey;
    }
    foreach ($this->getCookies() as $cookie) {
        $value = $cookie->value;
        if ($cookie->expire != 1  && isset($validationKey)) {
            $value = Yii::$app->getSecurity()->hashData(serialize([$cookie->name, $value]), $validationKey);
        }
        setcookie($cookie->name, $value, $cookie->expire, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httpOnly);
    }
}

sendCookies方法运用cookieValidationKey对cookie举行一四种处理,首若是为着取得的时候举办说明,防止cookie被歪曲。

public function getCookies()
{
    if ($this->_cookies === null) {
        $this->_cookies = new CookieCollection;
    }
    return $this->_cookies;
}

那边的get库克ies方法跟request中的分化,并不会从$_COOKIE中获取,_cookies属性在request中的generateCsrfToken方法中有举办安装

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

二、Yii2 CSRF

首先说雅培(Abbott)(Karicare)下,我设置的是Yii2高级模版。

三、总结

Yii2的做法就是儒生成一个擅自token,存入cookie中,同时在伸手中指点随机变化的csrf
token,也是根据此前的即兴token而生成的,验证的时候对cookie和csrf
token举行分析,得到随机token进行相比较,从而判断请求是或不是合法。
说到底,本文只是对大约的流水线展开了分析,具体的底细还请查看源码。

str_shuffle() 函数打乱一个字符串,使用其它一种可能的排序方案。

三、总结

Yii2的做法就是贡士成一个擅自token,存入cookie中,同时在乞求中带走随机生成的csrf
token,也是依据从前的自由token而变更的,验证的时候对cookie和csrf
token举行解析,获得随机token举行对照,从而判断请求是或不是合法。
最终,本文只是对几乎的流水线举办了分析,具体的底细还请查看源码。

csrf token生成

vendor\yiisoft\yii2\web\Request.php

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

getCsrfToken方法首先会用loadCsrfToken方法尝试加载已存在的token,借使没有则用generateCsrfToken方法再生成一个,并因而一连处理,得到最后的前台请求时带领的csrf
token。

protected function loadCsrfToken()
{
    if ($this->enableCsrfCookie) {
        return $this->getCookies()->getValue($this->csrfParam);
    } else {
        return Yii::$app->getSession()->get($this->csrfParam);
    }
}

loadCsrfToken方法会尝试从cookie或session中加载已经存在的token,enableCsrfCookie默许为true,所以一般会从cookie中得到

public function getCookies()
{
    if ($this->_cookies === null) {
        $this->_cookies = new CookieCollection($this->loadCookies(), [
            'readOnly' => true,
        ]);
    }

    return $this->_cookies;
}

此间又调用了loadCookies方法

protected function loadCookies()
    {
        $cookies = [];
        if ($this->enableCookieValidation) {
            if ($this->cookieValidationKey == '') {
                throw new InvalidConfigException(get_class($this) . '::cookieValidationKey must be configured with a secret key.');
            }
            foreach ($_COOKIE as $name => $value) {
                if (!is_string($value)) {
                    continue;
                }
                $data = Yii::$app->getSecurity()->validateData($value, $this->cookieValidationKey);
                if ($data === false) {
                    continue;
                }
                $data = @unserialize($data);
                if (is_array($data) && isset($data[0], $data[1]) && $data[0] === $name) {
                    $cookies[$name] = new Cookie([
                        'name' => $name,
                        'value' => $data[1],
                        'expire' => null,
                    ]);
                }
            }
        } else {
            foreach ($_COOKIE as $name => $value) {
                $cookies[$name] = new Cookie([
                    'name' => $name,
                    'value' => $value,
                    'expire' => null,
                ]);
            }
        }

        return $cookies;
    }

这里就是分析验证$_CEOKIE中的数据。

cookies设置

vendor\yiisoft\yii2\web\Response.php

protected function sendCookies()
{
    if ($this->_cookies === null) {
        return;
    }
    $request = Yii::$app->getRequest();
    if ($request->enableCookieValidation) {
        if ($request->cookieValidationKey == '') {
            throw new InvalidConfigException(get_class($request) . '::cookieValidationKey must be configured with a secret key.');
        }
        $validationKey = $request->cookieValidationKey;
    }
    foreach ($this->getCookies() as $cookie) {
        $value = $cookie->value;
        if ($cookie->expire != 1  && isset($validationKey)) {
            $value = Yii::$app->getSecurity()->hashData(serialize([$cookie->name, $value]), $validationKey);
        }
        setcookie($cookie->name, $value, $cookie->expire, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httpOnly);
    }
}

sendCookies方法运用cookieValidationKey对cookie举行一多级处理,重假如为着博取的时候举行表明,防止cookie被篡改。

public function getCookies()
{
    if ($this->_cookies === null) {
        $this->_cookies = new CookieCollection;
    }
    return $this->_cookies;
}

那里的getCookies方法跟request中的分歧,并不会从$_COOKIE中获取,_cookies属性在request中的generateCsrfToken方法中有进展安装

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

因为yii2 csrf的验证的加解密
涉及到异或运算

str_pad(),该函数重临 input
被从左端、右端或者同时两端被填充到制定长度后的结果。如果可选的
pad_string 参数没有被指定,input 将被空格字符填充,否则它将被
pad_string 填充到指定长度;

在controller.php里调用request.php里的validateCsrfToken方法

在控制器里将enableCsrfValidation为true,则控制器内所有操作都会敞开验证,平常做法是将enableCsrfValidation为false,而将一些机警操作设为true,开启局地验证。

发表评论

电子邮件地址不会被公开。 必填项已用*标注