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
4 changes: 0 additions & 4 deletions apps/oauth2/lib/Controller/OauthApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
use OCP\DB\Exception;
use OCP\IDBConnection;
use OCP\IRequest;
use OCP\Security\Bruteforce\IThrottler;
use OCP\Security\ICrypto;
use OCP\Security\ISecureRandom;
use Psr\Log\LoggerInterface;
Expand All @@ -46,7 +45,6 @@ public function __construct(
private ISecureRandom $secureRandom,
private ITimeFactory $time,
private LoggerInterface $logger,
private IThrottler $throttler,
private ITimeFactory $timeFactory,
private IDBConnection $db,
) {
Expand Down Expand Up @@ -226,8 +224,6 @@ public function getToken(
throw $e;
}

$this->throttler->resetDelay($this->request->getRemoteAddress(), 'login', ['user' => $appToken->getUID()]);

return new JSONResponse(
[
'access_token' => $newToken,
Expand Down
2 changes: 1 addition & 1 deletion apps/oauth2/lib/Service/ClientService.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public function deleteClient(int $id): void {
$this->userManager->callForSeenUsers(function (IUser $user) use ($client): void {
// Skip tokens that are marked for remote wipe so revoking the
// OAuth2 client does not silently cancel a pending wipe.
$tokens = $this->tokenProvider->getTokenByUser($user->getUID());
$tokens = $this->tokenProvider->getAllTokensByUser($user->getUID());
foreach ($tokens as $token) {
if ($token->getName() !== $client->getName()) {
continue;
Expand Down
41 changes: 0 additions & 41 deletions apps/oauth2/tests/Controller/OauthApiControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\IDBConnection;
use OCP\IRequest;
use OCP\Security\Bruteforce\IThrottler;
use OCP\Security\ICrypto;
use OCP\Security\ISecureRandom;
use Psr\Log\LoggerInterface;
Expand All @@ -48,8 +47,6 @@ class OauthApiControllerTest extends TestCase {
private $secureRandom;
/** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */
private $time;
/** @var IThrottler|\PHPUnit\Framework\MockObject\MockObject */
private $throttler;
/** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */
private $logger;
/** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */
Expand All @@ -69,7 +66,6 @@ protected function setUp(): void {
$this->tokenProvider = $this->createMock(TokenProvider::class);
$this->secureRandom = $this->createMock(ISecureRandom::class);
$this->time = $this->createMock(ITimeFactory::class);
$this->throttler = $this->createMock(IThrottler::class);
$this->logger = $this->createMock(LoggerInterface::class);
$this->timeFactory = $this->createMock(ITimeFactory::class);
$this->db = $this->createMock(IDBConnection::class);
Expand All @@ -84,7 +80,6 @@ protected function setUp(): void {
$this->secureRandom,
$this->time,
$this->logger,
$this->throttler,
$this->timeFactory,
$this->db,
);
Expand Down Expand Up @@ -415,17 +410,6 @@ public function testRefreshTokenValidAppToken(): void {
'user_id' => 'userId',
]);

$this->request->method('getRemoteAddress')
->willReturn('1.2.3.4');

$this->throttler->expects($this->once())
->method('resetDelay')
->with(
'1.2.3.4',
'login',
['user' => 'userId']
);

$this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', 'clientId', 'clientSecret'));
}

Expand Down Expand Up @@ -528,17 +512,6 @@ public function testRefreshTokenValidAppTokenBasicAuth(): void {
$this->request->server['PHP_AUTH_USER'] = 'clientId';
$this->request->server['PHP_AUTH_PW'] = 'clientSecret';

$this->request->method('getRemoteAddress')
->willReturn('1.2.3.4');

$this->throttler->expects($this->once())
->method('resetDelay')
->with(
'1.2.3.4',
'login',
['user' => 'userId']
);

$this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', null, null));
}

Expand Down Expand Up @@ -638,17 +611,6 @@ public function testRefreshTokenExpiredAppToken(): void {
'user_id' => 'userId',
]);

$this->request->method('getRemoteAddress')
->willReturn('1.2.3.4');

$this->throttler->expects($this->once())
->method('resetDelay')
->with(
'1.2.3.4',
'login',
['user' => 'userId']
);

$this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', 'clientId', 'clientSecret'));
}

Expand Down Expand Up @@ -731,9 +693,6 @@ public function testRefreshTokenRedeemedConcurrently(): void {
false,
)->willReturn(0);

$this->throttler->expects($this->never())
->method('resetDelay');

$this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', 'clientId', 'clientSecret'));
}
}
6 changes: 3 additions & 3 deletions apps/oauth2/tests/Service/ClientServiceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,11 +116,11 @@ public function testDeleteClient(): void {
$user1->updateLastLoginTimestamp();
$tokenProviderMock = $this->getMockBuilder(IAuthTokenProvider::class)->getMock();

// One getTokenByUser call per user; we return no matching tokens here
// One getAllTokensByUser call per user; we return no matching tokens here
// so invalidateTokenById is never invoked.
$tokenProviderMock
->expects($this->exactly($count + 1))
->method('getTokenByUser')
->method('getAllTokensByUser')
->willReturn([]);
$tokenProviderMock
->expects($this->never())
Expand Down Expand Up @@ -188,7 +188,7 @@ public function testDeleteClientPreservesWipePendingToken(): void {
$otherToken->method('getName')->willReturn('Some Other Client');

$this->authTokenProvider
->method('getTokenByUser')
->method('getAllTokensByUser')
->willReturnCallback(function (string $uid) use ($wipeToken, $regularToken, $otherToken) {
return $uid === 'test_wipe_preserve'
? [$wipeToken, $regularToken, $otherToken]
Expand Down
5 changes: 4 additions & 1 deletion core/Command/User/AuthTokens/ListCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,10 @@ protected function execute(InputInterface $input, OutputInterface $output): int
return 1;
}

$tokens = $this->tokenProvider->getTokenByUser($user->getUID());
$tokens = [];
foreach ($this->tokenProvider->getAllTokensByUser($user->getUID()) as $token) {
$tokens[] = $token;
}

$tokens = array_map(function (IToken $token) use ($input): mixed {
$sensitive = [
Expand Down
6 changes: 3 additions & 3 deletions core/Controller/AppPasswordController.php
Original file line number Diff line number Diff line change
Expand Up @@ -144,15 +144,15 @@ public function rotateAppPassword(): DataResponse {

$appPassword = $this->session->get('app_password');

$newToken = $this->random->generate(72, ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);

try {
$token = $this->tokenProvider->getToken($appPassword);
$this->tokenProvider->rotate($token, $appPassword, $newToken);
} catch (InvalidTokenException $e) {
throw new OCSForbiddenException('could not rotate apptoken');
}

$newToken = $this->random->generate(72, ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
$this->tokenProvider->rotate($token, $appPassword, $newToken);

return new DataResponse([
'apppassword' => $newToken,
]);
Expand Down
15 changes: 9 additions & 6 deletions lib/base.php
Original file line number Diff line number Diff line change
Expand Up @@ -905,13 +905,16 @@ public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): voi
if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
// NOTE: This will be replaced to use OCP
$userSession = Server::get(\OC\User\Session::class);
$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
$userSession->listen('\OC\User', 'postLogin', function ($loggedInUser, $loginName, $password, bool $isTokenLogin) use ($userSession) {
if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
// reset brute force delay for this IP address and username
$uid = $userSession->getUser()->getUID();
$request = Server::get(IRequest::class);
$throttler = Server::get(IThrottler::class);
$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
// A token login does not prove knowledge of the password
if (!$isTokenLogin) {
// reset brute force delay for this IP address and username
$uid = $userSession->getUser()->getUID();
$request = Server::get(IRequest::class);
$throttler = Server::get(IThrottler::class);
$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
}
}

try {
Expand Down
2 changes: 1 addition & 1 deletion lib/private/AppFramework/Http/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -882,7 +882,7 @@ private function fromTrustedProxy(): bool {

public function getFormat(): ?string {
$format = $this->getParam('format');
if ($format !== null) {
if (is_string($format)) {
return $format;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public function handle(Event $event): void {
*/
try {
$uid = $event->getUser()->getUID();
$tokens = $this->manager->getTokenByUser($uid);
$tokens = $this->manager->getAllTokensByUser($uid);
foreach ($tokens as $token) {
$this->manager->invalidateTokenById($uid, $token->getId());
}
Expand Down
12 changes: 11 additions & 1 deletion lib/private/Authentication/Token/IProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,15 @@ public function updateTokenActivity(OCPIToken $token);
*/
public function getTokenByUser(string $uid): array;

/**
* Get every token of a user, without the limit of getTokenByUser()
*
* Tokens may be deleted or updated while iterating.
*
* @return iterable<OCPIToken>
*/
public function getAllTokensByUser(string $uid): iterable;

/**
* Get the (unencrypted) password of the given token
*
Expand Down Expand Up @@ -150,7 +159,8 @@ public function setPassword(OCPIToken $token, string $tokenId, string $password)
* @param OCPIToken $token
* @param string $oldTokenId
* @param string $newTokenId
* @return OCPIToken
* @return OCPIToken the rotated token as it is stored, not necessarily the given instance
* @throws InvalidTokenException when the token does not exist (anymore)
* @throws \RuntimeException when OpenSSL reports a problem
*/
public function rotate(OCPIToken $token, string $oldTokenId, string $newTokenId): OCPIToken;
Expand Down
6 changes: 5 additions & 1 deletion lib/private/Authentication/Token/Manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,10 @@ public function getTokenByUser(string $uid): array {
return $this->publicKeyTokenProvider->getTokenByUser($uid);
}

public function getAllTokensByUser(string $uid): iterable {
return $this->publicKeyTokenProvider->getAllTokensByUser($uid);
}

/**
* Get a token by token
*
Expand Down Expand Up @@ -238,7 +242,7 @@ public function updatePasswords(string $uid, string $password) {
}

public function invalidateTokensOfUser(string $uid, ?string $clientName) {
$tokens = $this->getTokenByUser($uid);
$tokens = $this->getAllTokensByUser($uid);
foreach ($tokens as $token) {
if ($clientName === null || ($token->getName() === $clientName)) {
$this->invalidateTokenById($uid, $token->getId());
Expand Down
26 changes: 26 additions & 0 deletions lib/private/Authentication/Token/PublicKeyTokenMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,32 @@ public function getTokenByUser(string $uid): array {
return $entities;
}

/**
* Tokens may be deleted or updated while iterating.
*
* @return \Generator<PublicKeyToken>
*/
public function getAllTokensByUser(string $uid): \Generator {
$chunkSize = 1000;
$lastId = 0;
do {
$qb = $this->db->getQueryBuilder();
$qb->select('*')
->from($this->tableName)
->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)))
->andWhere($qb->expr()->gt('id', $qb->createNamedParameter($lastId, IQueryBuilder::PARAM_INT)))
->orderBy('id')
->setMaxResults($chunkSize);
$tokens = $this->findEntities($qb);

foreach ($tokens as $token) {
$lastId = $token->getId();
yield $token;
}
} while (count($tokens) === $chunkSize);
}

public function getTokenByUserAndId(string $uid, int $id): ?string {
/* @var $qb IQueryBuilder */
$qb = $this->db->getQueryBuilder();
Expand Down
27 changes: 25 additions & 2 deletions lib/private/Authentication/Token/PublicKeyTokenProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ public function getToken(string $tokenId): OCPIToken {
} catch (DoesNotExistException $ex) {
try {
$token = $this->mapper->getToken($this->hashTokenWithEmptySecret($tokenId));
$this->rotate($token, $tokenId, $tokenId);
$token = $this->rotate($token, $tokenId, $tokenId);
} catch (DoesNotExistException) {
$this->cacheInvalidHash($tokenHash);
throw new InvalidTokenException('Token does not exist: ' . $ex->getMessage(), 0, $ex);
Expand Down Expand Up @@ -356,6 +356,10 @@ public function getTokenByUser(string $uid): array {
return $this->mapper->getTokenByUser($uid);
}

public function getAllTokensByUser(string $uid): iterable {
return $this->mapper->getAllTokensByUser($uid);
}

public function getPassword(OCPIToken $savedToken, string $tokenId): string {
if (!($savedToken instanceof PublicKeyToken)) {
throw new InvalidTokenException('Invalid token type');
Expand Down Expand Up @@ -402,14 +406,33 @@ public function rotate(OCPIToken $token, string $oldTokenId, string $newTokenId)
throw new InvalidTokenException('Invalid token type');
}

// The given token might come from the cache, so rotate what is stored:
// it might have been invalidated, rotated or changed in the meantime
$oldTokenHash = $token->getToken();
try {
$token = $this->mapper->getToken($oldTokenHash);
} catch (DoesNotExistException $ex) {
$this->cacheInvalidHash($oldTokenHash);
throw new InvalidTokenException('Token does not exist: ' . $ex->getMessage(), 0, $ex);
}
if ($token->getType() === OCPIToken::WIPE_TOKEN) {
$this->cacheToken($token);
throw new WipeTokenException($token);
}

// Decrypt private key with oldTokenId
$privateKey = $this->decrypt($token->getPrivateKey(), $oldTokenId);
// Encrypt with the new token
$token->setPrivateKey($this->encrypt($privateKey, $newTokenId));

$token->setToken($this->hashToken($newTokenId));
$newTokenHash = $this->hashToken($newTokenId);
$token->setToken($newTokenHash);
$this->updateToken($token);

if ($oldTokenHash !== $newTokenHash) {
$this->cacheInvalidHash($oldTokenHash);
}

return $token;
}

Expand Down
5 changes: 4 additions & 1 deletion lib/private/Authentication/Token/RemoteWipe.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,10 @@ public function markTokenForWipe(IToken $token): bool {
* @return bool true if any tokens have been marked for remote wipe
*/
public function markAllTokensForWipe(IUser $user): bool {
$tokens = $this->tokenProvider->getTokenByUser($user->getUID());
$tokens = [];
foreach ($this->tokenProvider->getAllTokensByUser($user->getUID()) as $token) {
$tokens[] = $token;
}

/** @var IWipeableToken[] $wipeable */
$wipeable = array_filter($tokens, function (IToken $token) {
Expand Down
7 changes: 1 addition & 6 deletions lib/private/Security/Bruteforce/Throttler.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,6 @@
* @package OC\Security\Bruteforce
*/
class Throttler implements IThrottler {
/** @var bool[] */
private array $hasAttemptsDeleted = [];

public function __construct(
private ITimeFactory $timeFactory,
private LoggerInterface $logger,
Expand Down Expand Up @@ -104,7 +101,7 @@ public function getAttempts(string $ip, string $action = '', float $maxAgeHours
$maxAgeHours = 48;
}

if ($ip === '' || isset($this->hasAttemptsDeleted[$action])) {
if ($ip === '') {
return 0;
}

Expand Down Expand Up @@ -170,8 +167,6 @@ public function resetDelay(string $ip, string $action, array $metadata): void {
$action,
$metadata,
);

$this->hasAttemptsDeleted[$action] = true;
}

/**
Expand Down
Loading
Loading