Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
fabpot merged 6 commits intosymfony:masterfromwebmozart:csrf
Sep 30, 2013

Conversation

@webmozart
Copy link
Contributor

QA
Bug fix?yes
New feature?no
BC breaks?no
Deprecations?no
Tests pass?yes
Fixed tickets-
LicenseMIT
Doc PRTODO

Update September 27, 2013

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

Since the CSRF token generator depends onStringUtils andSecureRandom 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 sureSecureRandom never blocks forCsrfTokenGenerator

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

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
ContributorAuthor

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

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 commentedJan 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 whyAndroid sometimes lags - same root cause)

@webmozart
Copy link
ContributorAuthor

@mvrhov I made the tokens URI safe now.

@vicb
Copy link
Contributor

vicb commentedJan 7, 2013

Backwards compatibility break: no

Really ?

@padraic
Copy link

@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
ContributorAuthor

Postponed to 2.3

@vicb
Copy link
Contributor

vicb commentedJan 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
ContributorAuthor

Thanks! :)

@webmozart
Copy link
ContributorAuthor

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 inSecureRandomInterface:
publicfunction 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 fromSecureRandom andStringUtil toAbstractCsrfProvider

The code in question is:

// initialize seedif (null ===$this->seed) {if (null ===$this->seedFile) {thrownew \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();}returnsubstr($bytes,0,$nbBytes);

and

publicstaticfunctionequals($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 informationfor ($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...return0 ===$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
ContributorAuthor

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

@webmozart
Copy link
ContributorAuthor

@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

I'm for option (c)

fabpot added a commit that referenced this pull requestSep 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 Core5dbec8a [Security] fixed README files62bda79 [Security] copied the Resources/ directory to Core/Resources/7826781 [Security] Split the component into 3 sub-components Core, ACL, HTTP
@webmozart
Copy link
ContributorAuthor

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.

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
ContributorAuthor

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
ContributorAuthor

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

You can also removesymfony/form from the SecurityBundlecomposer.json file.

@webmozart
Copy link
ContributorAuthor

I just updated the PR description above for more information.

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
ContributorAuthor

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

the root composer.json needs to replace the component too

@webmozart
Copy link
ContributorAuthor

Fixed all mentioned issues.

@webmozart
Copy link
ContributorAuthor

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?

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 therequire-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
ContributorAuthor

Choose a reason for hiding this comment

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

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

@Tobion
Copy link
Contributor

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
ContributorAuthor

Updated.

@Tobion
Copy link
Contributor

FrameworkBundle also needs the security for security_csrf.xml.

@webmozart
Copy link
ContributorAuthor

Updated.

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

👍

@fabpotfabpot merged commit7f02304 intosymfony:masterSep 30, 2013
fabpot added a commit that referenced this pull requestOct 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 requestJan 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,#5942Commits-------304d7a5 finish csrf_token_generator and csrf_token_id docs3ceb61c Improper markdown for versionadded.91b5e2e Updated documentation as requested by@stof and@xabbuh0044aa2 Updated csrf_in_login_form.rst to include csrf_token_id and csrf_token_generator
@chalasrchalasr mentioned this pull requestSep 19, 2017
fabpot added a commit that referenced this pull requestDec 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#17482A 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 freeto join this conversation on GitHub. Already have an account?Sign in to comment

Reviewers

No reviews

Assignees

No one assigned

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

8 participants

@webmozart@mvrhov@vicb@padraic@fabpot@stof@Tobion@stloyd

[8]ページ先頭

©2009-2025 Movatter.jp