Browse Source

Merge pull request #16502 from cakephp/3.x-csrf-string-salt

Use random string not bytes for CSRF token salt
Mark Story 3 years ago
parent
commit
c816b3eb98

+ 1 - 1
src/Http/Middleware/CsrfProtectionMiddleware.php

@@ -190,7 +190,7 @@ class CsrfProtectionMiddleware
      */
     public function createToken()
     {
-        $value = Security::randomBytes(static::TOKEN_VALUE_LENGTH);
+        $value = Security::randomString(static::TOKEN_VALUE_LENGTH);
         if (!$this->_config['verifyTokenSource']) {
             return hash('sha512', $value, false);
         }

+ 3 - 0
tests/TestCase/Http/Middleware/CsrfProtectionMiddlewareTest.php

@@ -87,6 +87,7 @@ class CsrfProtectionMiddlewareTest extends TestCase
             $this->assertEquals(0, $cookie['expire'], 'session duration.');
             $this->assertEquals('/dir/', $cookie['path'], 'session path.');
             $this->assertEquals($cookie['value'], $request->getParam('_csrfToken'));
+            $this->assertRegExp('/^[a-z0-9]+$/', $cookie['value']);
         };
 
         $middleware = new CsrfProtectionMiddleware();
@@ -199,6 +200,8 @@ class CsrfProtectionMiddlewareTest extends TestCase
     {
         $middleware = new CsrfProtectionMiddleware(['verifyTokenSource' => true]);
         $token = $middleware->createToken();
+        $this->assertRegexp('/^[a-z0-9]+$/', $token, 'Token should not have unencoded binary data.');
+
         $request = new ServerRequest([
             'environment' => [
                 'REQUEST_METHOD' => $method,