GithubHelp home page GithubHelp logo

scheb / two-factor-bundle Goto Github PK

View Code? Open in Web Editor NEW
386.0 18.0 111.0 2.13 MB

[ABANDONED] Two-factor authentication for Symfony 2 & 3 applications πŸ”. Please use the newer versions from https://github.com/scheb/2fa.

Home Page: https://github.com/scheb/2fa

License: MIT License

PHP 99.50% Twig 0.50%
2fa two-factor-authentication authentication security symfony-bundle totp google-authenticator

two-factor-bundle's Introduction

scheb/two-factor-bundle

⚠ Unmaintained version

Please upgrade your project to a recent version. Use bundle version 5 (or newer), which is available as scheb/2fa-bundle from the scheb/2fa repository.


This bundle provides two-factor authentication for your Symfony application.

Build Status Scrutinizer Code Quality Code Coverage Latest Stable Version Monthly Downloads Total Downloads License

Logo


It comes with the following two-factor authentication methods:

Additional features you will like:

  • Interface for custom two-factor authentication methods
  • Trusted IPs
  • Trusted devices (once passed, no more two-factor authentication on that device)
  • Single-use backup codes for when you don't have access to the second factor device
  • Multi-factor authentication (more than 2 steps)
  • CSRF protection
  • Whitelisted routes (accessible during two-factor authentication)

Installation

composer require scheb/two-factor-bundle

... and follow the installation instructions.

Documentation

Detailed documentation of all features can be found in the Resources/doc directory.

Version Guidance

⚠ Version 4.x is no longer maintained.

Please upgrade your project to a recent version. Use bundle version 5 (or newer), which is available as scheb/2fa-bundle from the scheb/2fa repository.

License

This bundle is available under the MIT license.

Security

For information about the security policy and know security issues, see SECURITY.md.

Contributing

Want to contribute to this project? See CONTRIBUTING.md.

Support Me

I'm developing this library since 2014. I love to hear from people using it, giving me the motivation to keep working on my open source projects.

If you want to let me know you're finding it useful, please consider giving it a star ⭐ on GitHub.

If you love my work and want to say thank you, you can help me out for a beer 🍻️ via PayPal.

two-factor-bundle's People

Contributors

aaroncritchley avatar chalasr avatar darookee avatar dfridrich avatar j0k3r avatar keksa avatar lordjancso avatar maxhelias avatar mkrauser avatar montaniasystemab avatar odbayar avatar philetaylor avatar pierredup avatar quentinus95 avatar rcousens avatar remg avatar richardhj avatar rickprent avatar samvaughton avatar scheb avatar sdespont avatar seldaek avatar sirwaddles avatar spomky avatar stephanvierkant avatar tnajanssen avatar umpirsky avatar uneo7 avatar xabbuh avatar zerkms avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

two-factor-bundle's Issues

Make bundle compatible with symfony2.7

After upgrading to v2.7 last weekend this bundle started triggering deprecated errors.

PHP Deprecated:  Symfony\Component\DependencyInjection\Definition::setFactoryService(doctrine) is deprecated since version 2.6 and will be removed in 3.0. Use Definition::setFactory() instead. in /home/app/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Definition.php on line 208
PHP Stack trace:
PHP   1. {main}() /home/app/app/console:0
PHP   2. Symfony\Component\Console\Application->run() /home/app/app/console:27
PHP   3. Symfony\Bundle\FrameworkBundle\Console\Application->doRun() /home/app/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:126
PHP   4. Symfony\Component\HttpKernel\Kernel->boot() /home/app/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php:70
PHP   5. Symfony\Component\HttpKernel\Kernel->initializeContainer() /home/app/app/bootstrap.php.cache:2396
PHP   6. Symfony\Component\DependencyInjection\ContainerBuilder->compile() /home/app/app/bootstrap.php.cache:2618
PHP   7. Symfony\Component\DependencyInjection\Compiler\Compiler->compile() /home/app/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/ContainerBuilder.php:614
PHP   8. Symfony\Component\HttpKernel\DependencyInjection\MergeExtensionConfigurationPass->process() /home/app/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php:117
PHP   9. Symfony\Component\DependencyInjection\Compiler\MergeExtensionConfigurationPass->process() /home/app/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/DependencyInjection/MergeExtensionConfigurationPass.php:39
PHP  10. Scheb\TwoFactorBundle\DependencyInjection\SchebTwoFactorExtension->load() /home/app/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Compiler/MergeExtensionConfigurationPass.php:55
PHP  11. Symfony\Component\DependencyInjection\Loader\XmlFileLoader->load() /home/app/vendor/scheb/two-factor-bundle/DependencyInjection/SchebTwoFactorExtension.php:48
PHP  12. Symfony\Component\DependencyInjection\Loader\XmlFileLoader->parseDefinitions() /home/app/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php:58
PHP  13. Symfony\Component\DependencyInjection\Loader\XmlFileLoader->parseDefinition() /home/app/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php:119
PHP  14. Symfony\Component\DependencyInjection\Definition->setFactoryService() /home/app/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php:153
PHP  15. trigger_error() /home/app/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Definition.php:208

I have pinpointed the issue, it comes from Resources/config/persistence.xml.

I've also provided a solution that fixes this deprication warnings.

<service id="scheb_two_factor.entity_manager" class="Doctrine\ORM\EntityManager" public="false">
    <factory service="doctrine" method="getManager"/>
    <argument>%scheb_two_factor.model_manager_name%</argument>
</service>

Cheers!

require second factor only for some routes or a specified firewall

I have actions in my app that have higher security requirements than others. So I'd like to require the second factor only for these routes. I imagine two alternative strategies:

  • define two different firewalls and only require the second factor for one of this firewalls
  • somehow mark (annotate) or list (config) the routes that require the second factor

I'd like to contribute this feature to your bundle, if we can find an implementation that is generic and backwards compatible.

Google authentication with FOSUserBundle

Hi there,

I have installed the bundle in my current project with FOSUserBundle. I added the config, I have disable email and enable google authenticator, and added the in "security" this code:
access_decision_manager: strategy: unanimous
I don't know why, when I'm trying to get inside the login with my user. The website gives me to the homepage and do not shown me the google authenticator(as if I had not installed the bundle, but I have it).
I can use this command in terminal and gave me the correct code:
php app/console scheb:two-factor:google-secret
Please, could you help me with my issue?

Add Email Sender Name to Bundle Configuration

Currently, when opting for the Email Provider, one can specify the email of the sender in the configuration of the bundle. It would be useful to also be able to configure the name of the sender.

Support for HWIOAuthBundle

Do you know why this bundle doesn't work with HWIOAuthBundle?

Is it because they don't fire the InteractiveLoginEvent?

Limit authentication attempts?

I really love this bundle!

I've got a question about the security of the Google Authenticator part of the bundle:

Wouldn't it be necessary to limit the authentication attempts? I know every code is only valid for 30 seconds, but that doesn't totally rule out a brute force attack.

What's your take on this? And how to handle with this issue?

How to show QR code?

First of all: thank you for the great bundle!

I'm able to use my own template for the Google Authentication code, but I don't know how to use the following code (from the docs) to show a QR code in this template:

$url = $container->get("scheb_two_factor.security.google_authenticator")->getUrl($user);
echo '<img src="'.$url.'" />';

Thanks in advance!

Don't require two-factor-authentication if access_control doesn't require authentication

A part of my security.yml reads

access_control:
    - { path: ^/js/, role: IS_AUTHENTICATED_ANONYMOUSLY } # for FOSJsRoutingBundle

But when the user is logged in and before the security token is validated, all requests to this path ^/js/ are blocked by two-factor-bundle. In my opinion, the access_control should prevent two-factor-bundle from blocking this path.

Assetic filters on form.html.twig

Hi Christian

Great work on this bundle!

Just having an issue where applying Assetic filters - it seems to be blocked.

This is done in the DEV environment for debug is testing.

Not sure if I am doing this right.

    {% stylesheets '@AcmeBundle/Resources/public/css/Security/login.css'
    filter='?uglifycss' %}
    <link rel="stylesheet" type="text/css" media="screen" href="{{ asset_url }}" />
    {% endstylesheets %}

http-only trusted cookies

At the moment the trusted device cookie only accepts the lifetime and the secure flag.

How about adding the httponly additionally to that?

For discussion: would one treat having httponly: true as the new default value as a breaking change?

Using deprecated event_dispatcher, switch it out

The event_dispatcher service uses the Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher class, which has been deprecated in Symfony 3.3. Use the Symfony\Component\EventDispatcher\EventDispatcher class instead.

<service id="scheb_two_factor.provider_registry" class="%scheb_two_factor.provider_registry.class%" lazy="true">
			<argument type="service" id="scheb_two_factor.session_flag_manager" />
            <argument type="service" id="event_dispatcher" />
            <argument>%scheb_two_factor.parameter_names.auth_code%</argument>
            <argument /> <!-- Two-factor providers -->
		</service>

I can't register a new authentication provider

I wrote a new authentication provider, called "multiple" because using it I can allow both google and email authentication. According to the docs, to register it I should write something similar to:

<service id="acme.two_factor.provider" class="%acme.two_factor.provider.class%">
    <tag name="scheb_two_factor.provider" alias="acme_two_factor" />
</service>

This is my yml, which I'm pretty sure it's equivalent. (I also had it checked online on http://converter.rosstuck.com/ and manually by an expert Symfony user):

services:
    multiple.two_factor.provider:
        class: AppBundle\Security\MultipleTwoFactorProvider
        arguments:
            ...
        tags:
            - { name: scheb_two_factor.provider, alias: multiple }

and this is my config.yml:

scheb_two_factor:
    ...
        email: ...
        google: ...

        multiple:
            enabled: true
            template: security\twofactor\twofactor.html.twig

but when I read the new config, e.g. when cleaning the cache, I get an InvalidConfigurationException:
Symfony\Component\Config\Definition\Exception\InvalidConfigurationException]
Unrecognized option "multiple" under "scheb_two_factor"

The only workaround so far was adding the following code to vendor/scheb/two-factor-bundle/DependencyInjection/Configuration.php, right below the arrayNode('google') definition, but I know it's a Bad Thingβ„’:

/* vendor/scheb/two-factor-bundle/DependencyInjection/Configuration.php:56 */

    ->arrayNode('multiple')
        ->addDefaultsIfNotSet()
        ->children()
            ->booleanNode('enabled')->defaultFalse()->end()
        ->scalarNode('template')->defaultValue('SchebTwoFactorBundle:Authentication:form.html.twig')->end()
        ->end()
    ->end()

The provider in itself works like a charm, I solved all of the other issues I encountered by overriding the bundle when needed by following Symfony official docs, but it seems that I have kind of lost a step now.

P.S.: I'm on Symfony 3 (3.0.4), but I'm sure it shouldn't represent a problem.

Templating ServiceCircularReference

Hi all,

Just wonder if anyone had seen this error before:

 Circular reference detected for service "templating", path: "nelmio_api_doc.event_listener.request -> nelmio_api_doc.formatter.html_formatter -> templating -> twig -> security.authorization_checker -> security.access.decision_manager -> scheb_two_factor.security_voter -> scheb_two_factor.provider_collection -> scheb_two_factor.security.google.provider".

If I disable either nelmio_api_doc or scheb_two_factor this error goes away but I cannot figure out how to combat the circular reference but still get the functionality of both bundles.

Symfony2: 2.7.7
Scheb Two Factor: 1.5

Previous these bundles worked fine for me, I suspect a composer update has broken things. Any pointers would be much appreciated.

Cheers
Chris

Using multiple authentication methods in paralell

Hi!
I would like to use multiple authentication methods at once.
I mean, for example i wan't to be able to use googleauth and email auth at once.
So if i chose to not use google authentication i shall be able to use email authentication instead.
The UI part is simple to me, but how can i achieve that thus with only one requestlistener.

QR Code Issuer

Hi,

Fist, nice work with this bundle, help me a lot :) . I just can't figure out how to add issuer when generating url for QR Code. Is this supported?

Cheers

Limiting to Master Request + Security Voter breaks the authentication form

Release v2.7.0 (limiting the two-factor check only to master requests) may break 2FA, because a non-master request may invoke a security check, which triggeres the voter, which causes a security exception to rise (voter votes against access granted, because 2fa not yet complete). This prevents the authentication form from being shown.

Temporary solutions:

  • Disable voter
  • Use 2.6.x

proxy manager should probably be an optional dependency

Heya,

I noticed that the proxy manager is added as "require", but from what I can find, the only reason of why it's added, is the lazy="true" in a few service definitions. I believe this dependency should be optional as I rather not have this dependency in my application, can this be safely removed to "require-dev"?

Should exclude_pattern check also be in a voter?

Currently, even if you specify the .* as the exclude_pattern you still would get a 403.

It happens because Scheb\TwoFactorBundle\Security\TwoFactor\Voter does not take it into account and unconditionally returns VoterInterface::ACCESS_DENIED as soon as the session flag is not set.

So the question: is it deliberately that way? If so - what is the typical use case for the exclude_pattern?

Trusted IP address feature

Hi all,

I was wondering if there was a way to have a verification of the user's IP address prior to sending an authentication code which would be acting the same way as the trusted computer feature.

This idea for my application is to override the second factor if the users signs in from an identified IP (a company for example).

I am not sure if adding a custom authentication method would work for that or if a dedicated feature would be better.

Thanks

Google Authenticator Timezone

Sometimes two factor auth fails for me ("The verification code is not valid" flash message) and I suspect it may be a timezone issue. When it happens, I cannot login no matter how many times I try. After a day or two, I setup new secret and it works. It's pretty random.

I saw chregu/GoogleAuthenticator.php#15 and not sure if it is related.

Is there any other reason why it can fail like this?

Thanks.

Integrate Two-Factor Authentication Into Security Layer

Excerpt from the documentation:

Limitations

After the initial login happened, the user is already fully authenticated to the Symfony security layer. The bundle then prevents access to secured and non-secured content by intercepting any request and showing the two-factor authentication form instead.

If you execute code based on the authentication status, make sure to take the two-factor status into account. This can be done by checking access with isGranted (security voter has to be registered, see configuration).

Warning: Just doing a getUser on security.token_storage (or the old security.context) is not secure. You will get a user object even when two-factor authentication is not complete yet.

Overall, the current implementation causes some issues, which cannot really be solved, as long as two-factor authentication doesn't become part of the actual security layer.

  • #13 Two-factor authentication cannot be configured per firewall,
  • #60 & #62 Issues caused by the voter, which is there to prevent execution of code. This is necessary because in the current implementation the user already has all priviledges after login, even when two-factor authentication is not completed yet.
  • #70 & #71 - The bundle relies on intercepting the first kernel.request event, which causes problems in ESI environments,
  • #36 Two-factor authentication form doesn't have it's own route. Instead it is shown as a replacement for the actual content, which causes problems when the current route doesn't accept POST requests.

Google Authenticator: http status 400 (bad request)

Hi,

I've encountered a problem. If I add qr_code as suggested in documentation:

$url = $container->get("scheb_two_factor.security.google_authenticator")->getUrl($user);
echo '<img src="'.$url.'" />';

I get: 400 Bad Request.

Found solution on stackoverflow: http://stackoverflow.com/questions/17071368/400-bad-request-when-attempting-to-insert-qr-code-image-for-google-authenticator

Maybe we should use https://chart.googleapis.com instead of https://www.google.com?

Validate Token

Hi there,
is there any possibility to validate a token? I don't want to add the secret to the entity when the user can't create tokens. So it should be validated with a correct token from the authenticator.

regards

Before the trusted device is persisted it should first check if context allows to do so.

Currently the implementation (excerpt) in \Scheb\TwoFactorBundle\Security\TwoFactor\Trusted\TrustedFilter looks like

if ($context->isAuthenticated() && $request->get($this->trustedName)) {
    $cookie = $this->cookieManager->createTrustedCookie($request, $user);
    $response->headers->setCookie($cookie);
}

It is prone to race condition (when trusted is disabled between requests) or when a user manually added a flag.

So it should additionally check for $context->useTrustedOption().

2factor when fosuserbundle password reset

Hi,

I have implemented 2factor and it works. But i have noticed that there isn't a 2factor authentication after resetting a password. I directly logged in after that.

Is there a way to implement the 2factor on password reset?

Optimize RequestListener

Looks like RequestListener adds some latency, and not onCoreRequest as you'd expect, but just fetching the service from container can add ~25ms to each request.

I tried to track down the dependency graph and it goes like this: scheb_two_factor.security.request_listener -> scheb_two_factor.trusted_filter -> scheb_two_factor.provider_registry -> scheb_two_factor.security.google.provider -> scheb_two_factor.security.google.backup_code_validator -> scheb_two_factor.backup_code_validator -> scheb_two_factor.persister.doctrine.

If using lazy services and check FlagManager.isNotAuthenticated() earlier this can be optimized.

I know FlagManager does not know about providers, but maybe it can be tweaked to pull a minimal set of dependencies if FlagManager.isNotAuthenticated() is false.

Voter causes an infinite redirect for non-UsernamePasswordToken tokens

If you configure a project with RememberMeToken then when user is re-authenticated using the RememberMe cookie - voter's return VoterInterface::ACCESS_DENIED; turn the authentication process into an infinite loop.

It happens because:

  1. RememberMe listener authenticates a user
  2. On voter returns ACCESS_DENIED
  3. Symfony's Symfony\Component\Security\Http\Firewall\ExceptionListener exception handler checks the user is not fully authenticated and performs a redirect (through Symfony\Component\Security\Http\EntryPoint\FormAuthenticationEntryPoint::start()
  4. Go to step 2

Temporary solution: disable Voter

Permanent solution: the Voter implementation (and presence at all) should be reconsidered.

Renew trusted cookie on login

I've been using this bundle in a production application for awhile now, and I noticed most users have ~30 trusted computer tokens each.

The cookie expires after a set time, but the token is kept in the database. When the user checks the box again, a new one is generated (users also find this frustrating because they log in regularly and at seemingly sporadic intervals are required to enter their two-factor code again)

Would it be a good idea to allow an option to resend the cookie with a new expiration date on a sucessful remembered login? This way, when a user is actively using an application, it will remember them for the entire duration but if they fall into absence, they will need to reauthenticate.

Exception logged for every request of 2FA

 prod - 10th error occurrence: #347 Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException: Access Denied.

After getting a bunch of times on the logs this i think it is unnecessary, is there a standard way to catch this within the bundle code and prevent this from happening?

$url not using the correct Secret

When using $url = $this->get("scheb_two_factor.security.google_authenticator")->getUrl($user); it uses the wrong SECRET code.

URL:
string(180) "https://chart.googleapis.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth%3A%2F%2Ftotp%2FKeliba%3Amarco%2540slik.eu%40Zioo%2520Keliba%3Fsecret%3DKKUGJP3N65XJ3VWQ%26issuer%3DKeliba"

The secret Code:
string(16) "KKUGJP3N65XJ3VWQ"

As you can see the secret code is different from what the URL uses.

it puts a 3D before the code.

Is there a fix for this? What am I doing wrong?

Allow GET requests in TwoFactorProvider::requestAuthenticationCode

Thank you for your bundle, it's very useful and very easy to customize.

However, I'm using your Email Provider and I need to insert into the email an url that authenticates the user by sending the _auth_code parameter. I can't do this right now because the bundle is restricting the allowed methods to 'POST'.

One easy solution is to add a configuration parameter allow_get_request that default to false.

What do you think? Is it something you will consider if I send a PR?

Authentication success/failure event

Is it possible to observe an "authentication.failure" or "authentication.success" event? My user requirement is to lock the user account after "n" invalid authentication attemps.

Maybe I can add a dispatch event here https://github.com/scheb/two-factor-bundle/blob/master/Security/TwoFactor/Provider/TwoFactorProviderRegistry.php#L74 or here https://github.com/scheb/two-factor-bundle/blob/master/Security/TwoFactor/EventListener/RequestListener.php#L74 but I'm not sure.

Sorry for my basic English.

Add optional two factor auth

Is there a way to let the user choice if he wanna use google authenticator and/or email authentication. So by default just username and password auth is enabled. But the user can decide if he wanna use two factor auth.

Discussion: signed cookies for trusted computer

What about using some sort of signed cookies data (using the framework.secret by default or any other explicitly set secret) - eg: JWT/JWE instead of persisting storage?

This would save some db queries and simplify the bundle integration (less requirements for user entities).

Thoughts?

Support for multiple sites running one Symfony App <2.6

While the two factor bundle enforces both sites to authenticate in two steps.
Is there a way I can customize the template based on the host parameter?

The workaround is to create a dynamic template in twig so it builds the right template (which is causing an infinite loop at this point) or create a generic template to support both sites.

Error if a route can handle no POST.

When I call a URL that no POST can handle I get the following message.

No route found for "POST /buchung/dsh/anmeldung/29": Method Not Allowed (Allow: GET, HEAD)

Is there a solution?

cookie on trusted computer

Do you plan to integrate a cookie managment to skip the validation code if the computer is trusted? (as google do)

Issuer doesn't like spaces

I couldn't get the generated QR code to work when the issuer had a white space in. Changing it be URL encoded and use %20 made it work.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.