Skip to content
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

Fix several trusted device issues #1299

Merged
merged 8 commits into from
Feb 14, 2020
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,6 @@ protected function getResponse(Template $template, ModuleModel $model, Request $
$template->href = $this->page->getAbsoluteUrl().'?2fa=enable';
$template->backupCodes = json_decode((string) $user->backupCodes, true) ?? [];
$template->trustedDevices = $this->get('contao.security.two_factor.trusted_device_manager')->getTrustedDevices($user);
$template->currentDevice = $request->cookies->get($this->getParameter('scheb_two_factor.trusted_device.cookie_name'));

return new Response($template->parse());
}
Expand Down
34 changes: 1 addition & 33 deletions core-bundle/src/Entity/TrustedDevice.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,20 +51,6 @@ class TrustedDevice
*/
protected $userId;

/**
* @var string
*
* @ORM\Column(type="text", name="cookie_value")
*/
protected $cookieValue;

/**
* @var int
*
* @ORM\Column(type="integer")
*/
protected $version;

/**
* @var string|null
*
Expand Down Expand Up @@ -93,10 +79,9 @@ class TrustedDevice
*/
protected $deviceFamily;

public function __construct(User $user, int $version)
public function __construct(User $user)
{
$this->userId = (int) $user->id;
$this->version = $version;
$this->created = new \DateTime();
$this->userClass = \get_class($user);
}
Expand Down Expand Up @@ -130,23 +115,6 @@ public function getUserId(): int
return $this->userId;
}

public function getCookieValue(): string
{
return $this->cookieValue;
}

public function setCookieValue(string $cookieValue): self
{
$this->cookieValue = $cookieValue;

return $this;
}

public function getVersion(): int
{
return $this->version;
}

public function setUserAgent(?string $userAgent): self
{
$this->userAgent = $userAgent;
Expand Down
3 changes: 0 additions & 3 deletions core-bundle/src/Resources/contao/languages/en/default.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -1988,9 +1988,6 @@
<trans-unit id="MSC.device">
<source>Device</source>
</trans-unit>
<trans-unit id="MSC.thisDevice">
<source>this device</source>
</trans-unit>
<trans-unit id="MSC.browser">
<source>Browser</source>
</trans-unit>
Expand Down
4 changes: 0 additions & 4 deletions core-bundle/src/Resources/contao/modules/ModuleTwoFactor.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,9 @@ protected function compile()
$container->get('contao.security.two_factor.trusted_device_manager')->clearTrustedDevices($user);
}

/** @var Request $request */
$request = $container->get('request_stack')->getMasterRequest();

$this->Template->isEnabled = (bool) $user->useTwoFactor;
$this->Template->backupCodes = json_decode((string) $user->backupCodes, true) ?? array();
$this->Template->trustedDevices = $container->get('contao.security.two_factor.trusted_device_manager')->getTrustedDevices($user);
$this->Template->currentDevice = $request->cookies->get($container->getParameter('scheb_two_factor.trusted_device.cookie_name'));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@
</tr>
<?php foreach ($this->trustedDevices as $index => $trustedDevice): ?>
<tr class="<?= $index % 2 ? 'odd' : 'even' ?> hover-row">
<td class="tl_file_list"><?= $trustedDevice->getDeviceFamily() ?><?php if ($this->currentDevice === $trustedDevice->getCookieValue()): ?> (<?= $this->trans('MSC.thisDevice') ?>)<?php endif; ?></td>
<td class="tl_file_list"><?= $trustedDevice->getDeviceFamily() ?></td>
<td class="tl_file_list"><?= $trustedDevice->getUaFamily() ?></td>
<td class="tl_file_list"><?= $trustedDevice->getOsFamily() ?></td>
<td class="tl_file_list"><?= $trustedDevice->getCreated()->format(Contao\Config::get('datimFormat')) ?></td>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@
</tr>
<?php foreach ($this->trustedDevices as $trustedDevice): ?>
<tr>
<td><?= $trustedDevice->getDeviceFamily() ?><?php if ($this->currentDevice === $trustedDevice->getCookieValue()): ?> (<?= $this->trans('MSC.thisDevice') ?>)<?php endif; ?></td>
<td><?= $trustedDevice->getDeviceFamily() ?></td>
<td><?= $trustedDevice->getUaFamily() ?></td>
<td><?= $trustedDevice->getOsFamily() ?></td>
<td><?= $trustedDevice->getCreated()->format(Contao\Config::get('datimFormat')) ?></td>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,9 @@ public function onAuthenticationSuccess(Request $request, TokenInterface $token)
/** @var FirewallConfig $firewallConfig */
$firewallConfig = $this->firewallMap->getFirewallConfig($request);

$this->trustedDeviceManager->addTrustedDevice($token->getUser(), $firewallConfig->getName());
if (!$this->trustedDeviceManager->isTrustedDevice($user, $firewallConfig->getName())) {
$this->trustedDeviceManager->addTrustedDevice($token->getUser(), $firewallConfig->getName());
}
}

$response = new RedirectResponse($this->determineTargetUrl($request));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,19 +116,14 @@ public function authenticate(TokenInterface $token): TokenInterface
return $token;
}

$request = $this->requestStack->getMasterRequest();
$context = $this->authenticationContextFactory->create($request, $token, $this->providerKey);
$firewallName = $context->getFirewallName();
$user = $context->getUser();

// Skip two-factor authentication on trusted devices
if ($this->trustedDeviceManager->isTrustedDevice($user, $firewallName)) {
// Renew the token
$this->trustedDeviceManager->addTrustedDevice($user, $firewallName);

return $context->getToken();
if ($this->trustedDeviceManager->isTrustedDevice($token->getUser(), $this->providerKey)) {
return $token;
}

$request = $this->requestStack->getMasterRequest();
$context = $this->authenticationContextFactory->create($request, $token, $this->providerKey);

return $this->twoFactorAuthenticationHandler->beginTwoFactorAuthentication($context);
}

Expand Down
36 changes: 3 additions & 33 deletions core-bundle/src/Security/TwoFactor/TrustedDeviceManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
use Contao\CoreBundle\Entity\TrustedDevice;
use Contao\User;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\NonUniqueResultException;
use Scheb\TwoFactorBundle\Security\TwoFactor\Trusted\TrustedDeviceManagerInterface;
use Scheb\TwoFactorBundle\Security\TwoFactor\Trusted\TrustedDeviceTokenStorage;
use Symfony\Component\HttpFoundation\RequestStack;
Expand Down Expand Up @@ -51,25 +50,16 @@ public function addTrustedDevice($user, string $firewallName): void
return;
}

$version = (int) $user->trustedTokenVersion;
$oldCookieValue = $this->trustedTokenStorage->getCookieValue();
$userAgent = $this->requestStack->getMasterRequest()->headers->get('User-Agent');

$parser = Parser::create();
$parsedUserAgent = $parser->parse($userAgent);

$this->trustedTokenStorage->addTrustedToken($user->username, $firewallName, $version);

// Check if already an earlier version of the trusted device exists
try {
$trustedDevice = $this->findExistingTrustedDevice((int) $user->id, $oldCookieValue, $version) ?? new TrustedDevice($user, $version);
} catch (NonUniqueResultException $exception) {
$trustedDevice = new TrustedDevice($user, $version);
}
$this->trustedTokenStorage->addTrustedToken((string) $user->id, $firewallName, (int) $user->trustedTokenVersion);

$trustedDevice = new TrustedDevice($user);
$trustedDevice
->setCreated(new \DateTime())
->setCookieValue($this->trustedTokenStorage->getCookieValue())
->setUserAgent($userAgent)
->setUaFamily($parsedUserAgent->ua->family)
->setOsFamily($parsedUserAgent->os->family)
Expand All @@ -86,10 +76,7 @@ public function isTrustedDevice($user, string $firewallName): bool
return false;
}

$username = $user->username;
$version = (int) $user->trustedTokenVersion;

return $this->trustedTokenStorage->hasTrustedToken($username, $firewallName, $version);
return $this->trustedTokenStorage->hasTrustedToken((string) $user->id, $firewallName, (int) $user->trustedTokenVersion);
}

public function clearTrustedDevices(User $user): void
Expand Down Expand Up @@ -120,21 +107,4 @@ public function getTrustedDevices(User $user)
->execute()
;
}

public function findExistingTrustedDevice(int $userId, string $cookieValue, int $version)
{
return $this->entityManager
->createQueryBuilder()
->select('td')
->from(TrustedDevice::class, 'td')
->andWhere('td.userId = :userId')
->andWhere('td.cookieValue = :cookieValue')
->andWhere('td.version = :version')
->setParameter('userId', $userId)
->setParameter('cookieValue', $cookieValue)
->setParameter('version', $version)
->getQuery()
->getOneOrNullResult()
;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -334,12 +334,6 @@ public function testSkipsTwoFactorAuthenticationForTrustedDevices(): void
->willReturn(true)
;

$trustedDeviceManager
->expects($this->once())
->method('addTrustedDevice')
->with($user, 'contao_frontend')
;

$provider = $this->createUsernamePasswordProvider(null, $twoFactorHandler, $trustedDeviceManager);
$provider->authenticate($token);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ public function testIsTrustedDevice(): void
$tokenStorage
->expects($this->once())
->method('hasTrustedToken')
->with('foo', 'contao_backend', 1)
->with('1', 'contao_backend', 1)
->willReturn(true)
;

/** @var BackendUser $user */
$user = $this->mockClassWithProperties(BackendUser::class);
$user->username = 'foo';
$user->id = 1;
$user->trustedTokenVersion = 1;

$manager = new TrustedDeviceManager(
Expand Down