Skip to content

[Security] Randomize CSRF token to harden BREACH attacks #39919

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ public function testFormLoginAndLogoutWithCsrfTokens($options)
$logoutLinks = $crawler->selectLink('Log out')->links();
$this->assertCount(2, $logoutLinks);
$this->assertStringContainsString('_csrf_token=', $logoutLinks[0]->getUri());
$this->assertSame($logoutLinks[0]->getUri(), $logoutLinks[1]->getUri());

$client->click($logoutLinks[0]);

Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/Security/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ CHANGELOG
5.3
---

* Randomize CSRF tokens to harden BREACH attacks
* Deprecated voters that do not return a valid decision when calling the `vote` method.

5.2.0
Expand Down
35 changes: 32 additions & 3 deletions src/Symfony/Component/Security/Csrf/CsrfTokenManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public function getToken(string $tokenId)
$this->storage->setToken($namespacedId, $value);
}

return new CsrfToken($tokenId, $value);
return new CsrfToken($tokenId, $this->randomize($value));
}

/**
Expand All @@ -90,7 +90,7 @@ public function refreshToken(string $tokenId)

$this->storage->setToken($namespacedId, $value);

return new CsrfToken($tokenId, $value);
return new CsrfToken($tokenId, $this->randomize($value));
}

/**
Expand All @@ -111,11 +111,40 @@ public function isTokenValid(CsrfToken $token)
return false;
}

return hash_equals($this->storage->getToken($namespacedId), $token->getValue());
return hash_equals($this->storage->getToken($namespacedId), $this->derandomize($token->getValue()));
}

private function getNamespace(): string
{
return \is_callable($ns = $this->namespace) ? $ns() : $ns;
}

private function randomize(string $value): string
{
$key = random_bytes(32);
$value = $this->xor($value, $key);

return sprintf('%s.%s.%s', substr(md5($key), 0, 1 + (\ord($key[0]) % 32)), rtrim(strtr(base64_encode($key), '+/', '-_'), '='), rtrim(strtr(base64_encode($value), '+/', '-_'), '='));
}

private function derandomize(string $value): string
{
$parts = explode('.', $value);
if (3 !== \count($parts)) {
return $value;
}
$key = base64_decode(strtr($parts[1], '-_', '+/'));
$value = base64_decode(strtr($parts[2], '-_', '+/'));

return $this->xor($value, $key);
}

private function xor(string $value, string $key): string
{
if (\strlen($value) > \strlen($key)) {
$key = str_repeat($key, ceil(\strlen($value) / \strlen($key)));
}

return $value ^ $key;
}
}
54 changes: 50 additions & 4 deletions src/Symfony/Component/Security/Csrf/Tests/CsrfTokenManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public function testGetNonExistingToken($namespace, $manager, $storage, $generat

$this->assertInstanceOf(CsrfToken::class, $token);
$this->assertSame('token_id', $token->getId());
$this->assertSame('TOKEN', $token->getValue());
$this->assertNotSame('TOKEN', $token->getValue());
}

/**
Expand All @@ -66,7 +66,34 @@ public function testUseExistingTokenIfAvailable($namespace, $manager, $storage)

$this->assertInstanceOf(CsrfToken::class, $token);
$this->assertSame('token_id', $token->getId());
$this->assertSame('TOKEN', $token->getValue());
$this->assertNotSame('TOKEN', $token->getValue());
}

/**
* @dataProvider getManagerGeneratorAndStorage
*/
public function testRandomizeTheToken($namespace, $manager, $storage)
{
$storage->expects($this->any())
->method('hasToken')
->with($namespace.'token_id')
->willReturn(true);

$storage->expects($this->any())
->method('getToken')
->with($namespace.'token_id')
->willReturn('TOKEN');

$values = [];
$lengths = [];
for ($i = 0; $i < 10; ++$i) {
$token = $manager->getToken('token_id');
$values[] = $token->getValue();
$lengths[] = \strlen($token->getValue());
}

$this->assertCount(10, array_unique($values));
$this->assertGreaterThan(2, \count(array_unique($lengths)));
}

/**
Expand All @@ -89,13 +116,33 @@ public function testRefreshTokenAlwaysReturnsNewToken($namespace, $manager, $sto

$this->assertInstanceOf(CsrfToken::class, $token);
$this->assertSame('token_id', $token->getId());
$this->assertSame('TOKEN', $token->getValue());
$this->assertNotSame('TOKEN', $token->getValue());
}

/**
* @dataProvider getManagerGeneratorAndStorage
*/
public function testMatchingTokenIsValid($namespace, $manager, $storage)
{
$storage->expects($this->exactly(2))
->method('hasToken')
->with($namespace.'token_id')
->willReturn(true);

$storage->expects($this->exactly(2))
->method('getToken')
->with($namespace.'token_id')
->willReturn('TOKEN');

$token = $manager->getToken('token_id');
$this->assertNotSame('TOKEN', $token->getValue());
$this->assertTrue($manager->isTokenValid($token));
}

/**
* @dataProvider getManagerGeneratorAndStorage
*/
public function testMatchingTokenIsValidWithLegacyToken($namespace, $manager, $storage)
{
$storage->expects($this->once())
->method('hasToken')
Expand Down Expand Up @@ -170,7 +217,6 @@ public function testNamespaced()

$token = $manager->getToken('foo');
$this->assertSame('foo', $token->getId());
$this->assertSame('random', $token->getValue());
}

public function getManagerGeneratorAndStorage()
Expand Down