Skip to content
/ symfony Public
forked from symfony/symfony
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

Multi step authentication #1

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory;

use Symfony\Component\DependencyInjection\ContainerBuilder;

interface FirewallListenerFactoryInterface
{
/**
* Creates the firewall listener service(s) for the provided configuration.
*
* @return string|string[] The listener service ID(s) to be used by the firewall
*/
public function createListeners(ContainerBuilder $container, string $firewallName, array $config);
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\AuthenticatorFactoryInterface;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\EntryPointFactoryInterface;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\FirewallListenerFactoryInterface;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\RememberMeFactory;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SecurityFactoryInterface;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\UserProvider\UserProviderFactoryInterface;
Expand Down Expand Up @@ -568,6 +569,18 @@ private function createAuthenticationListeners(ContainerBuilder $container, stri
$listeners[] = new Reference($listenerId);
$authenticationProviders[] = $provider;
}

if ($factory instanceof FirewallListenerFactoryInterface) {
scheb marked this conversation as resolved.
Show resolved Hide resolved
$firewallListener = $factory->createListeners($container, $id, $firewall[$key]);
if (\is_array($firewallListener)) {
foreach ($firewallListener as $listenerId) {
$listeners[] = new Reference($listenerId);
}
} else {
$listeners[] = new Reference($firewallListener);
}
}

$hasListeners = true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,22 @@ private function executeAuthenticator(AuthenticatorInterface $authenticator, Req
$authenticatedToken->eraseCredentials();
}

// Since the security token is carrying the state of authentication around between request, for 2fa I'm
// making the system to carry a TwoFactorToken around, which has some specific characteristics.
// The main one are, it's signalizes to the system:
// 1) The authentication is not complete yes IS_AUTHENTICATED_FULLY == false
// 2) It actives the 2fa-specific logic, like redirecting to the 2fa form

// $authenticatedToken is coming from the authenticator, which initially identifies the user (e.g. username+
// password). Here at this point I have to hook-in to make multi-step authentication work.
// I need to exchange $authenticatedToken (which already exposes all roles/privileges) with a TwoFactorToken
// to put authentication into that intermediate state, which is neither anonymous, nor fully authenticated.
// I'm doing this by decorating all authenticators, so that I can "magically" exchange $authenticatedToken
// before it reaches these lines of code here and becomes visible to the system in the dispatched event
// below. But this is really hacky. I'd like to have a better way to hook-in after the authenticator,
// "raise a veto" and change the token before it becomes effective in the system.
Comment on lines +180 to +187
Copy link

@wouterj wouterj Jun 13, 2020

Choose a reason for hiding this comment

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

I'm fine with adding a new event here. Honestly, one of the biggest things we were usure about is if we had enough events and if events were dispatched at a logical places. I think it makes sense to have something after authenticated token is created.

I am however not sure about "The authentication is not complete yes IS_AUTHENTICATED_FULLY == false". I've talked about this previously as well - so we may just agree to disagree on this :). I think it makes sense to think about 2fa as level of assurance. In other words, using a username+password form would make a user LoA level 1. This means a user is already authenticated (ie. isGranted("IS_AUTHENTICATED_FULLY") === true). However, if you enforce 2fa for the whole website you would add something like { pattern: "^/", roles: "LEVEL_OF_ASSURANCE_2" } to your access control. Symfony/this bundle would then need to provide some sort of "authentication elevation classes" that can make a user LoA 2 by filling in a 2FA code.
This would allow users to enforce 2FA for some parts of the website (e.g. the admin panel), but not require it on others (e.g. when that same admin user just wants to edit their own personal profile). It would also remove most of the issues this bundle needs to work around.

Copy link
Owner Author

Choose a reason for hiding this comment

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

I'm fine with adding a new event here. Honestly, one of the biggest things we were usure about is if we had enough events and if events were dispatched at a logical places.

I'd say they are ;). A lot of things can be done with the current setup. The only thing that I see missing is this ability to influence the security token somehow before it becomes effective. But this is an entirely new feature, the old security system also couldn't do it.

I think it makes sense to have something after authenticated token is created.

I could imagine something similar to the "RequestEvent", which would allow a listener to return an alternative security token to be used (similar to the response of RequestEvent). I'll give it a shot and implement a proposal.

Regarding IS_AUTHENTICATED_FULLY, I'll put together some thoughts on this later.

Copy link
Owner Author

Choose a reason for hiding this comment

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

@wouterj Regarding the event, how does this look to you? 5ad1640

Copy link
Owner Author

Choose a reason for hiding this comment

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

@wouterj Regarding IS_AUTHENTICATED_FULLY:

I understand IS_AUTHENTICATED_FULLY as the flag that tells "you can trust this identity".

An account with 2fa should only be "authenticated fully" when they have passed 2fa. Until they've completed the 2fa authentication process, these clients have just claimed to be someone but not proven it. So that identify cannot be assumed trustworthy in any way and therefore IS_AUTHENTICATED_FULLY should evaluate false.

Also, I want this attribute to express "you can trust this identity now" in a system that has both users with 2fa enabled and users which have it disabled.

  • For a user with 2fa disabled the identity becomes trustworthy right after login - because how the account is configured. Therefore IS_AUTHENTICATED_FULLY becomes true immediately after login.
  • For a user with 2fa enabled you first have to go through the 2fa process. So right after login IS_AUTHENTICATED_FULLY must be false. Only when you complete 2fa IS_AUTHENTICATED_FULLY it becomes true.

So in both cases, the same attribute IS_AUTHENTICATED_FULLY can be used to check if you can trust that identity and you don't need to care about specifics of the account.

Compared to that, in a "level of assurance" system, both kinds of users would have the same "trust level" right after login, even the 2fa-enabled user that hasn't completed 2fa yet. And once that user has completed 2fa, they have a higher trust-level. So there's the issue, you don't have a single attribute to check if the identity is equally trustworthy. You'd always need to look at the user account, check if it requires 2fa and then use either level 2 or 3.

Nevertheless, I believe trust levels would be a great addition to the security system. I sometimes get the request from users, who only want to protect certain paths with 2fa. So they actually want to user to be "trustworthy" already after login and want 2fa as an extra (effectively what trust levels are). This contradicts my concept of 2fa, because I'm saying "your identity is not trustworth until you've completed 2fa".

Both concepts are pretty close together, so there must be a way to join them. Probably the best idea would be to remove the concept of IS_AUTHENTICATED_FULLY and come up with some mechanic to determine "you can trust this identity" which can be implemented/configured by the developer according to their needs.

Copy link

Choose a reason for hiding this comment

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

Ah, thanks for clarifying the difference between LoA and 2FA. In our application, 2FA is something that is required for admins and not available for users (it's on our list to make it optional). So based on what you are saying, 2FA is something decided from a user perspective (a user may or may not want 2FA), while LoA is something enforced by the application (some paths require a specific LoA).

This makes sense to me now 👍

Copy link

@wouterj wouterj Jun 18, 2020

Choose a reason for hiding this comment

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

Interesting thought! So AuthenticationTrustResolver#isFullFlegded() should actually do something like below if we're going to implement LoA.

// ...
if ($user instanceof EnforcesTrustLevelInterface) {
    return $user->getRequiredTrustLevel() > $token->getTrustLevel();
}

// ...

Copy link
Owner Author

Choose a reason for hiding this comment

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

Exactly, that could be the way to go. Should be >= btw ;)

Copy link

Choose a reason for hiding this comment

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

Would that also fix https://github.com/scheb/symfony/pull/1/files#diff-d6ccb5922f9ccac25c0993a763c4e5b4R185 ?

I think a RememberMeToken should always be a low LoA. So at first sight, I think we no longer have to prevent remember me cookies to be set if we require a higher LoA because of 2FA (e.g. remember me is LoA 1 and 2FA will be around LoA 3)

Copy link
Owner Author

Choose a reason for hiding this comment

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

True. There wouldn't be a need to prevent the cookie being set. Restarting the session would start with a low trust level, so low the identity wouldn't be trusted. So the client would be forced to go through 2fa. It would no longer be possible to bypass 2fa with a remember-me cookie.

Independent of that I still believe the RememberMeServices needs some refactoring.

Copy link

Choose a reason for hiding this comment

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

Independent of that I still believe the RememberMeServices needs some refactoring.

Oh 100% agreed. I think the second paragraph in that class (and where I also left a comment) still applies. I'm afraid BC will be quite a challenge.


// Btw. this if statement is unnecessary, $this->eventDispatcher is always !== null ;)
if (null !== $this->eventDispatcher) {
$this->eventDispatcher->dispatch(new AuthenticationSuccessEvent($authenticatedToken), AuthenticationEvents::AUTHENTICATION_SUCCESS);
}
Expand Down
32 changes: 11 additions & 21 deletions src/Symfony/Component/Security/Http/Firewall.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Http\Firewall\AccessListener;
use Symfony\Component\Security\Http\Firewall\FirewallListenerInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;

/**
Expand Down Expand Up @@ -59,29 +59,19 @@ public function onKernelRequest(RequestEvent $event)
$exceptionListener->register($this->dispatcher);
}

$authenticationListeners = function () use ($authenticationListeners, $logoutListener) {
scheb marked this conversation as resolved.
Show resolved Hide resolved
$accessListener = null;

foreach ($authenticationListeners as $listener) {
if ($listener instanceof AccessListener) {
$accessListener = $listener;

continue;
}

yield $listener;
}
$firewallListeners = $authenticationListeners;
if (null !== $logoutListener) {
$firewallListeners[] = $logoutListener;
}

if (null !== $logoutListener) {
yield $logoutListener;
}
uasort($firewallListeners, function ($a, $b) {
$aPriority = $a instanceof FirewallListenerInterface ? $a->getPriority() : 0;
$bPriority = $b instanceof FirewallListenerInterface ? $b->getPriority() : 0;

if (null !== $accessListener) {
yield $accessListener;
}
};
return $aPriority <=> $bPriority;
});

$this->callListeners($event, $authenticationListeners());
$this->callListeners($event, $firewallListeners);
}

public function onKernelFinishRequest(FinishRequestEvent $event)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
*
* @author Nicolas Grekas <p@tchwork.com>
*/
abstract class AbstractListener
abstract class AbstractListener implements FirewallListenerInterface
{
final public function __invoke(RequestEvent $event)
{
Expand All @@ -39,4 +39,9 @@ abstract public function supports(Request $request): ?bool;
* Does whatever is required to authenticate the request, typically calling $event->setResponse() internally.
*/
abstract public function authenticate(RequestEvent $event);

public function getPriority(): int
{
return 0; // Default
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -120,4 +120,9 @@ private function createAccessDeniedException(Request $request, array $attributes

return $exception;
}

public function getPriority(): int
{
return -255;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace Symfony\Component\Security\Http\Firewall;

interface FirewallListenerInterface
{
/**
* Defines the priority of the listener.
* The higher the number, the earlier a listener is executed.
*
* @return int
*/
public function getPriority(): int;
}
Original file line number Diff line number Diff line change
Expand Up @@ -142,4 +142,9 @@ protected function requiresLogout(Request $request): bool
{
return isset($this->options['logout_path']) && $this->httpUtils->checkRequestPath($request, $this->options['logout_path']);
}

public function getPriority(): int
{
return -254;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,12 @@ final public function loginSuccess(Request $request, Response $response, TokenIn
// Make sure any old remember-me cookies are cancelled
$this->cancelCookie($request);

// I'd suggest to extend the conditions under which the security system allows a remember-me cookie to be set.
// This class should check \Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface::isFullFledged
// Why? 1st) because it makes sense to have that requirement
// 2nd) in a multi-step authentication process it would help to prevent the remember-me cookie from being set
// Right now I have to do "hacks" to prevent the cookie being set, because AbstractRememberMeServices implicitly
// assumes that when it's called it's secure to set a remember-me cookie.
if (!$token->getUser() instanceof UserInterface) {
if (null !== $this->logger) {
$this->logger->debug('Remember-me ignores token since it does not contain a UserInterface implementation.');
Expand All @@ -190,6 +196,12 @@ final public function loginSuccess(Request $request, Response $response, TokenIn
return;
}

// Having this here makes it unnecessary hard to set a remember-me cookie after 2fa, because this requires
// the parameter to be present in the request. There's no way to reach the logic for setting the cookie without
// fulfilling this requirement.
// Imo the logic for settings the cookie (everything that's implemented in the sub-classes) should be decoupled
// from the conditions under which the cookie can be set (everything here). Effectively making the sub-classes
// separate classes and a dependency, instead of inheritance.
Comment on lines +199 to +204
Copy link

@wouterj wouterj Jun 13, 2020

Choose a reason for hiding this comment

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

Honestly, I think this whole remember me services needs some refactoring. Almost anything in this abstract class should be done in the authenticator instead (the RememberMeToken is now generated twice, to be able to support this legacy logic in the authenticator).

So yes, I agree with deprecating this abstract class and making the sub-classes real functioning classes on their own (with probably a new interface). That probably requires a new investigating to see the effects of this change and how it can be done in a BC way.

Copy link

Choose a reason for hiding this comment

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

I've taken a shot at this in: symfony#40145

if (!$this->isRememberMeRequested($request)) {
if (null !== $this->logger) {
$this->logger->debug('Remember-me was not requested.');
Expand Down