diff --git a/ProcessMaker/Http/Controllers/Api/UserController.php b/ProcessMaker/Http/Controllers/Api/UserController.php index ee2acfa837..aa8d9eb5ae 100644 --- a/ProcessMaker/Http/Controllers/Api/UserController.php +++ b/ProcessMaker/Http/Controllers/Api/UserController.php @@ -15,6 +15,7 @@ use ProcessMaker\Events\UserUpdated; use ProcessMaker\Exception\ReferentialIntegrityException; use ProcessMaker\Filters\SaveSession; +use ProcessMaker\Http\Controllers\Auth\TwoFactorAuthController; use ProcessMaker\Http\Controllers\Controller; use ProcessMaker\Http\Resources\ApiCollection; use ProcessMaker\Http\Resources\Users as UserResource; @@ -535,97 +536,19 @@ public function update(User $user, Request $request) $isLdapUser = isset($user->meta?->authenticationType) && $user->meta->authenticationType === 'ldap'; $user->fill($fields); - if (array_key_exists('cell', $fields)) { - $response = $this->validateCellPhoneNumber($user, $fields['cell']); - if ($response) { - return $response; - } - } - if ($fields['email'] !== $original['email']) { - $ssoUser = $isLdapUser; - if (class_exists(SsoUser::class)) { - // Check if the user is an SSO user (including SAML) - $ssoUser = $ssoUser || SsoUser::where('user_id', $user->id)->exists(); - } - if ($ssoUser) { - return response([ - 'message' => __( - "The email can't be edited. This action is only available for SSO-synced users." - ), - 'errors' => [ - 'email' => [ - __( - "The email can't be edited. This action is only available for SSO-synced users." - ), - ], - ], - ], 422); - } - if (!isset($fields['valpassword'])) { - return response([ - 'message' => __( - 'A valid authentication is required for for update the email.' - ), - 'errors' => [ - 'email' => [ - __( - 'The password is required.' - ), - ], - ], - ], 422); - } else { - $response = $this->validateBeforeChange(Auth::user(), $fields['valpassword']); - if ($response) { - return $response; - } - } - } - if (Auth::user()->is_administrator && $request->has('is_administrator')) { - // user must be an admin to make another user an admin - $user->is_administrator = $request->get('is_administrator'); - } - - if (empty($fields['meta'])) { - $user->meta = null; - } - - try { - $user->saveOrFail(); - } catch (\Exception $e) { - $slackExceptionClass = 'ProcessMaker\Packages\Connectors\Slack\Exceptions\SlackConfigurationException'; - if (class_exists($slackExceptionClass) && $e instanceof $slackExceptionClass) { - return response([ - 'message' => $e->getMessage(), - ], 422); - } - - throw $e; + $validationResponse = $this->resolveUserUpdateValidationResponse( + $authenticatedUser, + $user, + $fields, + $original, + $isLdapUser + ); + if ($validationResponse !== null) { + return $validationResponse; } - $changes = $user->getChanges(); - - //Call new Event to store User Changes into LOG - UserUpdated::dispatch($user, $changes, $original); - try { - if ($request->has('avatar')) { - $this->uploadAvatar($user, $request); - } - } catch (\Exception $e) { - return response([ - 'message' => 'Error uploading avatar', - 'errors' => [ - 'avatar' => [ - $e->getMessage(), - ], - ], - ], 422); - } - - RecommendationEngine::handleUserSettingChanges($user, $original); - - return response([], 204); + return $this->completeUserUpdate($user, $request, $fields, $original); } /** @@ -681,6 +604,172 @@ private function normalizeSelfServiceMeta(User $user, array $fields): array return $fields; } + private function resolveUserUpdateValidationResponse( + User $authenticatedUser, + User $user, + array $fields, + array $original, + bool $isLdapUser + ) { + $response = $this->selfServiceTwoFactorSensitiveUpdateBlocked( + $authenticatedUser, + $user, + $fields, + $original + ); + if ($response === null && array_key_exists('cell', $fields)) { + $response = $this->validateCellPhoneNumber($user, $fields['cell']) ?: null; + } + if ($response === null && $fields['email'] !== $original['email']) { + $response = $this->validateEmailChangeForUpdate($user, $fields, $isLdapUser); + } + + return $response; + } + + private function selfServiceTwoFactorSensitiveUpdateBlocked( + User $authenticatedUser, + User $user, + array $fields, + array $original + ) { + if ($authenticatedUser->id !== $user->id || !$this->touchesTwoFactorDestinations($fields, $original)) { + return null; + } + + if (!$this->selfServiceTwoFactorCompletionPending($authenticatedUser)) { + return null; + } + + return response()->json([ + 'message' => __('Two-factor authentication must be completed before updating 2FA preferences.'), + ], 422); + } + + private function touchesTwoFactorDestinations(array $fields, array $original): bool + { + if (array_key_exists('preferences_2fa', $fields)) { + return true; + } + + if (array_key_exists('cell', $fields) && ($fields['cell'] ?? null) !== ($original['cell'] ?? null)) { + return true; + } + + return array_key_exists('email', $fields) + && ($fields['email'] ?? null) !== ($original['email'] ?? null); + } + + private function selfServiceTwoFactorCompletionPending(User $authenticatedUser): bool + { + if (session('sso_driver') !== null + || !config('password-policies.2fa_enabled', false) + || empty(config('password-policies.2fa_method', [])) + || !TwoFactorAuthController::check2faByGroups() + ) { + return false; + } + + $webUserId = Auth::guard('web')->id(); + + return $webUserId === null + || (int) $webUserId !== (int) $authenticatedUser->id + || !session()->get(TwoFactorAuthController::TFA_VALIDATED, false); + } + + private function validateEmailChangeForUpdate(User $user, array $fields, bool $isLdapUser) + { + $response = null; + $ssoUser = $isLdapUser; + if (class_exists(SsoUser::class)) { + // Check if the user is an SSO user (including SAML) + $ssoUser = $ssoUser || SsoUser::where('user_id', $user->id)->exists(); + } + if ($ssoUser) { + $response = response([ + 'message' => __( + "The email can't be edited. This action is only available for SSO-synced users." + ), + 'errors' => [ + 'email' => [ + __( + "The email can't be edited. This action is only available for SSO-synced users." + ), + ], + ], + ], 422); + } elseif (!isset($fields['valpassword'])) { + $response = response([ + 'message' => __( + 'A valid authentication is required for for update the email.' + ), + 'errors' => [ + 'email' => [ + __( + 'The password is required.' + ), + ], + ], + ], 422); + } else { + $emailAuthResponse = $this->validateBeforeChange(Auth::user(), $fields['valpassword']); + if ($emailAuthResponse) { + $response = $emailAuthResponse; + } + } + + return $response; + } + + private function completeUserUpdate(User $user, Request $request, array $fields, array $original) + { + if (Auth::user()->is_administrator && $request->has('is_administrator')) { + // user must be an admin to make another user an admin + $user->is_administrator = $request->get('is_administrator'); + } + + if (empty($fields['meta'])) { + $user->meta = null; + } + + try { + $user->saveOrFail(); + } catch (\Exception $e) { + $slackExceptionClass = 'ProcessMaker\Packages\Connectors\Slack\Exceptions\SlackConfigurationException'; + + if (class_exists($slackExceptionClass) && $e instanceof $slackExceptionClass) { + return response([ + 'message' => $e->getMessage(), + ], 422); + } + + throw $e; + } + + $changes = $user->getChanges(); + + //Call new Event to store User Changes into LOG + UserUpdated::dispatch($user, $changes, $original); + try { + if ($request->has('avatar')) { + $this->uploadAvatar($user, $request); + } + } catch (\Exception $e) { + return response([ + 'message' => 'Error uploading avatar', + 'errors' => [ + 'avatar' => [ + $e->getMessage(), + ], + ], + ], 422); + } + + RecommendationEngine::handleUserSettingChanges($user, $original); + + return response([], 204); + } + /** * Validate the phone number for SMS two-factor authentication. * diff --git a/ProcessMaker/Http/Controllers/Auth/LoginController.php b/ProcessMaker/Http/Controllers/Auth/LoginController.php index 38b39fc9b6..0c8b31ba9e 100644 --- a/ProcessMaker/Http/Controllers/Auth/LoginController.php +++ b/ProcessMaker/Http/Controllers/Auth/LoginController.php @@ -12,6 +12,7 @@ use Laravel\Passport\ApiTokenCookieFactory; use Laravel\Passport\Passport; use ProcessMaker\Events\Logout; +use ProcessMaker\Http\Controllers\Auth\TwoFactorAuthController; use ProcessMaker\Http\Controllers\Controller; use ProcessMaker\Managers\LoginManager; use ProcessMaker\Models\Setting; @@ -19,6 +20,7 @@ use ProcessMaker\Package\Auth\Database\Seeds\AuthDefaultSeeder; use ProcessMaker\Services\PermissionCacheService; use ProcessMaker\Traits\HasControllerAddons; +use ProcessMaker\TwoFactorAuthentication; class LoginController extends Controller { @@ -274,6 +276,13 @@ protected function authenticated(Request $request, $user) if (env('LOGOUT_OTHER_DEVICES', false)) { Auth::logoutOtherDevices($request->input('password')); } + + if (config('password-policies.2fa_enabled', false) + && !empty(config('password-policies.2fa_method', [])) + && TwoFactorAuthController::check2faByGroups() + ) { + (new TwoFactorAuthentication())->rememberChallengeMethodsSnapshot($user); + } } public function beforeLogout(Request $request) @@ -294,6 +303,11 @@ public function beforeLogout(Request $request) session()->remove(TwoFactorAuthController::TFA_VALIDATED); session()->remove(TwoFactorAuthController::TFA_MESSAGE); session()->remove(TwoFactorAuthController::TFA_ERROR); + session()->remove(TwoFactorAuthentication::CHALLENGE_METHODS_SNAPSHOT); + session()->remove(TwoFactorAuthentication::CHALLENGE_DELIVERY_EMAIL); + session()->remove(TwoFactorAuthentication::CHALLENGE_DELIVERY_CELL); + session()->remove(TwoFactorAuthentication::DELIVERY_STEP_UP); + session()->remove(TwoFactorAuthentication::PENDING_AUTHENTICATOR_SECRET); // Notify to listeners (package-auth, security logger) $eventResult = event(new Logout(Auth::user())); diff --git a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php index 266d40faa5..4e7883941f 100644 --- a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php +++ b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php @@ -40,15 +40,16 @@ public function displayTwoFactorAuthForm(Request $request) return redirect()->route('login'); } - // Send code - if (!session()->has(self::TFA_ERROR) && !session()->has(self::TFA_MESSAGE)) { - $this->twoFactorAuthentication->sendCode($user); - } else { - if (!session()->has(self::TFA_MESSAGE)) { - $this->twoFactorAuthentication->sendCode($user); - } + // Reload DB state without User::refresh() (clears permission caches). + $user = $user->fresh() ?? $user; + $this->twoFactorAuthentication->rememberChallengeMethodsSnapshot($user); + if ($this->shouldRedirectToAuthenticatorQrEnrollment($user)) { + return redirect()->route('2fa.auth_app_qr'); } + // Send code + $this->sendTwoFactorCodeForDisplay($user); + // Set informative message $methodsNames = $this->twoFactorAuthentication->friendlyMethodsNames($user); $message = __('Enter the security code from :methods. If incorrect, please retry with the latest code provided.', @@ -82,6 +83,8 @@ public function validateTwoFactorAuthCode(Request $request) return redirect()->route('2fa'); } + $this->twoFactorAuthentication->rememberChallengeMethodsSnapshot($user); + // Validate code $validated = $this->twoFactorAuthentication->validateCode($user, $code); @@ -94,8 +97,11 @@ public function validateTwoFactorAuthCode(Request $request) session()->remove(self::TFA_ERROR); session()->remove(self::TFA_AUTH_APP); - // Success + $user = $user->fresh() ?? $user; $route = 'login'; + if (strlen($code) !== 6 && $this->twoFactorAuthentication->mayEnrollNewAuthenticator($user)) { + $route = '2fa.auth_app_qr'; + } } else { // Set error message session()->put(self::TFA_ERROR, __('Invalid code.')); @@ -129,10 +135,20 @@ public function displayAuthAppQr(Request $request) $user = $request->user(); // If not user not authenticated, redirect to login page - if (empty($user)) { + if (empty($user) || !config('password-policies.2fa_enabled', false)) { return redirect()->route('login'); } + $user = $user->fresh() ?? $user; + $this->twoFactorAuthentication->rememberChallengeMethodsSnapshot($user); + $methods = $user->getValid2FAPreferences(); + + if (!in_array(TwoFactorAuthentication::AUTH_APP, $methods, true) + || !$this->twoFactorAuthentication->mayEnrollNewAuthenticator($user) + ) { + return redirect()->route('2fa'); + } + // Generate QR code $qrCode = $this->twoFactorAuthentication->generateQr($user); @@ -140,6 +156,41 @@ public function displayAuthAppQr(Request $request) return view('auth.2fa.auth_app_qr', compact('qrCode')); } + private function shouldRedirectToAuthenticatorQrEnrollment(User $user): bool + { + if (!empty($user->two_factor_secret)) { + return false; + } + + if (session()->has(TwoFactorAuthentication::PENDING_AUTHENTICATOR_SECRET)) { + return false; + } + + $methods = $user->getValid2FAPreferences(); + + return in_array(TwoFactorAuthentication::AUTH_APP, $methods, true) + && !$this->twoFactorAuthentication->challengeRequiresDeliveryStepUp(); + } + + private function sendTwoFactorCodeForDisplay(User $user): void + { + if (!session()->has(self::TFA_ERROR) && !session()->has(self::TFA_MESSAGE)) { + $this->twoFactorAuthentication->sendCode($user); + + return; + } + + $methods = $user->getValid2FAPreferences(); + $needsProvisioning = in_array(TwoFactorAuthentication::EMAIL, $methods, true) + || in_array(TwoFactorAuthentication::SMS, $methods, true) + ? empty($user->two_factor_delivery_secret) + : empty($user->two_factor_secret); + + if (!session()->has(self::TFA_MESSAGE) || $needsProvisioning) { + $this->twoFactorAuthentication->sendCode($user); + } + } + public function testSettings(Request $request) { $enabled = $request->json('enabled'); diff --git a/ProcessMaker/Models/User.php b/ProcessMaker/Models/User.php index f2fdcb8b83..2008d7ccaa 100644 --- a/ProcessMaker/Models/User.php +++ b/ProcessMaker/Models/User.php @@ -144,6 +144,8 @@ class User extends Authenticatable implements HasMedia 'loggedin_at' => 'datetime', 'schedule' => 'array', 'preferences_2fa' => 'array', + 'two_factor_secret' => 'encrypted', + 'two_factor_delivery_secret' => 'encrypted', ]; /** @@ -239,6 +241,8 @@ public static function passwordRules(self $existing = null) */ protected $hidden = [ 'password', + 'two_factor_secret', + 'two_factor_delivery_secret', 'groupMembersFromMemberable', 'permissions', ]; diff --git a/ProcessMaker/TwoFactorAuthentication.php b/ProcessMaker/TwoFactorAuthentication.php index 4fe8f04807..d5841bdd4d 100644 --- a/ProcessMaker/TwoFactorAuthentication.php +++ b/ProcessMaker/TwoFactorAuthentication.php @@ -8,7 +8,6 @@ use BaconQrCode\Writer; use Illuminate\Support\Facades\Notification; use OTPHP\TOTP; -use ParagonIE\ConstantTime\Base32; use ProcessMaker\Models\User; use ProcessMaker\Notifications\TwoFactorAuthNotification; use Twilio\Exceptions\TwilioException; @@ -24,10 +23,21 @@ class TwoFactorAuthentication const ERROR_INVALID_TO_NUMBER = 21211; + public const PENDING_AUTHENTICATOR_SECRET = '2fa-pending-authenticator-secret'; + + public const DELIVERY_STEP_UP = '2fa-delivery-step-up'; + + public const CHALLENGE_METHODS_SNAPSHOT = '2fa-challenge-methods'; + + public const CHALLENGE_DELIVERY_EMAIL = '2fa-challenge-delivery-email'; + + public const CHALLENGE_DELIVERY_CELL = '2fa-challenge-delivery-cell'; + public function sendCode(User $user): void { // Get methods to send the code $methods = $user->getValid2FAPreferences(); + $deliveryUser = $this->userForDeliveryChallenge($user); if (in_array(self::EMAIL, $methods) || in_array(self::SMS, $methods)) { // Get code @@ -35,30 +45,104 @@ public function sendCode(User $user): void // Send OTP if (in_array(self::EMAIL, $methods)) { - Notification::send($user, new TwoFactorAuthNotification($user, $code)); + Notification::send($deliveryUser, new TwoFactorAuthNotification($deliveryUser, $code)); } if (in_array(self::SMS, $methods)) { - $this->sendSms($user, $code); + $this->sendSms($deliveryUser, $code); } } elseif (in_array(self::AUTH_APP, $methods)) { session()->put('2fa-auth-app', true); } } - private function generateSecret(User $user): string + private function getUserDeliveryTotpSecret(User $user): string { - $base = $user->uuid . '_' . $user->username; + if (!empty($user->two_factor_delivery_secret)) { + return $user->two_factor_delivery_secret; + } + + $secret = TOTP::generate()->getSecret(); + + if ($user->exists) { + $user->two_factor_delivery_secret = $secret; + $user->saveQuietly(); + } else { + $user->setAttribute('two_factor_delivery_secret', $secret); + } - return trim(Base32::encodeUpper($base), '='); + return $secret; } - private function createOtpInstance(User $user, bool $forGoogleAuthApp = false) + private function resolveAuthenticatorSecret(User $user): ?string { - // Get secret - $secret = $this->generateSecret($user); + if (!empty($user->two_factor_secret)) { + return $user->two_factor_secret; + } - // Config OTP - $otp = TOTP::createFromSecret($secret); + $pending = session()->get(self::PENDING_AUTHENTICATOR_SECRET); + + return !empty($pending) ? $pending : null; + } + + public function rememberChallengeMethodsSnapshot(User $user): void + { + if (session()->has(self::CHALLENGE_METHODS_SNAPSHOT)) { + return; + } + + session()->put( + self::CHALLENGE_METHODS_SNAPSHOT, + $user->getValid2FAPreferences() + ); + session()->put(self::CHALLENGE_DELIVERY_EMAIL, $user->email); + session()->put(self::CHALLENGE_DELIVERY_CELL, $user->cell); + } + + private function userForDeliveryChallenge(User $user): User + { + $email = session()->get(self::CHALLENGE_DELIVERY_EMAIL); + $cell = session()->get(self::CHALLENGE_DELIVERY_CELL); + if ($email === null && $cell === null) { + return $user; + } + + $deliveryUser = $user->replicate(); + $deliveryUser->exists = true; + $deliveryUser->id = $user->id; + if ($email !== null) { + $deliveryUser->email = $email; + } + if ($cell !== null) { + $deliveryUser->cell = $cell; + } + + return $deliveryUser; + } + + public function challengeRequiresDeliveryStepUp(): bool + { + $methods = session()->get(self::CHALLENGE_METHODS_SNAPSHOT, []); + + return in_array(self::EMAIL, $methods, true) + || in_array(self::SMS, $methods, true); + } + + public function mayEnrollNewAuthenticator(User $user): bool + { + $methods = $user->getValid2FAPreferences(); + if (!empty($user->two_factor_secret) || !in_array(self::AUTH_APP, $methods, true)) { + return false; + } + + if (!$this->challengeRequiresDeliveryStepUp()) { + return true; + } + + return session()->get(self::DELIVERY_STEP_UP, false); + } + + private function configureOtp(TOTP $otp, User $user, bool $forGoogleAuthApp): TOTP + { $otp->setIssuer('ProcessMaker'); $otp->setLabel($user->username); @@ -71,6 +155,16 @@ private function createOtpInstance(User $user, bool $forGoogleAuthApp = false) return $otp; } + private function createOtpInstance(User $user, bool $forGoogleAuthApp = false) + { + $secret = $forGoogleAuthApp + ? $this->resolveAuthenticatorSecret($user) + : $this->getUserDeliveryTotpSecret($user); + + // Config OTP + return $this->configureOtp(TOTP::createFromSecret($secret), $user, $forGoogleAuthApp); + } + private function getCodeForEmailSms(User $user): string { // Create OTP instance @@ -82,14 +176,48 @@ private function getCodeForEmailSms(User $user): string public function validateCode(User $user, string $code) { - // The code is for Google Authenticator app? - $forGoogleAuthApp = strlen($code) === 6; + $methods = $user->getValid2FAPreferences(); - // Create OTP instance - $otp = $this->createOtpInstance($user, $forGoogleAuthApp); + if (strlen($code) === 6) { + return $this->verifyAuthenticatorCode($user, $code, $methods); + } - // Validate code - return $otp->verify($code); + if (!$this->hasDeliveryMethod($methods) || empty($user->two_factor_delivery_secret)) { + return false; + } + + $otp = $this->createOtpInstance($user, false); + $valid = $otp->verify($code); + if ($valid) { + session()->put(self::DELIVERY_STEP_UP, true); + } + + return $valid; + } + + private function verifyAuthenticatorCode(User $user, string $code, array $methods): bool + { + $authSecret = $this->resolveAuthenticatorSecret($user); + $cannotUseAuthenticator = !in_array(self::AUTH_APP, $methods, true) || $authSecret === null; + $cannotEnroll = empty($user->two_factor_secret) && !$this->mayEnrollNewAuthenticator($user); + if ($cannotUseAuthenticator || $cannotEnroll) { + return false; + } + + $otp = $this->createOtpInstance($user, true); + $valid = $otp->verify($code); + if ($valid && empty($user->two_factor_secret)) { + $user->two_factor_secret = $authSecret; + $user->saveQuietly(); + session()->forget(self::PENDING_AUTHENTICATOR_SECRET); + } + + return $valid; + } + + private function hasDeliveryMethod(array $methods): bool + { + return in_array(self::EMAIL, $methods, true) || in_array(self::SMS, $methods, true); } /** @@ -154,7 +282,13 @@ private function sendSms(User $user, string $code) public function generateQr(User $user) { - $otp = $this->createOtpInstance($user, true); + $secret = session()->get(self::PENDING_AUTHENTICATOR_SECRET); + if (empty($secret)) { + $secret = TOTP::generate()->getSecret(); + session()->put(self::PENDING_AUTHENTICATOR_SECRET, $secret); + } + + $otp = $this->configureOtp(TOTP::createFromSecret($secret), $user, true); $g2faUrl = $otp->getProvisioningUri(); diff --git a/database/migrations/2026_11_09_120000_add_two_factor_secret_to_users_table.php b/database/migrations/2026_11_09_120000_add_two_factor_secret_to_users_table.php new file mode 100644 index 0000000000..87ef9ce8cf --- /dev/null +++ b/database/migrations/2026_11_09_120000_add_two_factor_secret_to_users_table.php @@ -0,0 +1,28 @@ +text('two_factor_secret')->nullable()->after('preferences_2fa'); + $table->text('two_factor_delivery_secret')->nullable()->after('two_factor_secret'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('users', function (Blueprint $table) { + $table->dropColumn(['two_factor_secret', 'two_factor_delivery_secret']); + }); + } +}; diff --git a/resources/views/auth/2fa/auth_app_qr.blade.php b/resources/views/auth/2fa/auth_app_qr.blade.php index 8e047304ed..da71c9f7b1 100644 --- a/resources/views/auth/2fa/auth_app_qr.blade.php +++ b/resources/views/auth/2fa/auth_app_qr.blade.php @@ -1,75 +1,42 @@ - - - - - - - - - - {{ __('Configure the authenticator app') }} - @vite('resources/sass/app.scss') - - - -
-
-
-
-
- @php - $isMobile = ( - isset($_SERVER['HTTP_USER_AGENT']) - && \ProcessMaker\Helpers\MobileHelper::isMobile($_SERVER['HTTP_USER_AGENT']) - ) ? true : false; - @endphp - @if (!$isMobile) -
- ProcessMaker - -
- @endif -
-
-
-
- @component('components.logo') - @endcomponent -

-

-
- {{__('Configure the authenticator app')}} -
-
- {{__('1.- Download the Google Authenticator App')}} -
-
- {{__('2.- On the Google Authenticator app click on the + icon')}} -
-
- {{__('3.- Select "Scan QR code" option')}} -
-
- QR -
- -
- -
-
-
-
-
+@extends('auth.layouts.auth') + +@section('skip-language-selector', 'skip') +@section('skip-auth-language-scripts', 'skip') + +@section('title') +{{ __('Configure the authenticator app') }} +@endsection + +@section('content') +
+
+ {{__('Configure the authenticator app')}}
+
+ {{__('1.- Download the Google Authenticator App')}} +
+
+ {{__('2.- On the Google Authenticator app click on the + icon')}} +
+
+ {{__('3.- Select "Scan QR code" option')}} +
+
+QR + +
+
- +@endsection + +@push('scripts') - - +@endpush diff --git a/resources/views/auth/2fa/otp.blade.php b/resources/views/auth/2fa/otp.blade.php index aba8a68b26..515c86fe47 100644 --- a/resources/views/auth/2fa/otp.blade.php +++ b/resources/views/auth/2fa/otp.blade.php @@ -1,105 +1,87 @@ - - - - - - - - - - {{ __('Enter Security Code') }} - @vite('resources/sass/app.scss') - - - -
-
-
-
-
- @php - $isMobile = ( - isset($_SERVER['HTTP_USER_AGENT']) - && \ProcessMaker\Helpers\MobileHelper::isMobile($_SERVER['HTTP_USER_AGENT']) - ) ? true : false; - @endphp - @if (!$isMobile) -
- ProcessMaker - -
- @endif -
-
-
-
- @component('components.logo') - @endcomponent -
-
- @if (session()->has('2fa-message') && !session()->has('2fa-error')) -
{{ session()->get('2fa-message')}}
- @endif - @if (session()->has('2fa-error')) -
{{ session()->get('2fa-error')}}
- @endif +@extends('auth.layouts.auth') -
- -
- - - @if ($errors->has('code')) - - {{ $errors->first('code') }} - - @endif -
-
-
- -
- @if (in_array(\ProcessMaker\TwoFactorAuthentication::AUTH_APP, - config('password-policies.2fa_method', []))) - - {{ __('Authenticator app') }} - -
- @endif - - {{ __('Log in as another user') }} - -
-
-
- -
-
-
-
-
+@section('skip-language-selector', 'skip') +@section('skip-auth-language-scripts', 'skip') + +@section('title') +{{ __('Enter Security Code') }} +@endsection + +@section('css') + +@endsection + +@section('content') +
+ @if (session()->has('2fa-message') && !session()->has('2fa-error')) +
{{ session()->get('2fa-message')}}
+ @endif + @if (session()->has('2fa-error')) +
{{ session()->get('2fa-error')}}
+ @endif + +
+ +
+ + + @if ($errors->has('code')) + + {{ $errors->first('code') }} + + @endif +
+
+
+ +
+ @if (app(\ProcessMaker\TwoFactorAuthentication::class)->mayEnrollNewAuthenticator(auth()->user())) + + {{ __('Authenticator app') }} + +
+ @endif + + {{ __('Log in as another user') }} +
-
- +
+ +
+ +@endsection + +@push('scripts') - - +@endpush diff --git a/tests/Feature/Auth/TwoFactorPredictableSecretTest.php b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php new file mode 100644 index 0000000000..5834f95fee --- /dev/null +++ b/tests/Feature/Auth/TwoFactorPredictableSecretTest.php @@ -0,0 +1,459 @@ + true, + 'password-policies.2fa_method' => [TwoFactorAuthentication::AUTH_APP], + ]); + } + + private function codeFromPublicIdentity(string $uuid, string $username, string $mode = 'app'): string + { + $secret = trim(Base32::encodeUpper($uuid . '_' . $username), '='); + $otp = TOTP::createFromSecret($secret); + + if ($mode === 'email') { + $otp->setDigest('sha512'); + $otp->setDigits(8); + $otp->setPeriod(300); + } + + return $otp->now(); + } + + private function victimAtTwoFactorGate(): User + { + return User::factory()->create([ + 'password' => Hash::make('password'), + 'preferences_2fa' => [TwoFactorAuthentication::AUTH_APP], + ]); + } + + private function postTwoFactorCode(User $sessionUser, string $code) + { + return $this->actingAs($sessionUser, 'web') + ->post(route('2fa.validate'), ['code' => $code]); + } + + public function testProtectedRouteRedirectsToTwoFactorUntilValidated(): void + { + $victim = $this->victimAtTwoFactorGate(); + + $this->actingAs($victim, 'web') + ->get(route('about.index')) + ->assertRedirect(route('2fa')); + } + + public function testWrongCodeDoesNotClearTwoFactorGate(): void + { + $victim = $this->victimAtTwoFactorGate(); + + $this->postTwoFactorCode($victim, '000000') + ->assertRedirect(route('2fa')); + + $this->assertNotTrue(session()->get(TwoFactorAuthController::TFA_VALIDATED)); + + $this->actingAs($victim, 'web') + ->get(route('about.index')) + ->assertRedirect(route('2fa')); + } + + public function testCodeDerivedFromAnotherUsersPublicIdentityDoesNotValidateVictimSession(): void + { + $victim = $this->victimAtTwoFactorGate(); + $attacker = User::factory()->create(); + + $codeForAttacker = $this->codeFromPublicIdentity($attacker->uuid, $attacker->username); + + $this->postTwoFactorCode($victim, $codeForAttacker) + ->assertRedirect(route('2fa')); + + $this->assertNotTrue(session()->get(TwoFactorAuthController::TFA_VALIDATED)); + } + + public function testVictimSessionRejectsCodeComputedFromPublicUuidAndUsernameOnly(): void + { + $victim = $this->victimAtTwoFactorGate(); + $attacker = User::factory()->create(); + + $harvested = User::query() + ->whereKey($victim->id) + ->first(['uuid', 'username']); + + $this->assertNotSame($attacker->uuid, $harvested->uuid); + + $code = $this->codeFromPublicIdentity($harvested->uuid, $harvested->username); + + $this->postTwoFactorCode($victim, $code) + ->assertRedirect(route('2fa')); + + $this->assertNotTrue(session()->get(TwoFactorAuthController::TFA_VALIDATED)); + + $this->actingAs($victim, 'web') + ->get(route('about.index')) + ->assertRedirect(route('2fa')); + } + + public function testVictimSessionRejectsEightDigitEmailModeCodeFromPublicIdentity(): void + { + config([ + 'password-policies.2fa_method' => [TwoFactorAuthentication::EMAIL], + ]); + + $victim = User::factory()->create([ + 'password' => Hash::make('password'), + 'preferences_2fa' => [TwoFactorAuthentication::EMAIL], + ]); + + $code = $this->codeFromPublicIdentity($victim->uuid, $victim->username, 'email'); + + $this->postTwoFactorCode($victim, $code) + ->assertRedirect(route('2fa')); + + $this->assertNotTrue(session()->get(TwoFactorAuthController::TFA_VALIDATED)); + } + + public function testLegacyUserProvisioningWhenSecretIsMissing(): void + { + Notification::fake(); + + $authOnly = User::factory()->create([ + 'password' => Hash::make('password'), + 'preferences_2fa' => [TwoFactorAuthentication::AUTH_APP], + 'two_factor_secret' => null, + ]); + $this->actingAs($authOnly, 'web') + ->get(route('2fa')) + ->assertRedirect(route('2fa.auth_app_qr')); + + $this->actingAs($authOnly, 'web') + ->get(route('2fa.auth_app_qr')) + ->assertOk(); + + $this->assertEmpty($authOnly->fresh()->two_factor_secret); + $this->assertNotEmpty(session(TwoFactorAuthentication::PENDING_AUTHENTICATOR_SECRET)); + + $this->actingAs($authOnly, 'web') + ->get(route('2fa')) + ->assertOk() + ->assertViewIs('auth.2fa.otp'); + + config(['password-policies.2fa_method' => [TwoFactorAuthentication::EMAIL]]); + $emailUser = User::factory()->create([ + 'password' => Hash::make('password'), + 'preferences_2fa' => [TwoFactorAuthentication::EMAIL], + 'two_factor_secret' => null, + ]); + $this->actingAs($emailUser, 'web')->get(route('2fa'))->assertOk(); + + Notification::assertSentTo($emailUser, TwoFactorAuthNotification::class); + $emailUser->refresh(); + $this->assertNotEmpty($emailUser->two_factor_delivery_secret); + $this->assertEmpty($emailUser->two_factor_secret); + } + + public function testAuthAppQrRouteRequiresAuthenticatorEnrollment(): void + { + config(['password-policies.2fa_method' => [TwoFactorAuthentication::EMAIL]]); + + $emailUser = User::factory()->create([ + 'password' => Hash::make('password'), + 'preferences_2fa' => [TwoFactorAuthentication::EMAIL], + ]); + + $this->actingAs($emailUser, 'web') + ->get(route('2fa.auth_app_qr')) + ->assertRedirect(route('2fa')); + + $secret = TOTP::generate()->getSecret(); + $authUser = User::factory()->create([ + 'password' => Hash::make('password'), + 'preferences_2fa' => [TwoFactorAuthentication::AUTH_APP], + 'two_factor_secret' => $secret, + ]); + + config(['password-policies.2fa_method' => [TwoFactorAuthentication::AUTH_APP]]); + + $this->actingAs($authUser, 'web') + ->get(route('2fa.auth_app_qr')) + ->assertRedirect(route('2fa')); + } + + /** + * Stateless auth:api must not narrow preferences_2fa before the same principal + * completes web 2FA (blocks Bearer PUT bypass of delivery step-up). + */ + public function testStatelessApiCannotUpdatePreferences2faBeforeWebTwoFactorValidated(): void + { + config([ + 'password-policies.2fa_method' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + ]); + + $user = User::factory()->create([ + 'is_administrator' => true, + 'preferences_2fa' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + 'two_factor_secret' => null, + ]); + + $payload = [ + 'username' => $user->username, + 'firstname' => $user->firstname, + 'lastname' => $user->lastname, + 'email' => $user->email, + 'status' => $user->status, + 'preferences_2fa' => [TwoFactorAuthentication::AUTH_APP], + ]; + + $this->actingAs($user, 'api') + ->putJson('/api/1.0/users/' . $user->id, $payload) + ->assertStatus(422) + ->assertJsonPath( + 'message', + __('Two-factor authentication must be completed before updating 2FA preferences.') + ); + + $freshPreferences = $user->fresh()->preferences_2fa; + $this->assertContains(TwoFactorAuthentication::EMAIL, $freshPreferences); + $this->assertContains(TwoFactorAuthentication::AUTH_APP, $freshPreferences); + } + + public function testStatelessApiCannotChangeEmailBeforeWebTwoFactorValidated(): void + { + config([ + 'password-policies.2fa_method' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + ]); + + $user = User::factory()->create([ + 'is_administrator' => true, + 'password' => Hash::make('password'), + 'preferences_2fa' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + 'two_factor_secret' => null, + ]); + + $payload = [ + 'username' => $user->username, + 'firstname' => $user->firstname, + 'lastname' => $user->lastname, + 'email' => 'attacker-' . $user->email, + 'status' => $user->status, + 'valpassword' => 'password', + ]; + + $this->actingAs($user, 'api') + ->putJson('/api/1.0/users/' . $user->id, $payload) + ->assertStatus(422) + ->assertJsonPath( + 'message', + __('Two-factor authentication must be completed before updating 2FA preferences.') + ); + + $this->assertSame($user->email, $user->fresh()->email); + } + + public function testCannotBypassDeliveryWithPendingAuthenticatorEnrollment(): void + { + config([ + 'password-policies.2fa_method' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + ]); + + $user = User::factory()->create([ + 'password' => Hash::make('password'), + 'preferences_2fa' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + 'two_factor_secret' => null, + ]); + + session()->put(TwoFactorAuthentication::CHALLENGE_METHODS_SNAPSHOT, [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ]); + + $pendingSecret = TOTP::generate()->getSecret(); + session()->put(TwoFactorAuthentication::PENDING_AUTHENTICATOR_SECRET, $pendingSecret); + + $this->actingAs($user, 'web') + ->get(route('2fa.auth_app_qr')) + ->assertRedirect(route('2fa')); + + $this->postTwoFactorCode($user, TOTP::createFromSecret($pendingSecret)->now()) + ->assertRedirect(route('2fa')); + + $this->assertNotTrue(session()->get(TwoFactorAuthController::TFA_VALIDATED)); + $this->assertEmpty($user->fresh()->two_factor_secret); + } + + /** + * Enrollment still requires delivery when the login snapshot includes it, even if + * stored preferences were narrowed outside the API (historical bypass shape). + */ + public function testNarrowedPreferencesCannotSkipDeliveryStepUpWhenPolicyRequiresIt(): void + { + Notification::fake(); + + config([ + 'password-policies.2fa_method' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + ]); + + $user = User::factory()->create([ + 'password' => Hash::make('password'), + 'preferences_2fa' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + 'two_factor_secret' => null, + ]); + + session()->put(TwoFactorAuthentication::CHALLENGE_METHODS_SNAPSHOT, [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ]); + + // Simulates narrowed prefs without going through UserController (not the API guard). + $user->preferences_2fa = [TwoFactorAuthentication::AUTH_APP]; + $user->saveQuietly(); + + $pendingSecret = TOTP::generate()->getSecret(); + session()->put(TwoFactorAuthentication::PENDING_AUTHENTICATOR_SECRET, $pendingSecret); + + $this->actingAs($user, 'web') + ->get(route('2fa.auth_app_qr')) + ->assertRedirect(route('2fa')); + + $this->postTwoFactorCode($user, TOTP::createFromSecret($pendingSecret)->now()) + ->assertRedirect(route('2fa')); + + $this->assertNotTrue(session()->get(TwoFactorAuthController::TFA_VALIDATED)); + $this->assertEmpty($user->fresh()->two_factor_secret); + } + + public function testMixedMethodsRedirectToQrAfterDeliveryCode(): void + { + config([ + 'password-policies.2fa_method' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + ]); + + $deliverySecret = TOTP::generate()->getSecret(); + $user = User::factory()->create([ + 'password' => Hash::make('password'), + 'preferences_2fa' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + 'two_factor_secret' => null, + 'two_factor_delivery_secret' => $deliverySecret, + ]); + + $emailOtp = TOTP::createFromSecret($deliverySecret); + $emailOtp->setDigest('sha512'); + $emailOtp->setDigits(8); + $emailOtp->setPeriod(300); + + $this->actingAs($user, 'web') + ->post(route('2fa.validate'), ['code' => $emailOtp->now()]) + ->assertRedirect(route('2fa.auth_app_qr')); + + $this->assertTrue(session()->get(TwoFactorAuthController::TFA_VALIDATED)); + $this->assertTrue(session()->get(TwoFactorAuthentication::DELIVERY_STEP_UP)); + } + + public function testMixedMethodsAllowAuthenticatorEnrollmentAfterDeliveryStepUp(): void + { + config([ + 'password-policies.2fa_method' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + ]); + + $deliverySecret = TOTP::generate()->getSecret(); + $user = User::factory()->create([ + 'password' => Hash::make('password'), + 'preferences_2fa' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + 'two_factor_secret' => null, + 'two_factor_delivery_secret' => $deliverySecret, + ]); + + session()->put(TwoFactorAuthentication::DELIVERY_STEP_UP, true); + $pendingSecret = TOTP::generate()->getSecret(); + session()->put(TwoFactorAuthentication::PENDING_AUTHENTICATOR_SECRET, $pendingSecret); + + $this->actingAs($user, 'web') + ->get(route('2fa.auth_app_qr')) + ->assertOk(); + + $this->postTwoFactorCode($user, TOTP::createFromSecret($pendingSecret)->now()) + ->assertRedirect(route('login')); + + $this->assertTrue(session()->get(TwoFactorAuthController::TFA_VALIDATED)); + $this->assertSame($pendingSecret, $user->fresh()->two_factor_secret); + } + + public function testVictimSessionAcceptsCodeFromStoredSecret(): void + { + $secret = TOTP::generate()->getSecret(); + $victim = User::factory()->create([ + 'password' => Hash::make('password'), + 'preferences_2fa' => [TwoFactorAuthentication::AUTH_APP], + 'two_factor_secret' => $secret, + ]); + + $code = TOTP::createFromSecret($secret)->now(); + + $this->postTwoFactorCode($victim, $code) + ->assertRedirect(route('login')); + + $this->assertTrue(session()->get(TwoFactorAuthController::TFA_VALIDATED)); + + $this->actingAs($victim, 'web') + ->get(route('about.index')) + ->assertOk(); + } +} diff --git a/tests/unit/ProcessMaker/TwoFactorAuthenticationTest.php b/tests/unit/ProcessMaker/TwoFactorAuthenticationTest.php new file mode 100644 index 0000000000..4bd8e3f272 --- /dev/null +++ b/tests/unit/ProcessMaker/TwoFactorAuthenticationTest.php @@ -0,0 +1,157 @@ +getMethod('getUserDeliveryTotpSecret'); + $method->setAccessible(true); + + return $method->invoke(new TwoFactorAuthentication(), $user); + } + + private function codeFromPublicIdentity(string $uuid, string $username, bool $emailMode = false): string + { + $secret = trim(Base32::encodeUpper($uuid . '_' . $username), '='); + $otp = TOTP::createFromSecret($secret); + + if ($emailMode) { + $otp->setDigest('sha512'); + $otp->setDigits(8); + $otp->setPeriod(300); + } + + return $otp->now(); + } + + public function testUserTotpSecretIsNotDerivedFromUuidAndUsername(): void + { + $user = User::factory()->create([ + 'uuid' => self::UUID, + 'username' => self::USERNAME, + ]); + + $secret = TOTP::generate()->getSecret(); + $user->two_factor_secret = $secret; + $user->saveQuietly(); + + $predictable = trim(Base32::encodeUpper(self::UUID . '_' . self::USERNAME), '='); + + $this->assertNotSame($predictable, $secret); + + $user->refresh(); + $this->assertSame($secret, $user->two_factor_secret); + } + + public function testUserDeliveryTotpSecretIsNotDerivedFromUuidAndUsername(): void + { + $user = User::factory()->create([ + 'uuid' => self::UUID, + 'username' => self::USERNAME, + ]); + + $secret = $this->invokeGetUserDeliveryTotpSecret($user); + $predictable = trim(Base32::encodeUpper(self::UUID . '_' . self::USERNAME), '='); + + $this->assertNotSame($predictable, $secret); + + $user->refresh(); + $this->assertSame($secret, $user->two_factor_delivery_secret); + $this->assertEmpty($user->two_factor_secret); + } + + public function testValidateCodeRejectsCodeDerivedFromPublicIdentityOnly(): void + { + $user = User::factory()->create([ + 'uuid' => self::UUID, + 'username' => self::USERNAME, + 'preferences_2fa' => [TwoFactorAuthentication::EMAIL], + ]); + + $this->invokeGetUserDeliveryTotpSecret($user); + + $service = new TwoFactorAuthentication(); + $this->assertFalse( + $service->validateCode($user, $this->codeFromPublicIdentity(self::UUID, self::USERNAME)) + ); + $this->assertFalse( + $service->validateCode($user, $this->codeFromPublicIdentity(self::UUID, self::USERNAME, true)) + ); + } + + public function testValidateCodeAcceptsCodeFromStoredSecrets(): void + { + config([ + 'password-policies.2fa_method' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + ]); + + $authSecret = TOTP::generate()->getSecret(); + $deliverySecret = TOTP::generate()->getSecret(); + $user = User::factory()->create([ + 'preferences_2fa' => [ + TwoFactorAuthentication::AUTH_APP, + TwoFactorAuthentication::EMAIL, + ], + 'two_factor_secret' => $authSecret, + 'two_factor_delivery_secret' => $deliverySecret, + ]); + + $service = new TwoFactorAuthentication(); + + $appCode = TOTP::createFromSecret($authSecret)->now(); + $this->assertTrue($service->validateCode($user, $appCode)); + + $emailOtp = TOTP::createFromSecret($deliverySecret); + $emailOtp->setDigest('sha512'); + $emailOtp->setDigits(8); + $emailOtp->setPeriod(300); + $this->assertTrue($service->validateCode($user, $emailOtp->now())); + } + + public function testValidateCodeRejectsSixDigitForEmailOnlyUser(): void + { + config(['password-policies.2fa_method' => [TwoFactorAuthentication::EMAIL]]); + + $deliverySecret = TOTP::generate()->getSecret(); + $authSecret = TOTP::generate()->getSecret(); + $user = User::factory()->create([ + 'preferences_2fa' => [TwoFactorAuthentication::EMAIL], + 'two_factor_secret' => $authSecret, + 'two_factor_delivery_secret' => $deliverySecret, + ]); + + $sixDigitFromAuthSecret = TOTP::createFromSecret($authSecret)->now(); + $this->assertFalse((new TwoFactorAuthentication())->validateCode($user, $sixDigitFromAuthSecret)); + } + + public function testValidateCodeRejectsRandomCode(): void + { + $user = User::factory()->create([ + 'preferences_2fa' => [TwoFactorAuthentication::EMAIL], + ]); + + $this->assertFalse((new TwoFactorAuthentication())->validateCode($user, '000000')); + } +}