Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 55 additions & 1 deletion Classes/SecondFactor/Controller/LoginController.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Configuration\ConfigurationManager;
use Neos\Flow\Configuration\Exception\InvalidConfigurationTypeException;
use Neos\Flow\Http\ServerRequestAttributes;
use Neos\Flow\I18n\Translator;
use Neos\Flow\Mvc\Controller\ActionController;
use Neos\Flow\Mvc\Exception\StopActionException;
Expand All @@ -24,6 +25,8 @@
use Sandstorm\BackendUserManagement\SecondFactor\Domain\AuthenticationStatus;
use Sandstorm\BackendUserManagement\SecondFactor\Domain\Model\SecondFactor;
use Sandstorm\BackendUserManagement\SecondFactor\Domain\Repository\SecondFactorRepository;
use Psr\Log\LoggerInterface;
use Sandstorm\BackendUserManagement\SecondFactor\Service\SecondFactorService;
use Sandstorm\BackendUserManagement\SecondFactor\Service\SecondFactorSessionStorageService;
use Sandstorm\BackendUserManagement\SecondFactor\Service\TOTPService;
use Sandstorm\BackendUserManagement\SecondFactor\Service\WebAuthnService;
Expand Down Expand Up @@ -96,6 +99,18 @@ class LoginController extends ActionController
*/
protected $translator;

/**
* @Flow\Inject
* @var SecondFactorService
*/
protected $secondFactorService;

/**
* @Flow\Inject(name="Neos.Flow:SecurityLogger")
* @var LoggerInterface
*/
protected $securityLogger;

/**
* @Flow\InjectConfiguration(path="secondFactor.loginForm.stylesheets")
* @var array
Expand Down Expand Up @@ -140,11 +155,38 @@ public function checkSecondFactorAction(string $otp): void
{
$account = $this->securityContext->getAccount();

// Throttled before the code is checked: once over the limit, even the right code is rejected - otherwise
// the throttle would still tell a brute-forcer which code was right.
if (!$this->secondFactorService->attemptSecondFactorCheck($account)) {
$this->logSecondFactorFailure('TOTP check throttled - too many attempts', $account);
$this->addFlashMessage(
$this->translator->translateById(
'login.flashMessage.tooManyAttempts',
[],
null,
null,
'SecondFactor',
'Sandstorm.BackendUserManagement'
),
$this->translator->translateById(
'login.flashMessage.errorHeader',
[],
null,
null,
'SecondFactor',
'Sandstorm.BackendUserManagement'
),
Message::SEVERITY_ERROR
);
$this->redirectToInterceptedRequestOrBackend();
}

$isValidOtp = $this->enteredTotpMatchesAnyTotpFactor($otp, $account);

if ($isValidOtp) {
$this->secondFactorSessionStorageService->setAuthenticationStatus(AuthenticationStatus::AUTHENTICATED);
} else {
$this->logSecondFactorFailure('invalid TOTP code', $account);
$this->addFlashMessage(
$this->translator->translateById(
'login.flashMessage.invalidOtp',
Expand Down Expand Up @@ -443,6 +485,18 @@ public function webAuthnAuthenticateVerifyAction(string $assertion): string
// Helpers
// ------------------------------------------------------------------

private function logSecondFactorFailure(string $reason, Account $account): void
{
$clientIp = $this->request->getHttpRequest()->getAttribute(ServerRequestAttributes::CLIENT_IP);
$this->securityLogger->warning(
'Sandstorm/BackendUserManagement: Second factor login failed: ' . $reason,
[
'clientIp' => is_string($clientIp) ? $clientIp : 'unknown',
'accountIdentifier' => $account->getAccountIdentifier(),
]
);
}

private function jsonError(string $message, int $code): string
{
$this->response->setStatusCode($code);
Expand All @@ -467,7 +521,7 @@ private function enteredTotpMatchesAnyTotpFactor(string $enteredSecondFactor, Ac
/**
* @throws StopActionException
*/
private function redirectToInterceptedRequestOrBackend(): void
private function redirectToInterceptedRequestOrBackend(): never
{
$originalRequest = $this->securityContext->getInterceptedRequest();
if ($originalRequest !== null) {
Expand Down
61 changes: 23 additions & 38 deletions Classes/SecondFactor/Controller/PasswordlessLoginController.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Mvc\Controller\ActionController;
use Neos\Flow\Mvc\View\JsonView;
use Neos\Flow\Security\Authentication\TokenInterface;
use Neos\Flow\Security\Authentication\AuthenticationManagerInterface;
use Neos\Flow\Security\Context as SecurityContext;
use Sandstorm\BackendUserManagement\SecondFactor\Domain\AuthenticationStatus;
use Neos\Flow\Security\Exception\AuthenticationRequiredException;
use Sandstorm\BackendUserManagement\SecondFactor\Security\Token\WebAuthnPasswordlessToken;
use Sandstorm\BackendUserManagement\SecondFactor\Service\SecondFactorSessionStorageService;
use Sandstorm\BackendUserManagement\SecondFactor\Service\WebAuthnService;
Expand All @@ -22,7 +22,9 @@
* Both actions are reachable while logged out (this controller is intentionally NOT behind
* the Neos.Neos:Backend request pattern). They are hard-gated by the
* `secondFactor.webAuthn.passwordlessLoginEnabled` setting (off by default) so that, while disabled, no
* one can authenticate through this path even if the UI button were somehow present.
* one can authenticate through this path even if the UI button were somehow present. The
* {@see \Sandstorm\BackendUserManagement\SecondFactor\Security\Authentication\WebAuthnPasswordlessProvider}
* checks the setting again, as its token is active on every request.
*/
class PasswordlessLoginController extends ActionController
{
Expand All @@ -36,6 +38,12 @@ class PasswordlessLoginController extends ActionController
*/
protected $securityContext;

/**
* @Flow\Inject
* @var AuthenticationManagerInterface
*/
protected $authenticationManager;

/**
* @Flow\Inject
* @var WebAuthnService
Expand Down Expand Up @@ -80,55 +88,32 @@ public function optionsAction(): string
}

/**
* Ceremony step 2: verify the assertion, resolve the account, authenticate the parallel
* WebAuthn token (which logs the user into the Neos backend without a password), and
* return the URI for the client to redirect to.
* Ceremony step 2: the assertion arrives as the internal argument
* {@see WebAuthnPasswordlessToken::ASSERTION_FIELD}, which puts the token into AUTHENTICATION_NEEDED.
* Flow's AuthenticationManager then runs the WebAuthnPasswordlessProvider (verification, session id
* renewal, session tagging). Here we only report the outcome and the URI to redirect to.
*
* @Flow\SkipCsrfProtection
*/
public function verifyAction(string $assertion): string
public function verifyAction(): string
{
if (!$this->passwordlessLoginEnabled) {
return $this->jsonError('Passwordless login is disabled', 403);
}

$serialized = $this->secondFactorSessionStorageService->getValue(
SecondFactorSessionStorageService::SESSION_OBJECT_WEBAUTHN_PASSWORDLESS_OPTIONS
);
if (!is_string($serialized)) {
return $this->jsonError('No passwordless login in progress', 400);
}
$options = $this->webAuthnService->requestOptionsFromJson($serialized);

try {
$account = $this->webAuthnService->verifyPasswordlessAssertion(
$assertion,
$options,
$this->request->getHttpRequest()
);
} catch (\Throwable $e) {
return $this->jsonError($e->getMessage(), 400);
// usually already done by the PolicyEnforcement interceptor - a no-op then
$this->authenticationManager->authenticate();
} catch (AuthenticationRequiredException) {
// evaluated via the token below
}

$token = $this->securityContext->getAuthenticationTokensOfType(WebAuthnPasswordlessToken::class)[0] ?? null;
if ($token === null) {
return $this->jsonError('Passwordless authentication token not available', 500);
if ($token === null || !$token->isAuthenticated()) {
// the reason is in the security log - don't hand webauthn-lib details to the client
return $this->jsonError('Passkey login failed', 401);
}

// Authenticate the parallel token with the resolved backend account and persist it to
// the session so the authentication survives the redirect to the backend.
$token->setAccount($account);
$token->setAuthenticationStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL);
$this->securityContext->refreshTokens();

// A user-verified passkey is itself multi-factor, so it also satisfies the 2FA gate.
$this->secondFactorSessionStorageService->initializeTwoFactorSessionObject();
$this->secondFactorSessionStorageService->setAuthenticationStatus(AuthenticationStatus::AUTHENTICATED);

$this->secondFactorSessionStorageService->removeValue(
SecondFactorSessionStorageService::SESSION_OBJECT_WEBAUTHN_PASSWORDLESS_OPTIONS
);

$this->response->setContentType('application/json');
return json_encode([
'status' => 'ok',
Expand Down
Loading
Loading