diff --git a/ProcessMaker/Http/Controllers/Api/UserController.php b/ProcessMaker/Http/Controllers/Api/UserController.php index ee2acfa837..6cc5babeb8 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,174 @@ 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; + } + + $twoFa = new TwoFactorAuthentication(); + if (!$twoFa->selfServiceUpdateRequiresTwoFactorCompletion($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 ($this->preferences2faChanged($fields, $original)) { + 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 preferences2faChanged(array $fields, array $original): bool + { + if (!array_key_exists('preferences_2fa', $fields)) { + return false; + } + + $normalize = static function ($value): array { + $items = is_array($value) ? $value : []; + + sort($items); + + return array_values($items); + }; + + return $normalize($fields['preferences_2fa'] ?? null) + !== $normalize($original['preferences_2fa'] ?? null); + } + + 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..28804066d6 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,13 @@ 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::CHALLENGE_DELIVERY_USER_ID); + session()->remove(TwoFactorAuthentication::DELIVERY_STEP_UP); + session()->remove(TwoFactorAuthentication::PENDING_AUTHENTICATOR_SECRET); + session()->remove(TwoFactorAuthentication::PENDING_AUTHENTICATOR_USER_ID); // 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..97682f0bf7 100644 --- a/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php +++ b/ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php @@ -29,36 +29,42 @@ public function __construct() $this->twoFactorAuthentication = new TwoFactorAuthentication(); } + private function reloadUser(?User $user): ?User + { + return $user?->fresh() ?? $user; + } + public function displayTwoFactorAuthForm(Request $request) { try { - // Get current user - $user = $request->user(); + $user = $this->reloadUser($request->user()); - // If not user not authenticated, redirect to login page if (empty($user) || !config('password-policies.2fa_enabled', false)) { 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); - } + $this->twoFactorAuthentication->rememberChallengeMethodsSnapshot($user); + if ($this->twoFactorAuthentication->shouldShowQrForFirstTime($user)) { + return redirect()->route('2fa.auth_app_qr'); } - // Set informative message - $methodsNames = $this->twoFactorAuthentication->friendlyMethodsNames($user); - $message = __('Enter the security code from :methods. If incorrect, please retry with the latest code provided.', - ['methods' => $methodsNames]); - session()->put(self::TFA_MESSAGE, $message); + $this->sendTwoFactorCodeForDisplay($user); + + if ($this->twoFactorAuthentication->isInAuthenticatorEnrollmentPhase($user)) { + session()->put( + self::TFA_MESSAGE, + __('Enter the 6-digit code from your authenticator app.') + ); + } else { + $methodsNames = $this->twoFactorAuthentication->friendlyMethodsNames($user); + $message = __('Enter the security code from :methods. If incorrect, please retry with the latest code provided.', + ['methods' => $methodsNames]); + session()->put(self::TFA_MESSAGE, $message); + } } catch (Exception $error) { session()->put(self::TFA_ERROR, $error->getMessage()); } - // Display view return view('auth.2fa.otp'); } @@ -82,20 +88,34 @@ public function validateTwoFactorAuthCode(Request $request) return redirect()->route('2fa'); } - // Validate code + $this->twoFactorAuthentication->rememberChallengeMethodsSnapshot($user); + $validated = $this->twoFactorAuthentication->validateCode($user, $code); - // Store validation status - session()->put(self::TFA_VALIDATED, $validated); + session()->put( + self::TFA_VALIDATED, + $this->twoFactorAuthentication->clearsWebTwoFactorGate($user, $code, $validated) + ); if ($validated) { - // Remove 2fa values in session session()->remove(self::TFA_MESSAGE); session()->remove(self::TFA_ERROR); session()->remove(self::TFA_AUTH_APP); - // Success + $user = $this->reloadUser($user); $route = 'login'; + if (strlen($code) !== 6 && $this->twoFactorAuthentication->mayEnrollNewAuthenticator($user)) { + $route = $this->twoFactorAuthentication->sessionHasPendingAuthenticatorForUser($user) + ? '2fa' + : '2fa.auth_app_qr'; + + if ($route === '2fa') { + session()->put( + self::TFA_MESSAGE, + __('Enter the 6-digit code from your authenticator app.') + ); + } + } } else { // Set error message session()->put(self::TFA_ERROR, __('Invalid code.')); @@ -109,37 +129,66 @@ public function validateTwoFactorAuthCode(Request $request) public function sendCode(Request $request) { - // Get current user - $user = $request->user(); + $user = $this->reloadUser($request->user()); + + if ($this->twoFactorAuthentication->isInAuthenticatorEnrollmentPhase($user)) { + return redirect()->route('2fa'); + } - // Send the code try { $this->twoFactorAuthentication->sendCode($user); } catch (Exception $error) { session()->put(self::TFA_ERROR, $error->getMessage()); } - // Return to 2fa page return redirect()->route('2fa'); } public function displayAuthAppQr(Request $request) { - // Get current user - $user = $request->user(); + $user = $this->reloadUser($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'); } - // Generate QR code + $this->twoFactorAuthentication->rememberChallengeMethodsSnapshot($user); + $methods = $this->twoFactorAuthentication->userPreferredMethods($user); + + if (!in_array(TwoFactorAuthentication::AUTH_APP, $methods, true) + || !$this->twoFactorAuthentication->mayEnrollNewAuthenticator($user) + ) { + return redirect()->route('2fa'); + } + $qrCode = $this->twoFactorAuthentication->generateQr($user); - // Display view return view('auth.2fa.auth_app_qr', compact('qrCode')); } + private function sendTwoFactorCodeForDisplay(User $user): void + { + if ($this->twoFactorAuthentication->isInAuthenticatorEnrollmentPhase($user)) { + return; + } + + if (!session()->has(self::TFA_ERROR) && !session()->has(self::TFA_MESSAGE)) { + $this->twoFactorAuthentication->sendCode($user); + + return; + } + + $methods = $this->twoFactorAuthentication->userPreferredMethods($user); + $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..33258c8934 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,27 @@ class TwoFactorAuthentication const ERROR_INVALID_TO_NUMBER = 21211; + public const PENDING_AUTHENTICATOR_SECRET = '2fa-pending-authenticator-secret'; + + public const PENDING_AUTHENTICATOR_USER_ID = '2fa-pending-authenticator-user-id'; + + public const DELIVERY_STEP_UP = '2fa-delivery-step-up'; + + public const CHALLENGE_METHODS_SNAPSHOT = '2fa-challenge-methods'; + + public const CHALLENGE_METHODS_USER_ID = '2fa-challenge-methods-user-id'; + + public const CHALLENGE_DELIVERY_EMAIL = '2fa-challenge-delivery-email'; + + public const CHALLENGE_DELIVERY_CELL = '2fa-challenge-delivery-cell'; + + public const CHALLENGE_DELIVERY_USER_ID = '2fa-challenge-delivery-user-id'; + 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 +51,211 @@ 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(); - return trim(Base32::encodeUpper($base), '='); + if ($user->exists) { + $user->two_factor_delivery_secret = $secret; + $user->saveQuietly(); + } else { + $user->setAttribute('two_factor_delivery_secret', $secret); + } + + 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); + if (!$this->sessionHasPendingAuthenticatorForUser($user)) { + return null; + } + + return session()->get(self::PENDING_AUTHENTICATOR_SECRET); + } + + public function sessionHasPendingAuthenticatorForUser(User $user): bool + { + // Check if there's a pending authenticator secret in session + // User ID validation is performed when generating the secret + return session()->has(self::PENDING_AUTHENTICATOR_SECRET); + } + + public function forgetPendingAuthenticatorEnrollment(): void + { + session()->forget(self::PENDING_AUTHENTICATOR_SECRET); + session()->forget(self::PENDING_AUTHENTICATOR_USER_ID); + } + + public function needsAuthenticatorEnrollment(User $user): bool + { + return empty($user->two_factor_secret) + && in_array(self::AUTH_APP, $this->challengeMethods($user), true); + } + + public function authenticatorEnrollmentRequiredForGate(User $user): bool + { + return $this->needsAuthenticatorEnrollment($user); + } + + public function isInAuthenticatorEnrollmentPhase(User $user): bool + { + if (!$this->needsAuthenticatorEnrollment($user)) { + return false; + } + + if ($this->sessionHasPendingAuthenticatorForUser($user)) { + return true; + } + + return $this->hasCompletedDeliveryStepUp() + && $this->mayEnrollNewAuthenticator($user); + } + + public function shouldShowQrForFirstTime(User $user): bool + { + if (!$this->needsAuthenticatorEnrollment($user)) { + return false; + } + + if ($this->sessionHasPendingAuthenticatorForUser($user)) { + return false; + } + + if (!$this->challengeRequiresDeliveryStepUp()) { + return true; + } + + return $this->hasCompletedDeliveryStepUp() + && $this->mayEnrollNewAuthenticator($user); + } + + public function clearsWebTwoFactorGate(User $user, string $code, bool $codeValid): bool + { + if (!$codeValid) { + return false; + } + + if (strlen($code) === 6) { + return true; + } + + return !$this->authenticatorEnrollmentRequiredForGate($user); + } + + public function challengeMethods(User $user): array + { + $snapshot = session()->get(self::CHALLENGE_METHODS_SNAPSHOT); + $snapshotUserId = session()->get(self::CHALLENGE_METHODS_USER_ID); + + // Use snapshot only if it exists, is valid, and belongs to this user + if (is_array($snapshot) && $snapshot !== []) { + if ($snapshotUserId === null || (int) $snapshotUserId === (int) $user->id) { + return $snapshot; + } + } + + return $user->getValid2FAPreferences(); + } + + public function userPreferredMethods(User $user): array + { + return $user->getValid2FAPreferences(); + } + + public function rememberChallengeMethodsSnapshot(User $user): void + { + // Check if snapshot exists AND belongs to this user + if (session()->exists(self::CHALLENGE_METHODS_SNAPSHOT)) { + $snapshotUserId = session()->get(self::CHALLENGE_METHODS_USER_ID); + if ($snapshotUserId === null || (int) $snapshotUserId === (int) $user->id) { + return; // Snapshot exists for this user + } + // Snapshot belongs to different user, clear it + $this->forgetChallengeSnapshot(); + } + + $methods = $user->getValid2FAPreferences(); + + session()->put(self::CHALLENGE_METHODS_SNAPSHOT, $methods); + session()->put(self::CHALLENGE_METHODS_USER_ID, $user->id); + session()->put(self::CHALLENGE_DELIVERY_EMAIL, $user->email); + session()->put(self::CHALLENGE_DELIVERY_CELL, $user->cell); + session()->put(self::CHALLENGE_DELIVERY_USER_ID, $user->id); + } + + private function userForDeliveryChallenge(User $user): User + { + $email = session()->get(self::CHALLENGE_DELIVERY_EMAIL); + $cell = session()->get(self::CHALLENGE_DELIVERY_CELL); + if (!session()->exists(self::CHALLENGE_DELIVERY_EMAIL) && !session()->exists(self::CHALLENGE_DELIVERY_CELL)) { + return $user; + } + + $snapshotUserId = session()->get(self::CHALLENGE_DELIVERY_USER_ID); + if ($snapshotUserId !== null && (int) $snapshotUserId !== (int) $user->id) { + return $user; + } + + $deliveryUser = $user->replicate(); + $deliveryUser->exists = true; + $deliveryUser->id = $user->id; + if (session()->exists(self::CHALLENGE_DELIVERY_EMAIL)) { + $deliveryUser->email = $email; + } + if (session()->exists(self::CHALLENGE_DELIVERY_CELL)) { + $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); + } + + private function hasCompletedDeliveryStepUp(): bool + { + return session()->get(self::DELIVERY_STEP_UP, false); + } + + public function mayEnrollNewAuthenticator(User $user): bool + { + if (!$this->needsAuthenticatorEnrollment($user)) { + return false; + } + + if (!$this->challengeRequiresDeliveryStepUp()) { + return true; + } + + return $this->hasCompletedDeliveryStepUp(); + } + + private function configureOtp(TOTP $otp, User $user, bool $forGoogleAuthApp): TOTP + { $otp->setIssuer('ProcessMaker'); $otp->setLabel($user->username); @@ -71,6 +268,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 +289,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 = $this->challengeMethods($user); - // Create OTP instance - $otp = $this->createOtpInstance($user, $forGoogleAuthApp); + if (strlen($code) === 6) { + return $this->verifyAuthenticatorCode($user, $code, $methods); + } + + 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); + } - // Validate code - return $otp->verify($code); + 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(); + $this->forgetPendingAuthenticatorEnrollment(); + } + + return $valid; + } + + private function hasDeliveryMethod(array $methods): bool + { + return in_array(self::EMAIL, $methods, true) || in_array(self::SMS, $methods, true); } /** @@ -154,7 +395,14 @@ 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) || !$this->sessionHasPendingAuthenticatorForUser($user)) { + $secret = TOTP::generate()->getSecret(); + session()->put(self::PENDING_AUTHENTICATOR_SECRET, $secret); + session()->put(self::PENDING_AUTHENTICATOR_USER_ID, $user->id); + } + + $otp = $this->configureOtp(TOTP::createFromSecret($secret), $user, true); $g2faUrl = $otp->getProvisioningUri(); @@ -168,6 +416,46 @@ public function generateQr(User $user) return base64_encode($writer->writeString($g2faUrl)); } + public function selfServiceUpdateRequiresTwoFactorCompletion(User $apiUser): bool + { + if (!$this->isTwoFactorEnabled()) { + return false; + } + + $webUserId = \Illuminate\Support\Facades\Auth::guard('web')->id(); + if ($webUserId === null || (int) $webUserId !== (int) $apiUser->id) { + return true; + } + + if ($this->userHasSsoBinding($apiUser)) { + return false; + } + + return !session()->get(Http\Controllers\Auth\TwoFactorAuthController::TFA_VALIDATED, false); + } + + private function isTwoFactorEnabled(): bool + { + return config('password-policies.2fa_enabled', false) + && !empty(config('password-policies.2fa_method', [])) + && Http\Controllers\Auth\TwoFactorAuthController::check2faByGroups(); + } + + private function userHasSsoBinding(User $user): bool + { + if (isset($user->meta?->authenticationType) + && $user->meta->authenticationType === 'ldap') { + return true; + } + + $ssoUserClass = 'ProcessMaker\Package\Auth\Models\SsoUser'; + if (class_exists($ssoUserClass)) { + return $ssoUserClass::where('user_id', $user->id)->exists(); + } + + return false; + } + public function friendlyMethodsNames(User $user, array $enabledMethods = []) { // Define the friendly names for each method @@ -179,7 +467,7 @@ public function friendlyMethodsNames(User $user, array $enabledMethods = []) // Get enabled methods to send the code if (empty($enabledMethods)) { - $enabledMethods = $user->getValid2FAPreferences(); + $enabledMethods = $this->userPreferredMethods($user); } // Return the friendly names for enabled methods @@ -197,4 +485,13 @@ public function friendlyMethodsNames(User $user, array $enabledMethods = []) return $methods; } + + private function forgetChallengeSnapshot(): void + { + session()->forget(self::CHALLENGE_METHODS_SNAPSHOT); + session()->forget(self::CHALLENGE_METHODS_USER_ID); + session()->forget(self::CHALLENGE_DELIVERY_EMAIL); + session()->forget(self::CHALLENGE_DELIVERY_CELL); + session()->forget(self::CHALLENGE_DELIVERY_USER_ID); + } } 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 @@ - - -
- - - - - - -