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
82 changes: 66 additions & 16 deletions core/Controller/ClientFlowLoginV2Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use OC\Core\Exception\LoginFlowV2NotFoundException;
use OC\Core\ResponseDefinitions;
use OC\Core\Service\LoginFlowV2Service;
use OC\Security\Ip\Address;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\FrontpageRoute;
Expand All @@ -30,7 +31,6 @@
use OCP\AppFramework\Http\StandaloneTemplateResponse;
use OCP\AppFramework\Services\IInitialState;
use OCP\Authentication\Exceptions\InvalidTokenException;
use OCP\Defaults;
use OCP\IL10N;
use OCP\IRequest;
use OCP\ISession;
Expand All @@ -56,7 +56,6 @@ public function __construct(
private ISession $session,
private IUserSession $userSession,
private ISecureRandom $random,
private Defaults $defaults,
private ?string $userId,
private IL10N $l10n,
private IInitialState $initialState,
Expand Down Expand Up @@ -109,7 +108,7 @@ public function landing(string $token, $user = '', int $direct = 0): Response {
#[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
#[UseSession]
#[FrontpageRoute(verb: 'GET', url: '/login/v2/flow')]
public function showAuthPickerPage(string $user = '', int $direct = 0): StandaloneTemplateResponse {
public function showAuthPickerPage(string $user = '', int $direct = 0): Response {
try {
$flow = $this->getFlowByLoginToken();
} catch (LoginFlowV2NotFoundException $e) {
Expand All @@ -123,13 +122,17 @@ public function showAuthPickerPage(string $user = '', int $direct = 0): Standalo
ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS
);
$this->session->set(self::STATE_NAME, $stateToken);
$loginRedirectUrl = $this->urlGenerator->linkToRouteAbsolute('core.ClientFlowLoginV2.grantPage', ['stateToken' => $stateToken, 'user' => $user, 'direct' => $direct]);
if ($this->userSession->getUser() !== null) {
Comment thread
fput marked this conversation as resolved.
Resolved
return new RedirectResponse($loginRedirectUrl);
}

$this->initialState->provideInitialState('loginFlowState', 'auth');
$this->provideFlowContext($flow);
$this->initialState->provideInitialState('loginFlowState', 'auth-v2');
$this->initialState->provideInitialState('loginFlowAuth', [
'client' => $flow->getClientName(),
'instanceName' => $this->defaults->getName(),
'stateToken' => $stateToken,
'loginRedirectUrl' => $this->urlGenerator->linkToRouteAbsolute('core.ClientFlowLoginV2.grantPage', ['stateToken' => $stateToken, 'user' => $user, 'direct' => $direct]),
'direct' => $direct === 1,
'loginRedirectUrl' => $loginRedirectUrl,
'appTokenUrl' => $this->urlGenerator->linkToRouteAbsolute('core.ClientFlowLoginV2.apptokenRedirect'),
]);

Expand Down Expand Up @@ -164,16 +167,10 @@ public function grantPage(?string $stateToken, int $direct = 0): StandaloneTempl
return $this->loginTokenForbiddenClientResponse();
}

$user = $this->userSession->getUser();
\assert($user !== null);

$this->initialState->provideInitialState('loginFlowState', 'grant');
$this->provideFlowContext($flow);
$this->initialState->provideInitialState('loginFlowState', 'grant-v2');
$this->initialState->provideInitialState('loginFlowGrant', [
'actionUrl' => $this->urlGenerator->linkToRouteAbsolute('core.ClientFlowLoginV2.generateAppPassword'),
'userId' => $user->getUID(),
'userDisplayName' => $user->getDisplayName(),
'client' => $flow->getClientName(),
'instanceName' => $this->defaults->getName(),
'stateToken' => $stateToken,
'direct' => $direct === 1,
]);
Expand All @@ -188,6 +185,33 @@ public function grantPage(?string $stateToken, int $direct = 0): StandaloneTempl
}

#[PublicPage]
#[UseSession]
#[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
#[FrontpageRoute(verb: 'POST', url: '/login/v2/decline')]
public function decline(?string $stateToken): JSONResponse {
if ($stateToken === null || !$this->isValidStateToken($stateToken)) {
return new JSONResponse([], Http::STATUS_FORBIDDEN);
}

try {
$this->getFlowByLoginToken();
} catch (LoginFlowV2NotFoundException $e) {
return new JSONResponse([], Http::STATUS_GONE);
} catch (LoginFlowV2ClientForbiddenException $e) {
return new JSONResponse([], Http::STATUS_FORBIDDEN);
}

if (!$this->loginFlowV2Service->decline($this->session->get(self::TOKEN_NAME))) {
return new JSONResponse([], Http::STATUS_CONFLICT);
}

$this->session->remove(self::TOKEN_NAME);
$this->session->remove(self::STATE_NAME);
return new JSONResponse([]);
}

#[PublicPage]
#[UseSession]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why does this one need UseSession now? It keeps the session locked for the whole request.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

There might be a race condition when not locking the session, as state token lookup/validation could be separated from the token cleanup.

Would you recommend removing UseSession here? Or maybe close the session early in the function after line 237?

$this->session->remove(self::TOKEN_NAME);
$this->session->remove(self::STATE_NAME);
$this->session->close();

#[FrontpageRoute(verb: 'POST', url: '/login/v2/apptoken')]
public function apptokenRedirect(?string $stateToken, string $user, string $password) {
if ($stateToken === null) {
Expand Down Expand Up @@ -270,6 +294,9 @@ private function handleFlowDone(bool $result): StandaloneTemplateResponse {
Util::addScript('core', 'login_flow');
Util::addStyle('core', 'login_flow');
$this->initialState->provideInitialState('loginFlowState', 'done');
$this->initialState->provideInitialState('loginFlowDone', [
'securitySettingsUrl' => $this->urlGenerator->linkToRouteAbsolute('settings.PersonalSettings.index', ['section' => 'security']),
]);
return new StandaloneTemplateResponse(
$this->appName,
'loginflow',
Expand Down Expand Up @@ -304,7 +331,7 @@ public function init(): JSONResponse {
// Get client user agent
$userAgent = $this->request->getHeader('user-agent');

$tokens = $this->loginFlowV2Service->createTokens($userAgent);
$tokens = $this->loginFlowV2Service->createTokens($userAgent, $this->request->getRemoteAddress());

$data = [
'poll' => [
Expand All @@ -317,6 +344,29 @@ public function init(): JSONResponse {
return new JSONResponse($data);
}

private function provideFlowContext(LoginFlowV2 $flow): void {
$clientIp = $flow->getClientIp();
$browserIp = $this->request->getRemoteAddress();
$sameIp = null;
if ($clientIp !== null && Address::isValid($clientIp) && Address::isValid($browserIp)) {
$sameIp = (string)new Address($clientIp) === (string)new Address($browserIp);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'm a bit worried about IPv6 here. With privacy addresses the same machine can show up with a different IP per connection, and with dual stack the app can come in over v6 while the browser uses v4. Both would show the warning on a normal login. Maybe compare the /64 for v6, and leave sameIp as null when one is v4 and the other v6?

@fput fput Nov 6, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Good points!

Comparing the IPv6 /64 is a great idea. The downside is that an attacker on the same shared subnet would not trigger a warning. But that's already the case anyways for IPv4 behind NAT, so we don't loose much.

For the case when one IP is v4 and the other is v6 I'm less sure, hmmm... An attacker could easily disable the warning then by using whatever IP version the user is not using on the phishing website. Even without that info, there's a substantial chance the attacker can disable the warning by guessing the correct IP version.

There is a trade-off here: Do we want fewer false alarms for dual-stack, but then also less warnings for actual attacks? @susnux @skjnldsv

}

$user = $this->userSession->getUser();
$this->initialState->provideInitialState('loginFlowContext', [
'userAgent' => $flow->getClientName(),
'serverUrl' => $this->getServerPath(),
'userId' => $user?->getUID(),
'userDisplayName' => $user?->getDisplayName(),
'declineUrl' => $this->urlGenerator->linkToRouteAbsolute('core.ClientFlowLoginV2.decline'),
'securitySettingsUrl' => $this->urlGenerator->linkToRouteAbsolute('settings.PersonalSettings.index', ['section' => 'security']),
'createdAt' => $flow->getTimestamp(),
'clientIp' => $clientIp,
'browserIp' => $browserIp,
'sameIp' => $sameIp,
]);
}

private function isValidStateToken(string $stateToken): bool {
$currentToken = $this->session->get(self::STATE_NAME);
if (!is_string($stateToken) || !is_string($currentToken)) {
Expand Down
4 changes: 4 additions & 0 deletions core/Db/LoginFlowV2.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
* @method void setPrivateKey(string $key)
* @method string getClientName()
* @method void setClientName(string $clientName)
* @method ?string getClientIp()
* @method void setClientIp(?string $clientIp)
* @method string getLoginName()
* @method void setLoginName(string $loginName)
* @method string getServer()
Expand All @@ -49,6 +51,7 @@ class LoginFlowV2 extends Entity {
protected $privateKey;
/** @var string */
protected $clientName;
protected ?string $clientIp = null;
/** @var string */
protected $loginName;
/** @var string */
Expand All @@ -64,6 +67,7 @@ public function __construct() {
$this->addType('publicKey', 'string');
$this->addType('privateKey', 'string');
$this->addType('clientName', 'string');
$this->addType('clientIp', 'string');
$this->addType('loginName', 'string');
$this->addType('server', 'string');
$this->addType('appPassword', 'string');
Expand Down
24 changes: 24 additions & 0 deletions core/Db/LoginFlowV2Mapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\QBMapper;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;

/**
Expand Down Expand Up @@ -75,6 +76,29 @@ public function cleanup(): void {
$qb->executeStatement();
}

public function deletePending(string $loginToken): bool {
$qb = $this->db->getQueryBuilder();
$qb->delete($this->getTableName())
->where($qb->expr()->eq('login_token', $qb->createNamedParameter($loginToken)))
->andWhere($qb->expr()->isNull('app_password'));

return $qb->executeStatement() === 1;
}

/** Only a pending, unexpired request can receive credentials. */
public function complete(LoginFlowV2 $flow): bool {
Comment thread
fput marked this conversation as resolved.
Resolved
$qb = $this->db->getQueryBuilder();
$qb->update($this->getTableName())
->set('login_name', $qb->createNamedParameter($flow->getLoginName()))
->set('server', $qb->createNamedParameter($flow->getServer()))
->set('app_password', $qb->createNamedParameter($flow->getAppPassword()))
->where($qb->expr()->eq('id', $qb->createNamedParameter($flow->getId(), IQueryBuilder::PARAM_INT)))
->andWhere($qb->expr()->isNull('app_password'))
->andWhere($qb->expr()->gte('timestamp', $qb->createNamedParameter($this->timeFactory->getTime() - self::lifetime, IQueryBuilder::PARAM_INT)));

return $qb->executeStatement() === 1;
}

/**
* @param LoginFlowV2 $flowV2
* @return LoginFlowV2
Expand Down
39 changes: 39 additions & 0 deletions core/Migrations/Version36000Date20261103000000.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OC\Core\Migrations;

use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\DB\Types;
use OCP\Migration\Attributes\AddColumn;
use OCP\Migration\Attributes\ColumnType;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;
use Override;

#[AddColumn(table: 'login_flow_v2', name: 'client_ip', type: ColumnType::STRING)]
class Version36000Date20261103000000 extends SimpleMigrationStep {
#[Override]
public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
/** @var ISchemaWrapper $schema */
$schema = $schemaClosure();
$table = $schema->getTable('login_flow_v2');
if ($table->hasColumn('client_ip')) {
return null;
}

$table->addColumn('client_ip', Types::STRING, [
'notnull' => false,
'length' => 45,
]);

return $schema;
}
}
44 changes: 32 additions & 12 deletions core/Service/LoginFlowV2Service.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,10 @@ public function startLoginFlow(string $loginToken): bool {
return true;
}

public function decline(string $loginToken): bool {
return $this->mapper->deletePending($loginToken);
}

/**
* @param string $loginToken
* @param string $sessionId
Expand All @@ -143,6 +147,10 @@ public function flowDone(string $loginToken, string $sessionId, string $server,
return false;
}

if ($data->getAppPassword() !== null) {
return false;
}

try {
$sessionToken = $this->tokenProvider->getToken($sessionId);
$loginName = $sessionToken->getLoginName();
Expand All @@ -165,21 +173,29 @@ public function flowDone(string $loginToken, string $sessionId, string $server,
IToken::PERMANENT_TOKEN,
IToken::DO_NOT_REMEMBER
);
$this->eventDispatcher->dispatchTyped(new CriticalActionPerformedEvent(
'App password with ID "%s" and name "%s" was created',
['tokenId' => $generatedToken->getId(), 'tokenName' => $generatedToken->getName()],
false,
'auth.app_password.created',
));

$data->setLoginName($loginName);
$data->setServer($server);

// Properly encrypt
$data->setAppPassword($this->encryptPassword($appPassword, $data->getPublicKey()));

$this->mapper->update($data);
return true;
$completed = false;
try {
$completed = $this->mapper->complete($data);
} finally {
if (!$completed) {
$this->tokenProvider->invalidateTokenById($userId, $generatedToken->getId());
}
}
if ($completed) {
$this->eventDispatcher->dispatchTyped(new CriticalActionPerformedEvent(
'App password with ID "%s" and name "%s" was created',
['tokenId' => $generatedToken->getId(), 'tokenName' => $generatedToken->getName()],
false,
'auth.app_password.created',
));
}
return $completed;
}

public function flowDoneWithAppPassword(string $loginToken, string $server, string $loginName, string $appPassword): bool {
Expand All @@ -189,17 +205,20 @@ public function flowDoneWithAppPassword(string $loginToken, string $server, stri
return false;
}

if ($data->getAppPassword() !== null) {
return false;
}

$data->setLoginName($loginName);
$data->setServer($server);

// Properly encrypt
$data->setAppPassword($this->encryptPassword($appPassword, $data->getPublicKey()));

$this->mapper->update($data);
return true;
return $this->mapper->complete($data);
}

public function createTokens(string $userAgent): LoginFlowV2Tokens {
public function createTokens(string $userAgent, string $clientIp): LoginFlowV2Tokens {
$flow = new LoginFlowV2();
$pollToken = $this->random->generate(128, ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER);
$loginToken = $this->random->generate(128, ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER);
Expand All @@ -208,6 +227,7 @@ public function createTokens(string $userAgent): LoginFlowV2Tokens {
$flow->setStarted(0);
$flow->setTimestamp($this->time->getTime());
$flow->setClientName($userAgent);
$flow->setClientIp($clientIp);

[$publicKey, $privateKey] = $this->getKeyPair();
$privateKey = $this->crypto->encrypt($privateKey, $pollToken);
Expand Down
Loading