Skip to content

[Security] Added Security\Csrf sub-component with better token generation #6554

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 6 commits into from
Sep 30, 2013

Conversation

webmozart
Copy link
Contributor

Q A
Bug fix? yes
New feature? no
BC breaks? no
Deprecations? no
Tests pass? yes
Fixed tickets -
License MIT
Doc PR TODO

Update September 27, 2013

This PR simplifies the CSRF mechanism to generate completely random tokens. A random token is generated once per intention token ID and then stored in the session. Tokens are valid until the session expires.

Since the CSRF token generator depends on StringUtils and SecureRandom from Security\Core, and since Security\Http currently depends on the Form component for token generation, I decided to add a new Security\Csrf sub-component that contains the improved CSRF token generator. Consequences:

  • Security\Http now depends on Security\Csrf instead of Form
  • Form now optionally depends on Security\Csrf
  • The configuration for the "security.secure_random" service and the "security.csrf.*" services was moved to FrameworkBundle to guarantee BC

In the new Security\Csrf sub-component, I tried to improve the naming where I could do so without breaking BC:

  • CSRF "providers" are now called "token generators"
  • CSRF "intentions" are now called "token IDs", because that's really what they are
TODO
  • Make sure SecureRandom never blocks for CsrfTokenGenerator

*
* @see http://blog.ircmaxell.com/2012/12/seven-ways-to-screw-up-bcrypt.html
*/
private function timingSafeEquals($a, $b) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This method should be removed as it is unused

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also if you do need such a method it's already present in Symfony\Component\Security\Core\Util\StringUtils

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

which is currently used, if you check the code ;)

@mvrhov
Copy link

mvrhov commented Jan 4, 2013

IMO we do not need cryptographic safe tokens here.
What I'm afraid of is emptying a entropy pretty quickly. Now when there is no more entropy the application WILL block.
This could pose a big problem on a busy server. AFAIK only a couple of bytes of entropy s generated each second.

@vicb
Copy link
Contributor

vicb commented Jan 5, 2013

@mvrhov good catch! This could indeed slow the server pretty badly (I was not aware of the problem until I read a forum post explaining why Android sometimes lags - same root cause)

@webmozart
Copy link
Contributor Author

@mvrhov I made the tokens URI safe now.

@vicb
Copy link
Contributor

vicb commented Jan 7, 2013

Backwards compatibility break: no

Really ?

@padraic
Copy link

padraic commented Jan 7, 2013

@mvrhov You're correct, the randomness need not be very cryptographically secure. The CSRF token is already a sub-unit of a randomly generated session ID though even that has some predictive weaknesses (needs better entropy) due to be improved in PHP 5.4.

The options currently in favour are to use openssl_pseudo_random_bytes() under PHP 5.3.4+ or fall back to a (concatenated) token generated using mt_rand(). Neither is, as far as I'm aware, blocking and mt_rand() is better than you'd expect if Suhosin is installed. I think openssl seeds itself using /dev/urandom intelligently (i.e. the non-blocking but lower entropy partner to /dev/random).

Only thing you have to watch for is that openssl's random functions were blocking under Windows due to an openssl bug. This was fixed but you should avoid using openssl_pseudo_random_bytes() under PHP 5.3.3 or less and go straight to mt_rand().

CSRF tokens need to be random - just not as crazily random as if we needed a high value long-term key :P.

@webmozart
Copy link
Contributor Author

Postponed to 2.3

@vicb
Copy link
Contributor

vicb commented Jan 8, 2013

@bschussek I have created a 2.3 milestone, you can set it in the PR header (which I've done for this one).

@webmozart
Copy link
Contributor Author

Thanks! :)

@webmozart
Copy link
Contributor Author

I'm currently trying to get this into 2.3. I'm not sure which way to go though:

(a) As is, plus a new parameter $blocking in SecureRandomInterface:
public function nextBytes($nbBytes, $blocking = true)

This parameter would guarantee a non-blocking behavior when set to false (at the cost of cryptographic security).

Advantage: SecureRandom can be reused
Disadvantage: dependency on the Security component in Form and FrameworkBundle

(b) Copy code from SecureRandom and StringUtil to AbstractCsrfProvider

The code in question is:

// initialize seed
if (null === $this->seed) {
    if (null === $this->seedFile) {
        throw new \RuntimeException('You need to specify a file path to store the seed.');
    }

    if (is_file($this->seedFile)) {
        list($this->seed, $this->seedLastUpdatedAt) = $this->readSeed();
    } else {
        $this->seed = uniqid(mt_rand(), true);
        $this->updateSeed();
    }
}

$bytes = '';
while (strlen($bytes) < $nbBytes) {
    static $incr = 1;
    $bytes .= hash('sha512', $incr++.$this->seed.uniqid(mt_rand(), true).$nbBytes, true);
    $this->seed = base64_encode(hash('sha512', $this->seed.$bytes.$nbBytes, true));
    $this->updateSeed();
}

return substr($bytes, 0, $nbBytes);

and

public static function equals($knownString, $userInput)
{
    // Prevent issues if string length is 0
    $knownString .= chr(0);
    $userInput .= chr(0);

    $knownLen = strlen($knownString);
    $userLen = strlen($userInput);

    // Set the result to the difference between the lengths
    $result = $knownLen - $userLen;

    // Note that we ALWAYS iterate over the user-supplied length
    // This is to prevent leaking length information
    for ($i = 0; $i < $userLen; $i++) {
        // Using % here is a trick to prevent notices
        // It's safe, since if the lengths are different
        // $result is already non-0
        $result |= (ord($knownString[$i % $knownLen]) ^ ord($userInput[$i]));
    }

    // They are only identical strings if $result is exactly 0...
    return 0 === $result;
}

Advantage: no dependency on Security in Form and FrameworkBundle
Disadvantage: code duplication, increased code complexity and maintenance costs, higher security risks

(c) As in (b), but use === instead of constant-time comparison; don't use seeds

Advantage: no dependency on Security in Form and FrameworkBundle
Disadvantage: less cryptographic security

Your opinions please?

@webmozart
Copy link
Contributor Author

@fabpot @padraic Do you have an opinion on this?

@webmozart
Copy link
Contributor Author

@fabpot @padraic Since today is feature freeze for the 2.3 LTS and this was on the top-priority list of tickets, can you please help me to resolve it? Which direction do we go?

@fabpot
Copy link
Member

fabpot commented May 6, 2013

I'm for option (c)

fabpot added a commit that referenced this pull request Sep 18, 2013
This PR was merged into the master branch.

Discussion
----------

[Security] Split the component into 3 sub-components Core, ACL, HTTP

| Q             | A
| ------------- | ---
| Bug fix?      | no
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | #9047, #8848
| License       | MIT
| Doc PR        | -

The rationale behind this PR is to be able to use any of the sub components without requiring all the dependencies of the other sub components. Specifically, I'd like to use the core utils for an improved CSRF protection mechanism (#6554).

Commits
-------

14e9f46 [Security] removed unneeded hard dependencies in Core
5dbec8a [Security] fixed README files
62bda79 [Security] copied the Resources/ directory to Core/Resources/
7826781 [Security] Split the component into 3 sub-components Core, ACL, HTTP
@webmozart
Copy link
Contributor Author

I updated this PR now. I deprecated the old CSRF implementation in the Form component and added a new Security CSRF sub-component with a better implementation that depends on Security Core. See the CHANGELOGs in the diff for more information.

I need some feedback regarding the service wiring.

@@ -168,6 +168,13 @@ UPGRADE FROM 2.x to 3.0
`ChoiceListInterface::getChoicesForValues()` and
`ChoiceListInterface::getValuesForChoices()` should be sufficient.

* The interface `CsrfProviderInterface` and all of its implementations were
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you should use the FQCN

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wow you're fast ;)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed

@fabpot
Copy link
Member

fabpot commented Sep 27, 2013

You can also remove symfony/form from the SecurityBundle composer.json file.

@webmozart
Copy link
Contributor Author

I just updated the PR description above for more information.

* @param string $namespace The namespace under which the token is stored
* in the session
*/
public function __construct(Session $session, $namespace = self::SESSION_NAMESPACE)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should be SessionInterface

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed

@stof
Copy link
Member

stof commented Sep 27, 2013

the root composer.json needs to replace the component too

@webmozart
Copy link
Contributor Author

Fixed all mentioned issues.

@webmozart
Copy link
Contributor Author

The SecurityBundle currently features the configuration values "csrf_provider" and "intention". Is it possible to add aliases "csrf_token_generator" and "csrf_token_id" for these settings?

"symfony/validator": "",
"symfony/http-foundation": ""
"symfony/validator": "For form validation.",
"symfony/security-csrf": "For protecting forms against CSRF attacks."
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You probably should add this also in the require-dev section.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

true because its used in tests. also its missing suggestions for dependency injection, httpfoundation, templating and kernel for all the extensions.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've added this to require-dev and added suggestions for symfony/twig-bridge and symfony/framework-bundle. I did not add suggestions for dependency injection, HTTP templating or kernel, because the corresponding form extensions don't add functionality, but only provide code to integrate with those components.

@Tobion
Copy link
Contributor

Tobion commented Sep 27, 2013

You need to update the require(-dev) sections for all libraries/bundles that use the new CsrfTokenGeneratorInterface to ~2.4, e.g. twigbridge, frameworkbundle, securitybundle.

@webmozart
Copy link
Contributor Author

Updated.

@Tobion
Copy link
Contributor

Tobion commented Sep 30, 2013

FrameworkBundle also needs the security for security_csrf.xml.

@webmozart
Copy link
Contributor Author

Updated.

*
* @param string $tokenId An ID that identifies the token
*/
public function generateCsrfToken($tokenId);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

missing @return

@Tobion
Copy link
Contributor

Tobion commented Sep 30, 2013

👍

@fabpot fabpot merged commit 7f02304 into symfony:master Sep 30, 2013
fabpot added a commit that referenced this pull request Oct 7, 2013
…ger and TokenGenerator (bschussek)

This PR was merged into the master branch.

Discussion
----------

[Security\Csrf] Split CsrfTokenGenerator into CsrfTokenManager and TokenGenerator

| Q             | A
| ------------- | ---
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | #9210
| License       | MIT
| Doc PR        | -

This is a follow-up PR of #6554 that splits the CsrfTokenGenerator into two separate classes for generating and managing CSRF tokens. As a consequence, it is now possible to explicitly remove or refresh CSRF tokens if they should be used only once. See #9210 for more information.

Commits
-------

d4bb5f4 [Security\Csrf] Split CsrfTokenGenerator into CsrfTokenManager and TokenGenerator
weaverryan added a commit to symfony/symfony-docs that referenced this pull request Jan 16, 2016
…lfiren, Aaron Valandra, xabbuh)

This PR was merged into the 2.7 branch.

Discussion
----------

csrf_token_generator and csrf_token_id documentation

| Q             | A
| ------------- | ---
| Doc fix?      | no
| New docs?     | yes (symfony/symfony#6554, symfony/symfony#9587)
| Applies to    | 2.4+
| Fixed tickets | #3059, #5942

Commits
-------

304d7a5 finish csrf_token_generator and csrf_token_id docs
3ceb61c Improper markdown for versionadded.
91b5e2e Updated documentation as requested by @stof and @xabbuh
0044aa2 Updated csrf_in_login_form.rst to include csrf_token_id and csrf_token_generator
@chalasr chalasr mentioned this pull request Sep 19, 2017
fabpot added a commit that referenced this pull request Dec 22, 2022
…enerator` to `firewalls.logout.csrf_token_manager` (MatTheCat)

This PR was merged into the 6.3 branch.

Discussion
----------

[SecurityBundle] Rename `firewalls.logout.csrf_token_generator` to `firewalls.logout.csrf_token_manager`

| Q             | A
| ------------- | ---
| Branch?       | 6.3
| Bug fix?      | no
| New feature?  | no
| Deprecations? | yes
| Tickets       | N/A
| License       | MIT
| Doc PR        | symfony/symfony-docs#17482

A long time ago, #6554 replaced `CsrfProviderInterface` by `CsrfTokenGeneratorInterface`, and #9216 split the latter into `CsrfTokenManagerInterface` and `TokenGeneratorInterface`. #9587 later introduced `csrf_token_generator`, which was already wrong at the time.

Given that token generators exist, it feels weird to have to set <code>csrf_token_**generator**</code> to <code>security.csrf.token_**manager**</code> as mentioned in [the documentation](https://symfony.com/doc/current/reference/configuration/security.html#csrf-token-generator).

As this confusion recently led to #48339, I propose to rename `firewalls.logout.csrf_token_generator` to `firewalls.logout.csrf_token_manager`.

Commits
-------

0a0a98a [SecurityBundle] Rename `firewalls.logout.csrf_token_generator` to `firewalls.logout.csrf_token_manager`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

8 participants