diff --git a/Classes/SecondFactor/Controller/LoginController.php b/Classes/SecondFactor/Controller/LoginController.php index 7dbf83c..9a4df7c 100644 --- a/Classes/SecondFactor/Controller/LoginController.php +++ b/Classes/SecondFactor/Controller/LoginController.php @@ -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; @@ -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; @@ -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 @@ -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', @@ -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); @@ -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) { diff --git a/Classes/SecondFactor/Controller/PasswordlessLoginController.php b/Classes/SecondFactor/Controller/PasswordlessLoginController.php index a03c872..21edc78 100644 --- a/Classes/SecondFactor/Controller/PasswordlessLoginController.php +++ b/Classes/SecondFactor/Controller/PasswordlessLoginController.php @@ -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; @@ -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 { @@ -36,6 +38,12 @@ class PasswordlessLoginController extends ActionController */ protected $securityContext; + /** + * @Flow\Inject + * @var AuthenticationManagerInterface + */ + protected $authenticationManager; + /** * @Flow\Inject * @var WebAuthnService @@ -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', diff --git a/Classes/SecondFactor/Security/Authentication/WebAuthnPasswordlessProvider.php b/Classes/SecondFactor/Security/Authentication/WebAuthnPasswordlessProvider.php index 1305f5d..a385c05 100644 --- a/Classes/SecondFactor/Security/Authentication/WebAuthnPasswordlessProvider.php +++ b/Classes/SecondFactor/Security/Authentication/WebAuthnPasswordlessProvider.php @@ -2,24 +2,82 @@ namespace Sandstorm\BackendUserManagement\SecondFactor\Security\Authentication; +use Neos\Flow\Annotations as Flow; +use Neos\Flow\Core\Bootstrap; +use Neos\Flow\Http\HttpRequestHandlerInterface; +use Neos\Flow\Http\ServerRequestAttributes; +use Neos\Flow\Persistence\PersistenceManagerInterface; +use Neos\Flow\Security\Account; +use Neos\Flow\Security\AccountRepository; use Neos\Flow\Security\Authentication\Provider\AbstractProvider; use Neos\Flow\Security\Authentication\TokenInterface; +use Neos\Flow\Security\Exception\UnsupportedAuthenticationTokenException; +use Psr\Http\Message\ServerRequestInterface; +use Psr\Log\LoggerInterface; +use Sandstorm\BackendUserManagement\SecondFactor\Domain\AuthenticationStatus; use Sandstorm\BackendUserManagement\SecondFactor\Security\Token\WebAuthnPasswordlessToken; +use Sandstorm\BackendUserManagement\SecondFactor\Service\PasswordlessAssertionRejectedException; +use Sandstorm\BackendUserManagement\SecondFactor\Service\SecondFactorSessionStorageService; +use Sandstorm\BackendUserManagement\SecondFactor\Service\WebAuthnService; /** * Authentication provider for usernameless passwordless passkey login. * - * The actual WebAuthn verification and token authentication happen in the - * {@see \Sandstorm\BackendUserManagement\SecondFactor\Controller\PasswordlessLoginController} - * (it needs the session-stored challenge and the webauthn-lib validator). This provider - * exists so the framework registers the {@see WebAuthnPasswordlessToken} for this provider - * name, keeps it active (no request pattern), and restores it from the session on later - * requests. With the `oneToken` authentication strategy, an authenticated parallel token is - * enough for the request to count as authenticated; the resolved account is a regular - * `Neos.Neos:Backend` account, so roles and the current Neos user resolve normally. + * Verifies the WebAuthn assertion carried by the {@see WebAuthnPasswordlessToken} against the challenge + * stored in the session by {@see \Sandstorm\BackendUserManagement\SecondFactor\Controller\PasswordlessLoginController::optionsAction()}. + * It runs inside Flow's AuthenticationProviderManager, which on success renews the session id and tags the + * session with the account (so Neos can destroy it on deactivate / delete / password change). + * + * With the `oneToken` authentication strategy an authenticated parallel token is enough for the request to + * count as authenticated; the resolved account is a regular `Neos.Neos:Backend` account, so roles and the + * current Neos user resolve normally. */ class WebAuthnPasswordlessProvider extends AbstractProvider { + private const LOGGING_PREFIX = 'Sandstorm/BackendUserManagement: '; + + /** + * @Flow\Inject + * @var WebAuthnService + */ + protected $webAuthnService; + + /** + * @Flow\Inject + * @var SecondFactorSessionStorageService + */ + protected $secondFactorSessionStorageService; + + /** + * @Flow\Inject + * @var Bootstrap + */ + protected $bootstrap; + + /** + * @Flow\Inject + * @var AccountRepository + */ + protected $accountRepository; + + /** + * @Flow\Inject + * @var PersistenceManagerInterface + */ + protected $persistenceManager; + + /** + * @Flow\Inject(name="Neos.Flow:SecurityLogger") + * @var LoggerInterface + */ + protected $securityLogger; + + /** + * @Flow\InjectConfiguration(path="secondFactor.webAuthn.passwordlessLoginEnabled", package="Sandstorm.BackendUserManagement") + * @var bool + */ + protected $passwordlessLoginEnabled = false; + /** * @return array */ @@ -29,18 +87,96 @@ public function getTokenClassNames() } /** - * The AuthenticationProviderManager only calls this for tokens in state - * AUTHENTICATION_NEEDED. The controller drives this token straight from - * NO_CREDENTIALS_GIVEN to AUTHENTICATION_SUCCESSFUL, so there is nothing to do here: - * never downgrade an already-successful (session-restored) token. + * Only called by the AuthenticationProviderManager for tokens in state AUTHENTICATION_NEEDED, i.e. when the + * request carried an assertion (see WebAuthnPasswordlessToken::updateCredentials()). */ public function authenticate(TokenInterface $authenticationToken) { if (!$authenticationToken instanceof WebAuthnPasswordlessToken) { + throw new UnsupportedAuthenticationTokenException( + sprintf('This provider cannot authenticate the given token "%s".', get_class($authenticationToken)), + 1793795726 + ); + } + + $httpRequest = $this->currentHttpRequest(); + + // The token is active on every request - so this is checked here, not only in the controller. + if (!$this->passwordlessLoginEnabled) { + $this->rejectLogin($authenticationToken, 'passwordless login is disabled', $httpRequest); + return; + } + + $assertion = $authenticationToken->getCredentials()['assertion'] ?? null; + $serializedOptions = $this->secondFactorSessionStorageService->getValue( + SecondFactorSessionStorageService::SESSION_OBJECT_WEBAUTHN_PASSWORDLESS_OPTIONS + ); + if (!is_string($assertion) || !is_string($serializedOptions) || $httpRequest === null) { + $this->rejectLogin($authenticationToken, 'no passwordless login in progress', $httpRequest); return; } - if ($authenticationToken->getAuthenticationStatus() !== TokenInterface::AUTHENTICATION_SUCCESSFUL) { - $authenticationToken->setAuthenticationStatus(TokenInterface::NO_CREDENTIALS_GIVEN); + // Single use: the challenge is gone after one verification attempt, whatever its outcome. + $this->secondFactorSessionStorageService->removeValue( + SecondFactorSessionStorageService::SESSION_OBJECT_WEBAUTHN_PASSWORDLESS_OPTIONS + ); + + try { + $account = $this->webAuthnService->verifyPasswordlessAssertion( + $assertion, + $this->webAuthnService->requestOptionsFromJson($serializedOptions), + $httpRequest + ); + } catch (\Throwable $exception) { + // Only a known credential of an active backend account yields an account here - like Flow's + // password provider, which counts failures only for accounts it found via findActiveBy...(). + $knownAccount = $exception instanceof PasswordlessAssertionRejectedException ? $exception->account : null; + if ($knownAccount !== null) { + $this->recordAuthenticationAttempt($knownAccount, TokenInterface::WRONG_CREDENTIALS); + } + $this->rejectLogin( + $authenticationToken, + sprintf('%s (%s)', $exception->getMessage(), $exception->getCode()), + $httpRequest, + $knownAccount + ); + return; + } + + $this->recordAuthenticationAttempt($account, TokenInterface::AUTHENTICATION_SUCCESSFUL); + $authenticationToken->setAccount($account); + $authenticationToken->setAuthenticationStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL); + + // A user-verified passkey is itself multi-factor, so it also satisfies the 2FA gate. + $this->secondFactorSessionStorageService->initializeTwoFactorSessionObject(); + $this->secondFactorSessionStorageService->setAuthenticationStatus(AuthenticationStatus::AUTHENTICATED); + } + + /** + * Same as PersistedUsernamePasswordProvider: a failure increases Account::$failedAuthenticationCount, + * a success resets it and sets lastSuccessfulAuthenticationDate. + */ + private function recordAuthenticationAttempt(Account $account, int $authenticationStatus): void + { + $account->authenticationAttempted($authenticationStatus); + $this->accountRepository->update($account); + // persisted even if the request turns out to be a "safe" one + $this->persistenceManager->allowObject($account); + } + + private function rejectLogin(WebAuthnPasswordlessToken $token, string $reason, ?ServerRequestInterface $httpRequest, ?Account $account = null): void + { + $token->setAuthenticationStatus(TokenInterface::WRONG_CREDENTIALS); + $clientIp = $httpRequest?->getAttribute(ServerRequestAttributes::CLIENT_IP); + $context = ['clientIp' => is_string($clientIp) ? $clientIp : 'unknown']; + if ($account !== null) { + $context['accountIdentifier'] = $account->getAccountIdentifier(); } + $this->securityLogger->warning(self::LOGGING_PREFIX . 'Passwordless passkey login failed: ' . $reason, $context); + } + + private function currentHttpRequest(): ?ServerRequestInterface + { + $requestHandler = $this->bootstrap->getActiveRequestHandler(); + return $requestHandler instanceof HttpRequestHandlerInterface ? $requestHandler->getHttpRequest() : null; } } diff --git a/Classes/SecondFactor/Security/Token/WebAuthnPasswordlessToken.php b/Classes/SecondFactor/Security/Token/WebAuthnPasswordlessToken.php index d2d029c..3d29ca0 100644 --- a/Classes/SecondFactor/Security/Token/WebAuthnPasswordlessToken.php +++ b/Classes/SecondFactor/Security/Token/WebAuthnPasswordlessToken.php @@ -4,26 +4,34 @@ use Neos\Flow\Mvc\ActionRequest; use Neos\Flow\Security\Authentication\Token\AbstractToken; +use Neos\Utility\ObjectAccess; /** * Authentication token for usernameless, passwordless passkey login. * - * Unlike the username/password token, this token carries no credentials extracted - * from the request: the WebAuthn assertion is verified by the - * {@see \Sandstorm\BackendUserManagement\SecondFactor\Controller\PasswordlessLoginController}, - * which then sets the resolved account on this token and marks it authenticated. + * Works like Flow's UsernamePassword token: it picks the WebAuthn assertion up from a namespaced + * internal POST argument and marks itself AUTHENTICATION_NEEDED, so the regular + * AuthenticationProviderManager runs the * {@see \Sandstorm\BackendUserManagement\SecondFactor\Security\Authentication\WebAuthnPasswordlessProvider} - * is registered for this token so the framework instantiates and persists it. + * - including session id renewal and session tagging on success. + * + * The argument is namespaced on purpose: the token has no request pattern, so it is active on every + * request. A plain `assertion` argument would also match the 2nd-factor WebAuthn endpoint. */ class WebAuthnPasswordlessToken extends AbstractToken { - /** - * No credentials are read from the request — the controller performs the WebAuthn - * ceremony and authenticates this token directly. Must NOT change the authentication - * status here, otherwise refreshTokens() (which calls updateCredentials on every active - * token) would reset a token the controller just authenticated. - */ + public const ASSERTION_FIELD = '__authentication.Sandstorm.BackendUserManagement.Passwordless.assertion'; + public function updateCredentials(ActionRequest $actionRequest) { + if ($actionRequest->getHttpRequest()->getMethod() !== 'POST') { + return; + } + $allArguments = array_merge($actionRequest->getArguments(), $actionRequest->getInternalArguments()); + $assertion = ObjectAccess::getPropertyPath($allArguments, self::ASSERTION_FIELD); + if (is_string($assertion) && $assertion !== '') { + $this->credentials['assertion'] = $assertion; + $this->setAuthenticationStatus(self::AUTHENTICATION_NEEDED); + } } } diff --git a/Classes/SecondFactor/Service/PasswordlessAssertionRejectedException.php b/Classes/SecondFactor/Service/PasswordlessAssertionRejectedException.php new file mode 100644 index 0000000..803b55c --- /dev/null +++ b/Classes/SecondFactor/Service/PasswordlessAssertionRejectedException.php @@ -0,0 +1,21 @@ +getMessage(), 1793796650, $previous); + } +} diff --git a/Classes/SecondFactor/Service/SecondFactorService.php b/Classes/SecondFactor/Service/SecondFactorService.php index f304af8..a11ef03 100644 --- a/Classes/SecondFactor/Service/SecondFactorService.php +++ b/Classes/SecondFactor/Service/SecondFactorService.php @@ -3,8 +3,10 @@ namespace Sandstorm\BackendUserManagement\SecondFactor\Service; use Neos\Flow\Annotations as Flow; +use Neos\Flow\Persistence\PersistenceManagerInterface; use Neos\Flow\Security\Account; use Sandstorm\BackendUserManagement\SecondFactor\Domain\Repository\SecondFactorRepository; +use Sandstorm\BackendUserManagement\UserManagement\Application\Throttle; class SecondFactorService { @@ -32,6 +34,38 @@ class SecondFactorService */ protected $secondFactorRepository; + /** + * @Flow\Inject + * @var Throttle + */ + protected $throttle; + + /** + * @Flow\Inject + * @var PersistenceManagerInterface + */ + protected $persistenceManager; + + /** + * @Flow\InjectConfiguration(path="secondFactor.throttle.perAccount") + * @var array{limit: int, window: string} + */ + protected $throttlePerAccount; + + /** + * Consume one second-factor check for the account. Returns false if the account exceeded its limit - the code must + * then not be checked at all. Keyed by the account's persistence identifier, so a new session (cancel + log in + * again) doesn't get a fresh limit. + */ + public function attemptSecondFactorCheck(Account $account): bool + { + return $this->throttle->attempt( + 'secondFactor:account:' . $this->persistenceManager->getIdentifierByObject($account), + (int)$this->throttlePerAccount['limit'], + (string)$this->throttlePerAccount['window'] + ); + } + /** * Check if the second factor is enforced for the given account. * diff --git a/Classes/SecondFactor/Service/WebAuthnService.php b/Classes/SecondFactor/Service/WebAuthnService.php index ce30663..48f006f 100644 --- a/Classes/SecondFactor/Service/WebAuthnService.php +++ b/Classes/SecondFactor/Service/WebAuthnService.php @@ -301,12 +301,16 @@ public function createPasswordlessAuthenticationOptions(string $hostname): Publi * Verify a usernameless assertion and resolve the Neos backend account it belongs to. * * The assertion carries both the credential id and a user handle. We look the credential - * up by its id first (proving we actually stored it), then let the library verify the - * assertion against that credential's stored user handle, and finally map the user handle - * (the account's persistence identifier) back to the Flow account. Only Neos backend - * accounts may use this login path. + * up by its id first (proving we actually stored it), map its stored user handle (the + * account's persistence identifier) back to the Flow account, and only then let the library + * verify the assertion against that credential. Only active Neos backend accounts may use + * this login path. * - * @throws \Throwable when validation fails or no matching backend account exists + * The account is resolved before the signature check, so a rejected assertion can be + * counted on it ({@see PasswordlessAssertionRejectedException}). + * + * @throws PasswordlessAssertionRejectedException when the assertion of a known credential does not verify + * @throws \Throwable when the credential is unknown or no matching active backend account exists */ public function verifyPasswordlessAssertion( string $assertionResponseJson, @@ -327,21 +331,27 @@ public function verifyPasswordlessAssertion( } $userHandle = $credentialSource->userHandle; + $account = $this->resolveBackendAccountByUserHandle($userHandle); + $validator = AuthenticatorAssertionResponseValidator::create( $this->buildCeremonyStepManagerFactory()->requestCeremony() ); - $updatedCredential = $validator->check( - $credentialSource, - $authenticatorResponse, - $options, - $request->getUri()->getHost(), - $userHandle - ); + try { + $updatedCredential = $validator->check( + $credentialSource, + $authenticatorResponse, + $options, + $request->getUri()->getHost(), + $userHandle + ); + } catch (\Throwable $exception) { + throw new PasswordlessAssertionRejectedException($account, $exception); + } // Persist the bumped counter so replay protection stays effective across logins. $this->credentialSourceRepository->saveCredential($updatedCredential); - return $this->resolveBackendAccountByUserHandle($userHandle); + return $account; } /** @@ -361,6 +371,11 @@ public function resolveBackendAccountByUserHandle(string $userHandle): Account if ($account->getAuthenticationProviderName() !== 'Neos.Neos:Backend') { throw new \RuntimeException('Passkey does not belong to a Neos backend account', 1751200003); } + // Guard: a deactivated (expired) account must not log in - the password provider checks this via + // AccountRepository::findActiveByAccountIdentifierAndAuthenticationProviderName(), we have to do it ourselves. + if (!$account->isActive()) { + throw new \RuntimeException('Passkey belongs to an inactive account', 1793795361); + } return $account; } diff --git a/Classes/UserManagement/Application/PasswordResetRequestHandler.php b/Classes/UserManagement/Application/PasswordResetRequestHandler.php index c7d0ba5..51ae715 100644 --- a/Classes/UserManagement/Application/PasswordResetRequestHandler.php +++ b/Classes/UserManagement/Application/PasswordResetRequestHandler.php @@ -78,6 +78,15 @@ public function handle(string $usernameOrEmail, string $clientIp): bool return false; } + // before resolving accounts - no token may be issued for a mail that can't be sent. Same answer as always. + if (!$this->userMailer->isBaseUriConfigured()) { + $this->securityLogger->error( + 'Sandstorm/BackendUserManagement: forgot password requested, but no mail sent - no base URI configured ' + . '(userManagement.mail.baseUri or Neos.Flow.http.baseUri).' + ); + return true; + } + foreach ($this->resolveAccountsByRecipient($input) as $recipient => $accounts) { $this->sendMail($recipient, $accounts); } diff --git a/Classes/UserManagement/Application/UserCommandService.php b/Classes/UserManagement/Application/UserCommandService.php index df3548f..afd7555 100644 --- a/Classes/UserManagement/Application/UserCommandService.php +++ b/Classes/UserManagement/Application/UserCommandService.php @@ -317,6 +317,7 @@ public function sendPasswordMail(User $user, UserActionType $action): void if ($accounts === []) { throw new UserManagementException('error.noActiveAccount', 1760000106); } + $this->userMailer->requireBaseUri(); $links = []; foreach ($accounts as $account) { $links[] = [ @@ -346,6 +347,7 @@ public function sendEmailVerificationMail(User $user): void if ($accounts === []) { throw new UserManagementException('error.noActiveAccount', 1760000106); } + $this->userMailer->requireBaseUri(); // the token needs an account to hang on to; any account of the user proves the same inbox $token = $this->tokenService->issue($accounts[0], UserActionType::VERIFY_EMAIL, $primaryEmail->getIdentifier()); $this->userMailer->sendEmailVerification( diff --git a/Classes/UserManagement/Application/UserMailer.php b/Classes/UserManagement/Application/UserMailer.php index f196ee8..ae019b1 100644 --- a/Classes/UserManagement/Application/UserMailer.php +++ b/Classes/UserManagement/Application/UserMailer.php @@ -7,7 +7,6 @@ use DateTimeImmutable; use Flowpack\JobQueue\Common\Job\JobManager; use Neos\Flow\Annotations as Flow; -use Neos\Flow\Http\BaseUriProvider; use Neos\Flow\I18n\Locale; use Neos\Flow\I18n\Service as I18nService; use Neos\Fusion\View\FusionView; @@ -48,8 +47,17 @@ class UserMailer #[Flow\Inject] protected MailerService $mailerService; - #[Flow\Inject] - protected BaseUriProvider $baseUriProvider; + /** + * Base URI of the links in mails. Falls back to Neos.Flow.http.baseUri. Never taken from the current request: + * its Host / X-Forwarded-Host header is attacker-controlled - a forged one on "forgot password" would send the + * victim a valid token pointing to the attacker's domain. + * Typed mixed: an unset %env:...% placeholder yields false, not null. + */ + #[Flow\InjectConfiguration(path: 'userManagement.mail.baseUri')] + protected mixed $mailBaseUri = null; + + #[Flow\InjectConfiguration(path: 'http.baseUri', package: 'Neos.Flow')] + protected mixed $flowBaseUri = null; #[Flow\Inject] protected I18nService $i18nService; @@ -127,6 +135,8 @@ public function sendTestMail(string $recipient, ?User $user): void { $this->send($recipient, $user, 'testMail', [ 'name' => $user?->getName()->getFullName() ?? '', + // a link like in the real mails - so the test mail also fails without a base URI, and its host can be checked + 'loginUri' => $this->buildUri(self::LOGIN_PATH), ]); } @@ -192,8 +202,40 @@ private function render(string $fusionPath, array $variables, string $localeIden } } + public function isBaseUriConfigured(): bool + { + return $this->configuredBaseUri() !== null; + } + + /** + * Callers check this BEFORE issuing tokens - otherwise a valid token would be stored for a mail that is never sent. + * + * @throws UserManagementException if no base URI is configured + */ + public function requireBaseUri(): string + { + $baseUri = $this->configuredBaseUri(); + if ($baseUri === null) { + throw new UserManagementException('error.baseUriMissing', 1793800007); + } + return $baseUri; + } + + /** + * @throws UserManagementException if no base URI is configured + */ private function buildUri(string $path): string { - return rtrim((string) $this->baseUriProvider->getConfiguredBaseUriOrFallbackToCurrentRequest(), '/') . $path; + return rtrim($this->requireBaseUri(), '/') . $path; + } + + private function configuredBaseUri(): ?string + { + foreach ([$this->mailBaseUri, $this->flowBaseUri] as $baseUri) { + if (is_string($baseUri) && trim($baseUri) !== '') { + return trim($baseUri); + } + } + return null; } } diff --git a/Classes/UserManagement/Command/UserManagementCommandController.php b/Classes/UserManagement/Command/UserManagementCommandController.php index f767592..2111011 100644 --- a/Classes/UserManagement/Command/UserManagementCommandController.php +++ b/Classes/UserManagement/Command/UserManagementCommandController.php @@ -18,7 +18,7 @@ /** * User management: send password mails, prune tokens, report duplicate emails, align usernames with emails. * - * Links in mails are built from Neos.Flow.http.baseUri - it must be configured for these commands. + * Links in mails are built from userManagement.mail.baseUri (fallback: Neos.Flow.http.baseUri) - it must be configured. */ class UserManagementCommandController extends CommandController { diff --git a/Classes/UserManagement/Controller/ModuleController.php b/Classes/UserManagement/Controller/ModuleController.php index 6ee2063..ec4d0e4 100644 --- a/Classes/UserManagement/Controller/ModuleController.php +++ b/Classes/UserManagement/Controller/ModuleController.php @@ -143,6 +143,13 @@ public function sendTestMailAction(): void try { $this->userMailer->sendTestMail($primaryEmail->getIdentifier(), $currentUser); $this->addTranslatedFlashMessage('flash.testMailSent', [$primaryEmail->getIdentifier()]); + } catch (UserManagementException $exception) { + // e.g. no base URI configured - the message is a translation id + $this->addFlashMessage( + $this->translate($exception->getMessage()), + $this->translate('flash.testMailFailed'), + Message::SEVERITY_ERROR + ); } catch (\Throwable $exception) { $this->addFlashMessage( $exception->getMessage(), @@ -625,6 +632,9 @@ private function mailConfigurationWarning(): ?string if ($this->mailFromAddress === null || $this->mailFromAddress === '') { return $this->translate('warning.mailFromMissing'); } + if (!$this->userMailer->isBaseUriConfigured()) { + return $this->translate('warning.baseUriMissing'); + } if ($this->mailerDsn === null || $this->mailerDsn === '' || str_starts_with($this->mailerDsn, 'null://')) { return $this->translate('warning.mailerDsnMissing'); } diff --git a/Configuration/Caches.yaml b/Configuration/Caches.yaml index ebb2238..4456a33 100644 --- a/Configuration/Caches.yaml +++ b/Configuration/Caches.yaml @@ -1,4 +1,4 @@ -# State of the forgot-password throttle (symfony/rate-limiter). Local file system by default - with several Neos +# State of the forgot-password and second-factor (TOTP) throttles (symfony/rate-limiter). Local file system by default - with several Neos # containers, use a shared backend (e.g. Neos\Cache\Backend\RedisBackend), see README "Running several Neos containers". Sandstorm_BackendUserManagement_Throttle: backend: Neos\Cache\Backend\FileBackend diff --git a/Configuration/Settings.2FA.yaml b/Configuration/Settings.2FA.yaml index cbefbd2..4a9c860 100644 --- a/Configuration/Settings.2FA.yaml +++ b/Configuration/Settings.2FA.yaml @@ -13,6 +13,15 @@ Sandstorm: # (now - leeway) through (now + leeway). 0 disables leeway (exact match only). # MUST be lower than the 30s TOTP period; values >= 30 are clamped to 29. totpLeewayInSeconds: 0 + # Throttle for checking a TOTP code during login (symfony/rate-limiter, sliding window), per account - so it also + # holds across new sessions / login attempts. Without it, someone who knows the password can brute-force the + # 6-digit code. Every check counts, also successful ones. The limiter state is kept in the Flow cache + # Sandstorm_BackendUserManagement_Throttle, locks use userManagement.throttle.lockStore. + # Side effect: whoever knows the password can block the TOTP login of that account for the window. + throttle: + perAccount: + limit: 5 + window: 'PT5M' webAuthn: # Human-readable relying party name shown in the browser's WebAuthn prompt. diff --git a/Configuration/Settings.UserManagement.yaml b/Configuration/Settings.UserManagement.yaml index 70221a9..de603a9 100644 --- a/Configuration/Settings.UserManagement.yaml +++ b/Configuration/Settings.UserManagement.yaml @@ -40,9 +40,14 @@ Sandstorm: minimumLength: 1 maximumLength: 255 mail: - # REQUIRED once enabled - sending fails loudly if unset. - # Links in mails are built from Neos.Flow.http.baseUri (required for the CLI commands) or the current request. + # Base URI of the links in mails, e.g. 'https://cms.example.com/'. Only required if Neos.Flow.http.baseUri is not + # set - which is the case in multi-site installations: there Neos.Flow.http.baseUri would also change the + # resource and absolute URIs of every site. Without either, no password / confirmation mail is sent. Never taken + # from the current request - its Host header is attacker-controlled, so "forgot password" could send a valid + # token to the attacker's domain. + baseUri: ~ from: + # REQUIRED once enabled - sending fails loudly if unset. address: ~ name: 'Neos' diff --git a/Configuration/Settings.yaml b/Configuration/Settings.yaml index f14ac5e..73742fb 100644 --- a/Configuration/Settings.yaml +++ b/Configuration/Settings.yaml @@ -58,9 +58,10 @@ Neos: patternOptions: controllerObjectNamePattern: 'Sandstorm\BackendUserManagement\SecondFactor\Controller\(LoginController|ModuleController)' # Parallel provider for usernameless passwordless passkey login. It has NO request - # pattern, so its token is always active and can be authenticated in-request by the - # PasswordlessLoginController; and NO entry point, so the existing Neos.Neos:Backend - # WebRedirect still serves the login screen. With Neos' `oneToken` strategy, an + # pattern, so its token is always active and is authenticated by Flow's + # AuthenticationProviderManager as soon as a POST carries the namespaced assertion + # (WebAuthnPasswordlessToken::ASSERTION_FIELD); and NO entry point, so the existing + # Neos.Neos:Backend WebRedirect still serves the login screen. With Neos' `oneToken` strategy, an # authenticated token here logs the (Neos.Neos:Backend) account into the backend. 'Sandstorm.BackendUserManagement:PasswordlessWebAuthn': provider: 'Sandstorm\BackendUserManagement\SecondFactor\Security\Authentication\WebAuthnPasswordlessProvider' diff --git a/README.md b/README.md index 5a786ec..ab06258 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,8 @@ All settings with their defaults: [`Settings.UserManagement.yaml`](Configuration and [username follows the email](#username-follows-the-email). Mails are sent via [neos/symfonymailer](https://github.com/neos/symfonymailer) - configure `Neos.SymfonyMailer.mailer.dsn` and: +To turn it off: `Sandstorm.BackendUserManagement.userManagement.enabled: false`. + ```yaml Sandstorm: BackendUserManagement: @@ -45,18 +47,16 @@ Sandstorm: # only accounts of these providers are managed authenticationProviders: ['Neos.Neos:Backend'] mail: + # required for multisite setups which cant set Neos.Flow.http.baseUri + baseUri: 'https://cms.example.com/' from: address: 'no-reply@example.com' # required - without it, no mail is sent (error in the security log) name: 'My CMS' - -Neos: - Flow: - http: - # required for the CLI commands (links in mails) - baseUri: 'https://cms.example.com/' ``` -To turn it off: `Sandstorm.BackendUserManagement.userManagement.enabled: false`. +> **Links in mails need a base URI:** `userManagement.mail.baseUri` or `Neos.Flow.http.baseUri` has to be set. +> Without either, no password, confirmation or test mail is sent - the module shows a warning and "forgot password" +> logs an error in the security log. This is for security reasons. Add a daily cron job for `./flow usermanagement:prunetokens`. @@ -234,7 +234,7 @@ with the same or a subset of their roles. Nobody can delete, deactivate or lock ### CLI -The mail commands require `userManagement.enabled` and `Neos.Flow.http.baseUri`. Commands taking a `` also +The mail commands require `userManagement.enabled` and `userManagement.mail.baseUri` (or `Neos.Flow.http.baseUri`). Commands taking a `` also accept `--authentication-provider` (default: first of `authenticationProviders`). | Command | | @@ -267,8 +267,18 @@ Sandstorm: issuerName: '' # accepted clock drift in seconds (codes from now-leeway to now+leeway); 0 = exact; values >= 30 are clamped to 29 totpLeewayInSeconds: 0 + # TOTP checks during login, per account (sliding window) - against brute-forcing the code once the password is known + throttle: + perAccount: + limit: 5 + window: 'PT5M' ``` +Every check counts, also successful ones; once over the limit, even a valid code is rejected until the window has +passed. Keyed by account, so a new login doesn't reset it - which also means that whoever knows the password can block +the TOTP login of that account for the window. Passkeys are not throttled (nothing to guess). Limiter state and lock +are shared with the [forgot password throttle](#throttle) - see there for several Neos containers. + ### Passkeys (WebAuthn / FIDO2) Platform authenticators (Touch ID, Windows Hello) and security keys (e.g. YubiKey). Requires HTTPS; an IP address diff --git a/Resources/Private/Fusion/SecondFactor/Integration/Controller/Module/NewTotp.fusion b/Resources/Private/Fusion/SecondFactor/Integration/Controller/Module/NewTotp.fusion index ef1bdc1..19ec7cd 100644 --- a/Resources/Private/Fusion/SecondFactor/Integration/Controller/Module/NewTotp.fusion +++ b/Resources/Private/Fusion/SecondFactor/Integration/Controller/Module/NewTotp.fusion @@ -10,7 +10,7 @@ Sandstorm.BackendUserManagement.SecondFactor.ModuleController.newTotp = Sandstor

- {I18n.id('module.new.user-context').package('Sandstorm.BackendUserManagement').source('SecondFactor').arguments([currentUser ? currentUser.name.fullName : accountIdentifier]).translate()} + {I18n.id('module.new.user-context').package('Sandstorm.BackendUserManagement').source('SecondFactor').arguments([String.htmlSpecialChars(currentUser ? currentUser.name.fullName : accountIdentifier)]).translate()}

1 diff --git a/Resources/Private/Fusion/SecondFactor/Integration/Controller/Module/NewWebAuthn.fusion b/Resources/Private/Fusion/SecondFactor/Integration/Controller/Module/NewWebAuthn.fusion index fc4981b..bd1c0a9 100644 --- a/Resources/Private/Fusion/SecondFactor/Integration/Controller/Module/NewWebAuthn.fusion +++ b/Resources/Private/Fusion/SecondFactor/Integration/Controller/Module/NewWebAuthn.fusion @@ -16,7 +16,7 @@ Sandstorm.BackendUserManagement.SecondFactor.ModuleController.newWebAuthn = Sand } renderer = afx`

- {I18n.id('module.new.user-context').package('Sandstorm.BackendUserManagement').source('SecondFactor').arguments([currentUser ? currentUser.name.fullName : accountIdentifier]).translate()} + {I18n.id('module.new.user-context').package('Sandstorm.BackendUserManagement').source('SecondFactor').arguments([String.htmlSpecialChars(currentUser ? currentUser.name.fullName : accountIdentifier)]).translate()}

- {props.factorAndPerson.user.name.fullName} ({props.factorAndPerson.secondFactor.account.accountIdentifier}) + {String.htmlSpecialChars(props.factorAndPerson.user.name.fullName)} ({String.htmlSpecialChars(props.factorAndPerson.secondFactor.account.accountIdentifier)}) {props.factorAndPerson.secondFactor.typeAsName} - {props.factorAndPerson.secondFactor.name == null ? '-' : props.factorAndPerson.secondFactor.name} + {props.factorAndPerson.secondFactor.name == null ? '-' : String.htmlSpecialChars(props.factorAndPerson.secondFactor.name)} {props.factorAndPerson.secondFactor.creationDate == null ? '-' : Date.format(props.factorAndPerson.secondFactor.creationDate, 'Y-m-d H:i')}