Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[stable30] [oauth2] Store hashed secret instead of encrypted #47699

Merged
merged 3 commits into from
Sep 3, 2024
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
2 changes: 1 addition & 1 deletion apps/oauth2/appinfo/info.xml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<name>OAuth 2.0</name>
<summary>Allows OAuth2 compatible authentication from other web applications.</summary>
<description>The OAuth2 app allows administrators to configure the built-in authentication workflow to also allow OAuth2 compatible authentication from other web applications.</description>
<version>1.18.0</version>
<version>1.18.1</version>
<licence>agpl</licence>
<author>Lukas Reschke</author>
<namespace>OAuth2</namespace>
Expand Down
1 change: 1 addition & 0 deletions apps/oauth2/composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,6 @@
'OCA\\OAuth2\\Migration\\Version011601Date20230522143227' => $baseDir . '/../lib/Migration/Version011601Date20230522143227.php',
'OCA\\OAuth2\\Migration\\Version011602Date20230613160650' => $baseDir . '/../lib/Migration/Version011602Date20230613160650.php',
'OCA\\OAuth2\\Migration\\Version011603Date20230620111039' => $baseDir . '/../lib/Migration/Version011603Date20230620111039.php',
'OCA\\OAuth2\\Migration\\Version011901Date20240829164356' => $baseDir . '/../lib/Migration/Version011901Date20240829164356.php',
'OCA\\OAuth2\\Settings\\Admin' => $baseDir . '/../lib/Settings/Admin.php',
);
1 change: 1 addition & 0 deletions apps/oauth2/composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ class ComposerStaticInitOAuth2
'OCA\\OAuth2\\Migration\\Version011601Date20230522143227' => __DIR__ . '/..' . '/../lib/Migration/Version011601Date20230522143227.php',
'OCA\\OAuth2\\Migration\\Version011602Date20230613160650' => __DIR__ . '/..' . '/../lib/Migration/Version011602Date20230613160650.php',
'OCA\\OAuth2\\Migration\\Version011603Date20230620111039' => __DIR__ . '/..' . '/../lib/Migration/Version011603Date20230620111039.php',
'OCA\\OAuth2\\Migration\\Version011901Date20240829164356' => __DIR__ . '/..' . '/../lib/Migration/Version011901Date20240829164356.php',
'OCA\\OAuth2\\Settings\\Admin' => __DIR__ . '/..' . '/../lib/Settings/Admin.php',
);

Expand Down
5 changes: 3 additions & 2 deletions apps/oauth2/lib/Controller/OauthApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,8 @@
}

try {
$storedClientSecret = $this->crypto->decrypt($client->getSecret());
$storedClientSecretHash = $client->getSecret();
$clientSecretHash = bin2hex($this->crypto->calculateHMAC($client_secret));

Check notice

Code scanning / Psalm

PossiblyNullArgument Note

Argument 1 of OCP\Security\ICrypto::calculateHMAC cannot be null, possibly null value provided
} catch (\Exception $e) {
$this->logger->error('OAuth client secret decryption error', ['exception' => $e]);
// we don't throttle here because it might not be a bruteforce attack
Expand All @@ -147,7 +148,7 @@
], Http::STATUS_BAD_REQUEST);
}
// The client id and secret must match. Else we don't provide an access token!
if ($client->getClientIdentifier() !== $client_id || $storedClientSecret !== $client_secret) {
if ($client->getClientIdentifier() !== $client_id || $storedClientSecretHash !== $clientSecretHash) {
$response = new JSONResponse([
'error' => 'invalid_client',
], Http::STATUS_BAD_REQUEST);
Expand Down
4 changes: 2 additions & 2 deletions apps/oauth2/lib/Controller/SettingsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ public function addClient(string $name,
$client->setName($name);
$client->setRedirectUri($redirectUri);
$secret = $this->secureRandom->generate(64, self::validChars);
$encryptedSecret = $this->crypto->encrypt($secret);
$client->setSecret($encryptedSecret);
$hashedSecret = bin2hex($this->crypto->calculateHMAC($secret));
$client->setSecret($hashedSecret);
$client->setClientIdentifier($this->secureRandom->generate(64, self::validChars));
$client = $this->clientMapper->insert($client);

Expand Down
49 changes: 49 additions & 0 deletions apps/oauth2/lib/Migration/Version011901Date20240829164356.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\OAuth2\Migration;

use Closure;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;
use OCP\Security\ICrypto;

class Version011901Date20240829164356 extends SimpleMigrationStep {

public function __construct(
private IDBConnection $connection,
private ICrypto $crypto,
) {
}

public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void {
$qbUpdate = $this->connection->getQueryBuilder();
$qbUpdate->update('oauth2_clients')
->set('secret', $qbUpdate->createParameter('updateSecret'))
->where(
$qbUpdate->expr()->eq('id', $qbUpdate->createParameter('updateId'))
);

$qbSelect = $this->connection->getQueryBuilder();
$qbSelect->select('id', 'secret')
->from('oauth2_clients');
$req = $qbSelect->executeQuery();
while ($row = $req->fetch()) {
$id = $row['id'];
$storedEncryptedSecret = $row['secret'];
$secret = $this->crypto->decrypt($storedEncryptedSecret);
$hashedSecret = bin2hex($this->crypto->calculateHMAC($secret));
$qbUpdate->setParameter('updateSecret', $hashedSecret, IQueryBuilder::PARAM_STR);
$qbUpdate->setParameter('updateId', $id, IQueryBuilder::PARAM_INT);
$qbUpdate->executeStatement();
}
$req->closeCursor();
}
}
5 changes: 1 addition & 4 deletions apps/oauth2/lib/Settings/Admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
use OCP\AppFramework\Http\TemplateResponse;
use OCP\AppFramework\Services\IInitialState;
use OCP\IURLGenerator;
use OCP\Security\ICrypto;
use OCP\Settings\ISettings;
use Psr\Log\LoggerInterface;

Expand All @@ -22,7 +21,6 @@ public function __construct(
private IInitialState $initialState,
private ClientMapper $clientMapper,
private IURLGenerator $urlGenerator,
private ICrypto $crypto,
private LoggerInterface $logger,
) {
}
Expand All @@ -33,13 +31,12 @@ public function getForm(): TemplateResponse {

foreach ($clients as $client) {
try {
$secret = $this->crypto->decrypt($client->getSecret());
$result[] = [
'id' => $client->getId(),
'name' => $client->getName(),
'redirectUri' => $client->getRedirectUri(),
'clientId' => $client->getClientIdentifier(),
'clientSecret' => $secret,
'clientSecret' => '',
];
} catch (\Exception $e) {
$this->logger->error('[Settings] OAuth client secret decryption error', ['exception' => $e]);
Expand Down
8 changes: 8 additions & 0 deletions apps/oauth2/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@
@delete="deleteClient" />
</tbody>
</table>
<NcNoteCard v-if="showSecretWarning"
type="warning">
{{ t('oauth2', 'Make sure you store the secret key, it cannot be recovered.') }}
</NcNoteCard>

<br>
<h3>{{ t('oauth2', 'Add client') }}</h3>
Expand Down Expand Up @@ -66,6 +70,7 @@ import { generateUrl } from '@nextcloud/router'
import { getCapabilities } from '@nextcloud/capabilities'
import NcSettingsSection from '@nextcloud/vue/dist/Components/NcSettingsSection.js'
import NcButton from '@nextcloud/vue/dist/Components/NcButton.js'
import NcNoteCard from '@nextcloud/vue/dist/Components/NcNoteCard.js'
import { loadState } from '@nextcloud/initial-state'
import NcTextField from '@nextcloud/vue/dist/Components/NcTextField.js'

Expand All @@ -76,6 +81,7 @@ export default {
NcSettingsSection,
NcButton,
NcTextField,
NcNoteCard,
},
props: {
clients: {
Expand All @@ -92,6 +98,7 @@ export default {
error: false,
},
oauthDocLink: loadState('oauth2', 'oauth2-doc-link'),
showSecretWarning: false,
}
},
computed: {
Expand Down Expand Up @@ -119,6 +126,7 @@ export default {
).then(response => {
// eslint-disable-next-line vue/no-mutating-props
this.clients.push(response.data)
this.showSecretWarning = true

this.newClient.name = ''
this.newClient.redirectUri = ''
Expand Down
3 changes: 2 additions & 1 deletion apps/oauth2/src/components/OAuthItem.vue
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
<td>
<div class="action-secret">
<code>{{ renderedSecret }}</code>
<NcButton type="tertiary-no-background"
<NcButton v-if="clientSecret !== ''"
type="tertiary-no-background"
:aria-label="toggleAriaLabel"
@click="toggleSecret">
<template #icon>
Expand Down
81 changes: 44 additions & 37 deletions apps/oauth2/tests/Controller/OauthApiControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -249,9 +249,20 @@ public function testRefreshTokenInvalidClient($clientId, $clientSecret) {
->with('validrefresh')
->willReturn($accessToken);

$this->crypto
->method('calculateHMAC')
->with($this->callback(function (string $text) {
return $text === 'clientSecret' || $text === 'invalidClientSecret';
}))
->willReturnCallback(function (string $text) {
return $text === 'clientSecret'
? 'hashedClientSecret'
: 'hashedInvalidClientSecret';
});

$client = new Client();
$client->setClientIdentifier('clientId');
$client->setSecret('clientSecret');
$client->setSecret(bin2hex('hashedClientSecret'));
$this->clientMapper->method('getByUid')
->with(42)
->willReturn($client);
Expand All @@ -276,21 +287,20 @@ public function testRefreshTokenInvalidAppToken() {

$client = new Client();
$client->setClientIdentifier('clientId');
$client->setSecret('encryptedClientSecret');
$client->setSecret(bin2hex('hashedClientSecret'));
$this->clientMapper->method('getByUid')
->with(42)
->willReturn($client);

$this->crypto
->method('decrypt')
->with($this->callback(function (string $text) {
return $text === 'encryptedClientSecret' || $text === 'encryptedToken';
}))
->willReturnCallback(function (string $text) {
return $text === 'encryptedClientSecret'
? 'clientSecret'
: ($text === 'encryptedToken' ? 'decryptedToken' : '');
});
->with('encryptedToken')
->willReturn('decryptedToken');

$this->crypto
->method('calculateHMAC')
->with('clientSecret')
->willReturn('hashedClientSecret');

$this->tokenProvider->method('getTokenById')
->with(1337)
Expand All @@ -315,21 +325,20 @@ public function testRefreshTokenValidAppToken() {

$client = new Client();
$client->setClientIdentifier('clientId');
$client->setSecret('encryptedClientSecret');
$client->setSecret(bin2hex('hashedClientSecret'));
$this->clientMapper->method('getByUid')
->with(42)
->willReturn($client);

$this->crypto
->method('decrypt')
->with($this->callback(function (string $text) {
return $text === 'encryptedClientSecret' || $text === 'encryptedToken';
}))
->willReturnCallback(function (string $text) {
return $text === 'encryptedClientSecret'
? 'clientSecret'
: ($text === 'encryptedToken' ? 'decryptedToken' : '');
});
->with('encryptedToken')
->willReturn('decryptedToken');

$this->crypto
->method('calculateHMAC')
->with('clientSecret')
->willReturn('hashedClientSecret');

$appToken = new PublicKeyToken();
$appToken->setUid('userId');
Expand Down Expand Up @@ -412,21 +421,20 @@ public function testRefreshTokenValidAppTokenBasicAuth() {

$client = new Client();
$client->setClientIdentifier('clientId');
$client->setSecret('encryptedClientSecret');
$client->setSecret(bin2hex('hashedClientSecret'));
$this->clientMapper->method('getByUid')
->with(42)
->willReturn($client);

$this->crypto
->method('decrypt')
->with($this->callback(function (string $text) {
return $text === 'encryptedClientSecret' || $text === 'encryptedToken';
}))
->willReturnCallback(function (string $text) {
return $text === 'encryptedClientSecret'
? 'clientSecret'
: ($text === 'encryptedToken' ? 'decryptedToken' : '');
});
->with('encryptedToken')
->willReturn('decryptedToken');

$this->crypto
->method('calculateHMAC')
->with('clientSecret')
->willReturn('hashedClientSecret');

$appToken = new PublicKeyToken();
$appToken->setUid('userId');
Expand Down Expand Up @@ -512,21 +520,20 @@ public function testRefreshTokenExpiredAppToken() {

$client = new Client();
$client->setClientIdentifier('clientId');
$client->setSecret('encryptedClientSecret');
$client->setSecret(bin2hex('hashedClientSecret'));
$this->clientMapper->method('getByUid')
->with(42)
->willReturn($client);

$this->crypto
->method('decrypt')
->with($this->callback(function (string $text) {
return $text === 'encryptedClientSecret' || $text === 'encryptedToken';
}))
->willReturnCallback(function (string $text) {
return $text === 'encryptedClientSecret'
? 'clientSecret'
: ($text === 'encryptedToken' ? 'decryptedToken' : '');
});
->with('encryptedToken')
->willReturn('decryptedToken');

$this->crypto
->method('calculateHMAC')
->with('clientSecret')
->willReturn('hashedClientSecret');

$appToken = new PublicKeyToken();
$appToken->setUid('userId');
Expand Down
10 changes: 5 additions & 5 deletions apps/oauth2/tests/Controller/SettingsControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,13 @@ public function testAddClient() {

$this->crypto
->expects($this->once())
->method('encrypt')
->willReturn('MyEncryptedSecret');
->method('calculateHMAC')
->willReturn('MyHashedSecret');

$client = new Client();
$client->setName('My Client Name');
$client->setRedirectUri('https://example.com/');
$client->setSecret('MySecret');
$client->setSecret(bin2hex('MyHashedSecret'));
$client->setClientIdentifier('MyClientIdentifier');

$this->clientMapper
Expand All @@ -96,7 +96,7 @@ public function testAddClient() {
->with($this->callback(function (Client $c) {
return $c->getName() === 'My Client Name' &&
$c->getRedirectUri() === 'https://example.com/' &&
$c->getSecret() === 'MyEncryptedSecret' &&
$c->getSecret() === bin2hex('MyHashedSecret') &&
$c->getClientIdentifier() === 'MyClientIdentifier';
}))->willReturnCallback(function (Client $c) {
$c->setId(42);
Expand Down Expand Up @@ -139,7 +139,7 @@ public function testDeleteClient() {
$client->setId(123);
$client->setName('My Client Name');
$client->setRedirectUri('https://example.com/');
$client->setSecret('MySecret');
$client->setSecret(bin2hex('MyHashedSecret'));
$client->setClientIdentifier('MyClientIdentifier');

$this->clientMapper
Expand Down
4 changes: 1 addition & 3 deletions apps/oauth2/tests/Settings/AdminTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
use OCP\AppFramework\Http\TemplateResponse;
use OCP\AppFramework\Services\IInitialState;
use OCP\IURLGenerator;
use OCP\Security\ICrypto;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
use Test\TestCase;
Expand All @@ -20,7 +19,7 @@ class AdminTest extends TestCase {
/** @var Admin|MockObject */
private $admin;

/** @var IInitialStateService|MockObject */
/** @var IInitialState|MockObject */
private $initialState;

/** @var ClientMapper|MockObject */
Expand All @@ -36,7 +35,6 @@ protected function setUp(): void {
$this->initialState,
$this->clientMapper,
$this->createMock(IURLGenerator::class),
$this->createMock(ICrypto::class),
$this->createMock(LoggerInterface::class)
);
}
Expand Down
4 changes: 2 additions & 2 deletions dist/core-common.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/core-common.js.map

Large diffs are not rendered by default.

Loading
Loading