Skip to content
Open
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
1 change: 1 addition & 0 deletions build/integration/features/bootstrap/FeatureContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class FeatureContext implements Context, SnippetAcceptingContext {
use Search;
use WebDav;
use Trashbin;
use TwoFactorAuth;

protected function resetAppConfigs(): void {
$this->deleteServerConfig('bruteForce', 'whitelist_0');
Expand Down
179 changes: 179 additions & 0 deletions build/integration/features/bootstrap/TwoFactorAuth.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
<?php

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
use Behat\Hook\AfterScenario;
use Behat\Step\Given;
use Behat\Step\Then;
use Behat\Step\When;
use GuzzleHttp\Client;
use PHPUnit\Framework\Assert;

/**
* Steps for logins that are waiting for their second factor
*
* Needs the OccRunner, Auth and Sharing traits.
*/
trait TwoFactorAuth {
private bool $twoFactorEnforced = false;
/** @var array<string, string> */
private array $appPasswords = [];

#[Given('two-factor authentication is enforced for group :group')]
public function twoFactorAuthenticationIsEnforcedForGroup(string $group): void {
$this->enforceTwoFactorAuthentication(['--on', '--group', $group]);
}

/**
* The admin group stays excluded, the admin account is used for the setup and cleanup of scenarios
*/
#[Given('two-factor authentication is enforced for all users except group :group')]
public function twoFactorAuthenticationIsEnforcedExceptForGroup(string $group): void {
$this->enforceTwoFactorAuthentication(['--on', '--exclude', 'admin', '--exclude', $group]);
}

#[Given('two-factor authentication is not enforced')]
public function twoFactorAuthenticationIsNotEnforced(): void {
$this->enforceTwoFactorAuthentication(['--off']);
}

private function enforceTwoFactorAuthentication(array $options): void {
$this->runOcc(array_merge(['twofactorauth:enforce'], $options));
Assert::assertSame(0, $this->lastCode, $this->lastStdOut . $this->lastStdErr);
$this->twoFactorEnforced = true;
}

#[AfterScenario]
public function resetTwoFactorEnforcement(): void {
if ($this->twoFactorEnforced) {
$this->runOcc(['twofactorauth:enforce', '--off']);
$this->twoFactorEnforced = false;
}
$this->appPasswords = [];
}

#[Given('user :user has an app password')]
public function userHasAnAppPassword(string $user): void {
putenv('NC_PASS=' . $this->regularUser);
$this->runOcc(['user:auth-tokens:add', '--password-from-env', $user]);
putenv('NC_PASS');
Assert::assertSame(0, $this->lastCode, $this->lastStdOut . $this->lastStdErr);

$lines = explode("\n", trim($this->lastStdOut));
$this->appPasswords[$user] = end($lines);
}

#[When('requesting :url with :method using the app password of :user')]
public function requestingWithAppPassword(string $url, string $method, string $user): void {
$this->sendRequest($url, $method, 'basic ' . base64_encode($user . ':' . $this->appPasswords[$user]));
}

#[When('requesting :url with :method using the app password of :user and the browser session')]
public function requestingWithAppPasswordAndBrowserSession(string $url, string $method, string $user): void {
$this->sendRequest($url, $method, 'basic ' . base64_encode($user . ':' . $this->appPasswords[$user]), true);
}

#[When('submitting the login form as :user using the browser session')]
public function submittingTheLoginFormAs(string $user): void {
$this->submitLoginForm($user, []);
}

/**
* A timezone offset that is not valid UTF-8 makes saving the session fail
* after the session token of the login was created
*/
#[When('logging in using web as :user with a timezone offset that is not valid UTF-8')]
public function loggingInUsingWebWithInvalidTimezoneOffset(string $user): void {
$this->submitLoginForm($user, [
'timezone' => 'Europe/Berlin',
'timezone_offset' => "\xFF",
]);
}

/**
* Submits the login form without following the redirect to the challenge
*/
private function submitLoginForm(string $user, array $formParams): void {
$loginUrl = $this->getServerUrl() . '/index.php/login';
$client = new Client();
$this->extracRequestTokenFromResponse($client->get($loginUrl, ['cookies' => $this->cookieJar]));

// Without http_errors the cookies of a failed login are kept
$this->response = $client->post($loginUrl, [
'form_params' => [
'user' => $user,
'password' => $this->regularUser,
'requesttoken' => $this->requestToken,
] + $formParams,
'cookies' => $this->cookieJar,
'headers' => ['Origin' => $this->getServerUrl()],
'allow_redirects' => false,
'http_errors' => false,
]);
}

#[When('the password :password of the last link share is sent as an anonymous request using the browser session')]
public function thePasswordOfTheLastLinkShareIsSent(string $password): void {
$client = new Client();
$authenticateUrl = $this->getServerUrl() . '/index.php/s/' . $this->lastShareData->data[0]->token . '/authenticate/showShare';
// Keeps the request anonymous although the session cookie belongs to a login
$headers = ['X-Nextcloud-Federation' => '1'];

$this->extracRequestTokenFromResponse($client->get($authenticateUrl, [
'cookies' => $this->cookieJar,
'headers' => $headers,
]));

$this->response = $client->post($authenticateUrl, [
'form_params' => [
'password' => $password,
'requesttoken' => $this->requestToken,
],
'cookies' => $this->cookieJar,
'headers' => $headers + ['Origin' => $this->getServerUrl()],
'allow_redirects' => false,
'http_errors' => false,
]);
}

#[Then('the response redirects to :path')]
public function theResponseRedirectsTo(string $path): void {
Assert::assertContains($this->response->getStatusCode(), [302, 303]);
Assert::assertSame($path, parse_url($this->response->getHeaderLine('Location'), PHP_URL_PATH));
}

#[Then('the browser session has access to the account of :user')]
public function theBrowserSessionHasAccessToTheAccountOf(string $user): void {
Assert::assertSame($user, $this->getBrowserSessionUser(), 'The browser session is not logged in as ' . $user);
}

#[Then('the browser session has no access to the account of :user')]
public function theBrowserSessionHasNoAccessToTheAccountOf(string $user): void {
Assert::assertNotSame($user, $this->getBrowserSessionUser(), 'The browser session is logged in as ' . $user);
}

/**
* The user the browser session is fully logged in as, without following
* a redirect to a two-factor challenge
*/
private function getBrowserSessionUser(): ?string {
$client = new Client();
$this->response = $client->get($this->getServerUrl() . '/ocs/v2.php/cloud/user?format=json', [
'cookies' => $this->cookieJar,
'headers' => ['OCS-APIRequest' => 'true'],
'allow_redirects' => false,
'http_errors' => false,
]);

if ($this->response->getStatusCode() !== 200) {
return null;
}
return json_decode($this->response->getBody()->getContents())->ocs->data->id;
}

private function getServerUrl(): string {
return substr($this->baseUrl, 0, -5);
}
}
83 changes: 83 additions & 0 deletions build/integration/features/two-factor-auth.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
# SPDX-License-Identifier: AGPL-3.0-or-later
Feature: two-factor-auth

Background:
Given user "user0" exists
And user "user1" exists
And As an "admin"
And creating the group "twofactor"
And user "user0" belongs to group "twofactor"
And two-factor authentication is enforced for group "twofactor"
And the cookie jar is reset

Scenario: a login is redirected to the challenge selection
When submitting the login form as "user0" using the browser session
Then the response redirects to "/index.php/login/selectchallenge"
And the browser session has no access to the account of "user0"

Scenario: a user outside the enforced group logs in without a second factor
When submitting the login form as "user1" using the browser session
Then the HTTP status code should be "303"
And the browser session has access to the account of "user1"

Scenario: a user in an excluded group logs in without a second factor
Given creating the group "notwofactor"
And user "user1" belongs to group "notwofactor"
And two-factor authentication is enforced for all users except group "notwofactor"
When submitting the login form as "user1" using the browser session
Then the HTTP status code should be "303"
And the browser session has access to the account of "user1"

Scenario: a user outside an excluded group has to pass a second factor
Given creating the group "notwofactor"
And two-factor authentication is enforced for all users except group "notwofactor"
When submitting the login form as "user1" using the browser session
Then the response redirects to "/index.php/login/selectchallenge"
And the browser session has no access to the account of "user1"

Scenario: a login is complete when two-factor authentication is no longer enforced
Given two-factor authentication is not enforced
When submitting the login form as "user0" using the browser session
Then the HTTP status code should be "303"
And the browser session has access to the account of "user0"

Scenario: WebDAV refuses the login password of a user who has to pass a second factor
When requesting "/remote.php/dav/files/user0/" with "PROPFIND" using basic auth
Then the HTTP status code should be "401"

Scenario: WebDAV accepts an app password of a user who has to pass a second factor
Given user "user0" has an app password
When requesting "/remote.php/dav/files/user0/" with "PROPFIND" using the app password of "user0"
Then the HTTP status code should be "207"

Scenario: a login whose session could not be saved still needs its second factor
When logging in using web as "user0" with a timezone offset that is not valid UTF-8
Then the HTTP status code should be "500"
And the browser session has no access to the account of "user0"

Scenario: the app password of another user in the session does not replace the second factor
Given user "user1" has an app password
And requesting "/ocs/v2.php/cloud/user" with "GET" using the app password of "user1" and the browser session
And the HTTP status code should be "200"
When submitting the login form as "user0" using the browser session
Then the HTTP status code should be "303"
And the browser session has no access to the account of "user0"

Scenario: a session whose session token belongs to another user is logged out
Given Logging in using web as "user1"
When logging in using web as "user0" with a timezone offset that is not valid UTF-8
Then the HTTP status code should be "500"
And the browser session has no access to the account of "user1"

Scenario: renewing the session token of a login keeps its pending second factor
Given User "user1" uploads file with content "shared note" to "/note.txt"
And as "user1" creating a share with
| path | note.txt |
| shareType | 3 |
| password | Link-password-2fa-test |
And logging in using web as "user0" with a timezone offset that is not valid UTF-8
And the HTTP status code should be "500"
When the password "Link-password-2fa-test" of the last link share is sent as an anonymous request using the browser session
Then the HTTP status code should be "303"
And the browser session has no access to the account of "user0"
10 changes: 10 additions & 0 deletions lib/private/Authentication/Token/PublicKeyTokenProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,16 @@ public function renewSessionToken(string $oldSessionId, string $sessionId): OCPI
);
$this->cacheToken($newToken);

// Pending second factors are tracked by token id
// @see \OC\Authentication\TwoFactorAuth\Manager::needsSecondFactor()
$uid = $token->getUID();
$oldId = (string)$token->getId();
if (in_array($oldId, $this->config->getUserKeys($uid, 'login_token_2fa'), true)) {
$pendingSince = $this->config->getUserValue($uid, 'login_token_2fa', $oldId);
$this->config->setUserValue($uid, 'login_token_2fa', (string)$newToken->getId(), $pendingSince);
$this->config->deleteUserValue($uid, 'login_token_2fa', $oldId);
}

$this->cacheInvalidHash($token->getToken());
$this->mapper->delete($token);

Expand Down
19 changes: 18 additions & 1 deletion lib/private/Authentication/TwoFactorAuth/Manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ public function needsSecondFactor(?IUser $user = null): bool {
}

// If we are authenticated using an app password or AppAPI Auth, skip all this
if ($this->session->exists('app_password') || $this->session->get('app_api') === true) {
if ($this->isAppPasswordOf($user) || $this->session->get('app_api') === true) {
return false;
}

Expand Down Expand Up @@ -348,6 +348,23 @@ public function needsSecondFactor(?IUser $user = null): bool {
return true;
}

/**
* Check if the app password of the session belongs to the given user
*/
private function isAppPasswordOf(IUser $user): bool {
if (!$this->session->exists('app_password')) {
return false;
}

try {
$token = $this->tokenProvider->getToken($this->session->get('app_password'));
} catch (InvalidTokenException) {
return false;
}

return $token->getUID() === $user->getUID();
}

/**
* Prepare the 2FA login
*
Expand Down
27 changes: 25 additions & 2 deletions lib/private/User/Session.php
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ protected function validateSession() {
$token = $appPassword;
}

if (!$this->validateToken($token)) {
if (!$this->validateToken($token, checkOwner: true)) {
// Session was invalidated
$this->logout();
}
Expand Down Expand Up @@ -766,9 +766,10 @@ private function checkTokenCredentials(IToken $dbToken, $token) {
*
* @param string $token
* @param string $user login name
* @param bool $checkOwner Whether the token must belong to the session user
* @return boolean
*/
private function validateToken($token, $user = null) {
private function validateToken($token, $user = null, bool $checkOwner = false) {
try {
$dbToken = $this->tokenProvider->getToken($token);
} catch (InvalidTokenException $ex) {
Expand All @@ -784,6 +785,10 @@ private function validateToken($token, $user = null) {
return false;
}

if ($checkOwner && !$this->validateTokenOwner($dbToken)) {
return false;
}

if (!$this->checkTokenCredentials($dbToken, $token)) {
$this->logger->warning('Session token credentials are invalid', [
'app' => 'core',
Expand All @@ -800,6 +805,24 @@ private function validateToken($token, $user = null) {
return true;
}

/**
* Check if the token that keeps the session alive belongs to the user of
* the session, or to the user that impersonates them
*/
private function validateTokenOwner(IToken $dbToken): bool {
$tokenUid = $dbToken->getUID();
if ($tokenUid === $this->activeUser?->getUID() || $tokenUid === $this->getImpersonatingUserID()) {
return true;
}

$this->logger->warning('Session token belongs to a different user', [
'app' => 'core',
'user' => $this->activeUser?->getUID(),
]);

return false;
}

/**
* Check if login names match
*/
Expand Down
Loading
Loading