From 614bf980833a10865148452724097f3dd72aa341 Mon Sep 17 00:00:00 2001 From: romanetar Date: Tue, 1 Dec 2026 18:53:33 +0100 Subject: [PATCH] fix(2fa): rate limit the current-password check of the user update The current-password check of the profile password change had no limit: a session could guess the password without a bound, and a correct guess both changes the password and gives the secret that 2fa/disable and recovery-codes/regenerate ask for, so the limit added to those two could be sidestepped. The OAuth2 profile update reaches the same check. - UserService::update: a wrong or missing current_password consumes the password_confirm limit of the acting user (the counter 2fa/disable and recovery-codes/regenerate share), keyed by the (int) user id the service already resolves, so it also works on a token request with no session - the attempt is reserved first and refunded when the password is right: a successful change never counts, and a user over the limit gets the 429 without learning if the password was right; a save without password is never limited - new TwoFactorRateLimitedException, mapped to 429 with Retry-After in APICRUDController::_update (PUT admin/api/v1/users/me and users/{id}) and OAuth2UserApiController::_update (PUT api/v1/users/me), which turned it into a 500 - tests with the whole middleware stack for the admin routes, the shared counter and the OAuth2 route with a token and no session ClickUp 1k5eh578uwa --- .../Controllers/Api/APICRUDController.php | 6 + .../Api/OAuth2/OAuth2UserApiController.php | 4 + app/Http/Controllers/Traits/JsonResponses.php | 23 +- app/Services/OpenId/UserService.php | 61 ++++- .../TwoFactorRateLimitedException.php | 53 ++++ .../OAuth2UserUpdatePasswordRateLimitTest.php | 138 ++++++++++ tests/UserUpdatePasswordRateLimitTest.php | 254 ++++++++++++++++++ 7 files changed, 531 insertions(+), 8 deletions(-) create mode 100644 app/libs/Auth/Exceptions/TwoFactorRateLimitedException.php create mode 100644 tests/OAuth2UserUpdatePasswordRateLimitTest.php create mode 100644 tests/UserUpdatePasswordRateLimitTest.php diff --git a/app/Http/Controllers/Api/APICRUDController.php b/app/Http/Controllers/Api/APICRUDController.php index 1d4178494..629e65600 100644 --- a/app/Http/Controllers/Api/APICRUDController.php +++ b/app/Http/Controllers/Api/APICRUDController.php @@ -14,6 +14,7 @@ use App\Http\Controllers\Api\JsonController; use App\ModelSerializers\SerializerRegistry; use App\Services\IBaseService; +use Auth\Exceptions\TwoFactorRateLimitedException; use Illuminate\Support\Facades\Request; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Validator; @@ -150,6 +151,11 @@ protected function _update($id, array $payload) return $this->updated(SerializerRegistry::getInstance()->getSerializer($entity, $this->serializerType())->serialize()); } + catch (TwoFactorRateLimitedException $ex0) + { + Log::warning($ex0); + return $this->error429($ex0->getRetryAfterSeconds(), $ex0->getLimit()); + } catch (ValidationException $ex1) { Log::warning($ex1); diff --git a/app/Http/Controllers/Api/OAuth2/OAuth2UserApiController.php b/app/Http/Controllers/Api/OAuth2/OAuth2UserApiController.php index 1880fca76..7c4e29779 100644 --- a/app/Http/Controllers/Api/OAuth2/OAuth2UserApiController.php +++ b/app/Http/Controllers/Api/OAuth2/OAuth2UserApiController.php @@ -21,6 +21,7 @@ use App\Http\Utils\HTMLCleaner; use App\ModelSerializers\SerializerRegistry; use App\ModelSerializers\SerializerUtils; +use Auth\Exceptions\TwoFactorRateLimitedException; use Auth\Repositories\IUserRepository; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request as LaravelRequest; @@ -317,6 +318,9 @@ private function _update($id) $user = $this->openid_user_service->update($id, $this->curateUpdatePayload($payload)); return $this->updated(SerializerRegistry::getInstance()->getSerializer($user, SerializerRegistry::SerializerType_Private)->serialize()); + } catch (TwoFactorRateLimitedException $ex0) { + Log::warning($ex0); + return $this->error429($ex0->getRetryAfterSeconds(), $ex0->getLimit()); } catch (ValidationException $ex1) { Log::warning($ex1); return $this->error412($ex1->getMessages()); diff --git a/app/Http/Controllers/Traits/JsonResponses.php b/app/Http/Controllers/Traits/JsonResponses.php index b0d9fff75..7f1908892 100644 --- a/app/Http/Controllers/Traits/JsonResponses.php +++ b/app/Http/Controllers/Traits/JsonResponses.php @@ -11,6 +11,7 @@ * See the License for the specific language governing permissions and * limitations under the License. **/ +use App\Services\Auth\ITwoFactorRateLimitService; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Request; use Illuminate\Support\Facades\Response; @@ -102,4 +103,24 @@ protected function error412($messages){ } return Response::json(array('message' => 'Validation Failed', 'errors' => $messages), HttpResponse::HTTP_PRECONDITION_FAILED); } -} \ No newline at end of file + + /** + * @param int $retry_after_seconds + * @param int|null $limit + * @return mixed + */ + protected function error429(int $retry_after_seconds, ?int $limit = null){ + $headers = ['Retry-After' => $retry_after_seconds]; + if(!is_null($limit)){ + $headers['X-RateLimit-Limit'] = $limit; + $headers['X-RateLimit-Remaining'] = 0; + } + return Response::json( + [ + 'error_code' => ITwoFactorRateLimitService::RATE_LIMIT_ERROR_CODE, + 'error_message' => ITwoFactorRateLimitService::RATE_LIMIT_MESSAGE, + ], + HttpResponse::HTTP_TOO_MANY_REQUESTS + )->withHeaders($headers); + } +} diff --git a/app/Services/OpenId/UserService.php b/app/Services/OpenId/UserService.php index fbd996ac0..cecd6201d 100644 --- a/app/Services/OpenId/UserService.php +++ b/app/Services/OpenId/UserService.php @@ -26,7 +26,9 @@ use App\Services\AbstractService; use App\Services\Auth\IRecoveryCodeService; use App\Services\Auth\ITwoFactorAuditService; +use App\Services\Auth\ITwoFactorRateLimitService; use App\Services\Auth\IUserIdentifierGeneratorService; +use Auth\Exceptions\TwoFactorRateLimitedException; use Auth\Group; use Auth\IUserNameGeneratorService; use Auth\Repositories\IUserRepository; @@ -93,6 +95,11 @@ final class UserService extends AbstractService implements IUserService */ private $server_ctx; + /** + * @var ITwoFactorRateLimitService + */ + private $rate_limit_service; + /** * @var IUserIdentifierGeneratorService */ @@ -121,6 +128,7 @@ final class UserService extends AbstractService implements IUserService * @param IClientRepository $client_repository * @param IRecoveryCodeService $recovery_code_service * @param ITwoFactorAuditService $two_factor_audit_service + * @param ITwoFactorRateLimitService $rate_limit_service */ public function __construct ( @@ -134,10 +142,12 @@ public function __construct IUserIdentifierGeneratorService $identifier_service, IClientRepository $client_repository, IRecoveryCodeService $recovery_code_service, - ITwoFactorAuditService $two_factor_audit_service + ITwoFactorAuditService $two_factor_audit_service, + ITwoFactorRateLimitService $rate_limit_service ) { parent::__construct($tx_service); + $this->rate_limit_service = $rate_limit_service; $this->recovery_code_service = $recovery_code_service; $this->two_factor_audit_service = $two_factor_audit_service; $this->repository = $repository; @@ -305,6 +315,48 @@ public function create(array $payload): IEntity return $user; } + /** + * Checks the current password of a password change. A wrong or missing one counts against the + * password_confirm limit of the acting user, the same counter 2fa/disable and + * recovery-codes/regenerate use (SDS idp-mfa.md section 4.12), so the password cannot be + * guessed through the user update. The counter is keyed by the acting user resolved by + * update() and not by Auth::id(): it is also set on the OAuth2 route, where there is no + * session. Same as the 2fa.rate middleware, the attempt is reserved first and given back when + * the password is right: a successful change never counts, and a user over the limit gets the + * 429 without learning if the password was right. + * @param User $user user to update + * @param User|null $current_user acting user + * @param array $payload + * @throws ValidationException + * @throws TwoFactorRateLimitedException + */ + private function checkCurrentPassword(User $user, ?User $current_user, array $payload): void + { + $action = ITwoFactorRateLimitService::ActionPasswordConfirm; + // no acting user (console / service account): nobody to throttle + $subject = !is_null($current_user) ? (int)$current_user->getId() : null; + + if (!is_null($subject)) { + $attempts = $this->rate_limit_service->consume($action, $subject); + if ($attempts > $this->rate_limit_service->getLimit($action)) { + throw new TwoFactorRateLimitedException( + $this->rate_limit_service->getRetryAfterSeconds($action, $subject), + $this->rate_limit_service->getLimit($action), + ITwoFactorRateLimitService::RATE_LIMIT_MESSAGE + ); + } + } + + if (!isset($payload['current_password'])) + throw new ValidationException(sprintf("current_password is needed to update user password.")); + + if (!$user->checkPassword(trim($payload['current_password']))) + throw new ValidationException(sprintf("current_password is not correct.")); + + if (!is_null($subject)) + $this->rate_limit_service->refund($action, $subject); + } + /** * @param int $id * @param array $payload @@ -337,12 +389,7 @@ public function update(int $id, array $payload): IEntity if ($should_ask_4_cur_password_validation) { if (isset($payload["password"]) && !empty($payload["password"])) { // changing password - if (!isset($payload['current_password'])) - throw new ValidationException(sprintf("current_password is needed to update user password.")); - - if (!$user->checkPassword(trim($payload['current_password']))) { - throw new ValidationException(sprintf("current_password is not correct.")); - } + $this->checkCurrentPassword($user, $current_user, $payload); } } diff --git a/app/libs/Auth/Exceptions/TwoFactorRateLimitedException.php b/app/libs/Auth/Exceptions/TwoFactorRateLimitedException.php new file mode 100644 index 000000000..317c24ae8 --- /dev/null +++ b/app/libs/Auth/Exceptions/TwoFactorRateLimitedException.php @@ -0,0 +1,53 @@ +retry_after_seconds; + } + + /** + * @return int max attempts of the window + */ + public function getLimit(): int + { + return $this->limit; + } +} diff --git a/tests/OAuth2UserUpdatePasswordRateLimitTest.php b/tests/OAuth2UserUpdatePasswordRateLimitTest.php new file mode 100644 index 000000000..366a4525c --- /dev/null +++ b/tests/OAuth2UserUpdatePasswordRateLimitTest.php @@ -0,0 +1,138 @@ +findOneBy(['identifier' => 'sebastian.marcet']); + $this->owner_id = $owner->getId(); + $this->clearCounter(); + + // the token is issued: from here on the request carries only the token, no session + Auth::forgetGuards(); + Session::flush(); + } + + protected function tearDown(): void + { + if (isset($this->owner_id)) + $this->clearCounter(); + parent::tearDown(); + } + + private function counterKey(): string + { + return ITwoFactorRateLimitService::RATE_LIMIT_CACHE_KEY_PREFIX + . ITwoFactorRateLimitService::ActionPasswordConfirm . ':' . $this->owner_id; + } + + private function clearCounter(): void + { + RateLimiter::clear($this->counterKey()); + } + + private function owner(): User + { + return EntityManager::getRepository(User::class)->find($this->owner_id); + } + + private function changePassword(string $current_password) + { + return $this->action( + "PUT", + "Api\\OAuth2\\OAuth2UserApiController@updateMe", + [], + [], + [], + [], + [ + "HTTP_Authorization" => " Bearer " . $this->access_token, + "CONTENT_TYPE" => "application/json", + ], + json_encode([ + 'email' => 'sebastian.marcet@test.invalid', + 'current_password' => $current_password, + 'password' => self::NEW_PASSWORD, + 'password_confirmation' => self::NEW_PASSWORD, + ]) + ); + } + + public function testSixthWrongCurrentPasswordAnswers429NotAn500(): void + { + // the middleware limiter has no subject here: nothing logs the token owner into the session guard + $this->assertNull(Auth::id()); + + for ($i = 0; $i < self::MAX_ATTEMPTS; $i++) { + $this->changePassword('not-the-password'); + $this->assertResponseStatus(412); + } + + $response = $this->changePassword('not-the-password'); + $this->assertResponseStatus(429); + $this->assertGreaterThan(0, (int)$response->headers->get('Retry-After')); + + // locked: not even the right password gets through until the window ends + $this->changePassword(self::PASSWORD); + $this->assertResponseStatus(429); + $this->assertTrue($this->owner()->checkPassword(self::PASSWORD)); + $this->assertFalse($this->owner()->checkPassword(self::NEW_PASSWORD)); + } + + public function testCorrectCurrentPasswordWithinTheLimitChangesItAndDoesNotCount(): void + { + for ($i = 0; $i < self::MAX_ATTEMPTS - 1; $i++) { + $this->changePassword('not-the-password'); + $this->assertResponseStatus(412); + } + + $this->changePassword(self::PASSWORD); + $this->assertResponseStatus(201); + + $this->assertTrue($this->owner()->checkPassword(self::NEW_PASSWORD)); + $this->assertSame(self::MAX_ATTEMPTS - 1, (int)RateLimiter::attempts($this->counterKey())); + } +} diff --git a/tests/UserUpdatePasswordRateLimitTest.php b/tests/UserUpdatePasswordRateLimitTest.php new file mode 100644 index 000000000..5390d4ea2 --- /dev/null +++ b/tests/UserUpdatePasswordRateLimitTest.php @@ -0,0 +1,254 @@ +test_user = EntityManager::getRepository(User::class) + ->findOneBy(['identifier' => 'sebastian.marcet']); + $this->be($this->test_user, 'web'); + $this->clearCounter($this->test_user->getId()); + } + + protected function tearDown(): void + { + if (isset($this->test_user)) + $this->clearCounter($this->test_user->getId()); + parent::tearDown(); + } + + private function counterKey(int $user_id): string + { + return ITwoFactorRateLimitService::RATE_LIMIT_CACHE_KEY_PREFIX + . ITwoFactorRateLimitService::ActionPasswordConfirm . ':' . $user_id; + } + + private function clearCounter(int $user_id): void + { + RateLimiter::clear($this->counterKey($user_id)); + } + + private function attempts(int $user_id): int + { + return (int)RateLimiter::attempts($this->counterKey($user_id)); + } + + private function storedPassword(int $user_id): string + { + return (string)DB::table('users')->where('id', $user_id)->value('password'); + } + + private function changePassword(string $current_password) + { + return $this->put('/admin/api/v1/users/me', [ + 'first_name' => $this->test_user->getFirstName(), + 'last_name' => $this->test_user->getLastName(), + 'email' => $this->test_user->getEmail(), + 'current_password' => $current_password, + 'password' => self::NEW_PASSWORD, + 'password_confirmation' => self::NEW_PASSWORD, + ]); + } + + private function disableTwoFactor(string $current_password) + { + return $this->post('/admin/api/v1/users/me/2fa/disable', ['current_password' => $current_password]); + } + + public function testSixthWrongCurrentPasswordAnswers429AndKeepsThePassword(): void + { + $hash = $this->storedPassword($this->test_user->getId()); + + for ($i = 0; $i < self::MAX_ATTEMPTS; $i++) { + $this->changePassword('not-the-password')->assertResponseStatus(412); + } + + $this->changePassword('not-the-password')->assertResponseStatus(429); + $this->assertGreaterThan(0, (int)$this->response->headers->get('Retry-After')); + + // locked: not even the right password gets through until the window ends + $this->changePassword(self::PASSWORD)->assertResponseStatus(429); + $this->assertSame($hash, $this->storedPassword($this->test_user->getId())); + } + + public function testMissingCurrentPasswordCountsAsAFailure(): void + { + // bypasses the validation rule (required_with:password) to reach the service check + $service = $this->app->make(IUserService::class); + + for ($i = 0; $i < self::MAX_ATTEMPTS; $i++) { + try { + $service->update($this->test_user->getId(), ['password' => self::NEW_PASSWORD]); + $this->fail('a missing current_password must be refused'); + } catch (ValidationException $ex) { + $this->assertStringContainsString('current_password is needed', $ex->getMessage()); + } + } + + $this->expectException(TwoFactorRateLimitedException::class); + $service->update($this->test_user->getId(), ['password' => self::NEW_PASSWORD]); + } + + public function testFailuresShareOneCounterWithDisableTwoFactor(): void + { + // 3 wrong guesses on the user update + 2 on 2fa/disable = 5 failures of one counter + for ($i = 0; $i < 3; $i++) { + $this->changePassword('not-the-password')->assertResponseStatus(412); + } + for ($i = 0; $i < 2; $i++) { + $this->disableTwoFactor('not-the-password')->assertResponseStatus(412); + } + + $this->disableTwoFactor('not-the-password')->assertResponseStatus(429); + $this->changePassword('not-the-password')->assertResponseStatus(429); + } + + public function testFailuresOfDisableTwoFactorLockTheUserUpdate(): void + { + for ($i = 0; $i < self::MAX_ATTEMPTS; $i++) { + $this->disableTwoFactor('not-the-password')->assertResponseStatus(412); + } + + $this->changePassword('not-the-password')->assertResponseStatus(429); + $this->assertGreaterThan(0, (int)$this->response->headers->get('Retry-After')); + } + + public function testSaveWithoutPasswordIsNeverLimited(): void + { + // the counter is full ... + for ($i = 0; $i < self::MAX_ATTEMPTS; $i++) { + $this->changePassword('not-the-password')->assertResponseStatus(412); + } + + // ... and a validation error before it must not matter either + $this->put('/admin/api/v1/users/me', ['email' => 'not-an-email'])->assertResponseStatus(412); + + $this->put('/admin/api/v1/users/me', [ + 'first_name' => 'Renamed', + 'last_name' => $this->test_user->getLastName(), + 'email' => $this->test_user->getEmail(), + ])->assertResponseStatus(201); + } + + public function testValidationErrorsWithoutPasswordDoNotConsumeTheLimit(): void + { + for ($i = 0; $i < self::MAX_ATTEMPTS + 2; $i++) { + $this->put('/admin/api/v1/users/me', ['email' => 'not-an-email'])->assertResponseStatus(412); + } + + $this->assertSame(0, $this->attempts($this->test_user->getId())); + $this->changePassword(self::PASSWORD)->assertResponseStatus(201); + } + + public function testCorrectCurrentPasswordChangesItAndDoesNotCount(): void + { + $hash = $this->storedPassword($this->test_user->getId()); + + for ($i = 0; $i < self::MAX_ATTEMPTS - 1; $i++) { + $this->changePassword('not-the-password')->assertResponseStatus(412); + } + $this->assertSame(self::MAX_ATTEMPTS - 1, $this->attempts($this->test_user->getId())); + + $this->changePassword(self::PASSWORD)->assertResponseStatus(201); + + $this->assertNotSame($hash, $this->storedPassword($this->test_user->getId())); + $this->assertSame(self::MAX_ATTEMPTS - 1, $this->attempts($this->test_user->getId())); + } + + public function testUpdatingAnotherUserCountsAgainstTheActingUser(): void + { + $actor = $this->createUser('actor'); + $target = $this->createUser('target'); + $this->clearCounter($actor->getId()); + $this->clearCounter($target->getId()); + $this->be($actor, 'web'); + + $service = $this->app->make(IUserService::class); + $hash = $this->storedPassword($target->getId()); + + // the actor is not an administrator: the target's current password is asked + for ($i = 0; $i < self::MAX_ATTEMPTS; $i++) { + try { + $service->update($target->getId(), [ + 'password' => self::NEW_PASSWORD, + 'current_password' => 'not-the-password', + ]); + $this->fail('a wrong current_password must be refused'); + } catch (ValidationException $ex) { + $this->assertStringContainsString('current_password is not correct', $ex->getMessage()); + } + } + + $this->assertSame(self::MAX_ATTEMPTS, $this->attempts($actor->getId())); + $this->assertSame(0, $this->attempts($target->getId())); + + try { + $service->update($target->getId(), [ + 'password' => self::NEW_PASSWORD, + 'current_password' => 'not-the-password', + ]); + $this->fail('the acting user is over the limit'); + } catch (TwoFactorRateLimitedException $ex) { + $this->assertGreaterThan(0, $ex->getRetryAfterSeconds()); + $this->assertSame(self::MAX_ATTEMPTS, $ex->getLimit()); + } + + $this->assertSame($hash, $this->storedPassword($target->getId())); + $this->clearCounter($actor->getId()); + $this->clearCounter($target->getId()); + } + + private function createUser(string $prefix): User + { + $user = UserFactory::build([ + 'first_name' => $prefix, + 'last_name' => 'RateLimit', + 'email' => $prefix . '.' . uniqid() . '@test.invalid', + 'active' => true, + 'email_verified' => true, + 'identifier' => $prefix . '.' . uniqid(), + 'password' => self::PASSWORD, + 'password_enc' => AuthHelper::AlgSHA1_V2_4, + ]); + EntityManager::persist($user); + EntityManager::flush(); + return $user; + } +}