Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 57 additions & 11 deletions ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,15 @@ 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;
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.',
Expand Down Expand Up @@ -76,7 +76,7 @@ public function validateTwoFactorAuthCode(Request $request)
// If empty code return error message
if (empty($code)) {
// Set error message
session()->put(self::TFA_ERROR, _('Invalid code.'));
session()->put(self::TFA_ERROR, __('Invalid code.'));

// Return to 2fa page
return redirect()->route('2fa');
Expand All @@ -98,7 +98,7 @@ public function validateTwoFactorAuthCode(Request $request)
$route = 'login';
} else {
// Set error message
session()->put(self::TFA_ERROR, _('Invalid code.'));
session()->put(self::TFA_ERROR, __('Invalid code.'));

// Return to 2fa page
$route = '2fa';
Expand Down Expand Up @@ -129,17 +129,62 @@ 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;
$methods = $user->getValid2FAPreferences();

if (!in_array(TwoFactorAuthentication::AUTH_APP, $methods, true)
|| !empty($user->two_factor_secret)
) {
return redirect()->route('2fa');
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

// Generate QR code
$qrCode = $this->twoFactorAuthentication->generateQr($user);

// Display view
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)
&& !in_array(TwoFactorAuthentication::EMAIL, $methods, true)
&& !in_array(TwoFactorAuthentication::SMS, $methods, true);
}

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');
Expand All @@ -153,7 +198,7 @@ public function testSettings(Request $request)
if (count($enabled) === 0) {
$message = [
'status' => 'error',
'message' => __('The two-step method must be selected.')
'message' => __('The two-step method must be selected.'),
];
$status = 500;
}
Expand Down Expand Up @@ -237,6 +282,7 @@ public static function check2faByGroups()
{
try {
$user = Auth::user();

return $user->in2FAGroupOrIndependent();
} catch (Exception $e) {
session()->put(self::TFA_ERROR, $e->getMessage());
Expand Down
4 changes: 4 additions & 0 deletions ProcessMaker/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
];

/**
Expand Down Expand Up @@ -238,6 +240,8 @@ public static function passwordRules(self $existing = null)
*/
protected $hidden = [
'password',
'two_factor_secret',
'two_factor_delivery_secret',
'groupMembersFromMemberable',
'permissions',
];
Expand Down
6 changes: 3 additions & 3 deletions ProcessMaker/Notifications/TwoFactorAuthNotification.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class TwoFactorAuthNotification extends Notification
/**
* Create a new notification instance.
*
* @param \ProcessMaker\Models\User $user
* @param User $user
* @param string $code
*/
public function __construct(User $user, string $code)
Expand All @@ -43,12 +43,12 @@ public function via($notifiable)
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
* @return MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->subject(_('Security Code'))
->subject(__('Security Code'))
->greeting($this->user->username)
->line(__('This is your security code: :code', ['code' => $this->code]));
}
Expand Down
108 changes: 92 additions & 16 deletions ProcessMaker/TwoFactorAuthentication.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -24,6 +23,8 @@

const ERROR_INVALID_TO_NUMBER = 21211;

public const PENDING_AUTHENTICATOR_SECRET = '2fa-pending-authenticator-secret';

public function sendCode(User $user): void
{
// Get methods to send the code
Expand All @@ -45,20 +46,55 @@
}
}

private function generateSecret(User $user): string
private function getUserTotpSecret(User $user): string

Check warning on line 49 in ProcessMaker/TwoFactorAuthentication.php

View check run for this annotation

Decisions SonarQube / SonarQube Code Analysis

Remove this unused private "getusertotpsecret" method.

[S1144] Unused "private" methods should be removed See more on https://builds.decisions.com:9000/project/issues?id=ProcessMaker_processmaker_AYkzkfKexYvY_isvKt07&pullRequest=9127&issues=8d3cfc5e-3510-4d61-b519-99399eddd13e&open=8d3cfc5e-3510-4d61-b519-99399eddd13e
{
$base = $user->uuid . '_' . $user->username;
if (!empty($user->two_factor_secret)) {
return $user->two_factor_secret;
}

$secret = TOTP::generate()->getSecret();

if ($user->exists) {
$user->two_factor_secret = $secret;
$user->saveQuietly();
} else {
$user->setAttribute('two_factor_secret', $secret);
}

return trim(Base32::encodeUpper($base), '=');
return $secret;
}

private function createOtpInstance(User $user, bool $forGoogleAuthApp = false)
private function getUserDeliveryTotpSecret(User $user): string
{
// Get secret
$secret = $this->generateSecret($user);
if (!empty($user->two_factor_delivery_secret)) {
return $user->two_factor_delivery_secret;
}

// Config OTP
$otp = TOTP::createFromSecret($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 $secret;
}

private function resolveAuthenticatorSecret(User $user): ?string
{
if (!empty($user->two_factor_secret)) {
return $user->two_factor_secret;
}

$pending = session()->get(self::PENDING_AUTHENTICATOR_SECRET);

return !empty($pending) ? $pending : null;
}

private function configureOtp(TOTP $otp, User $user, bool $forGoogleAuthApp): TOTP
{
$otp->setIssuer('ProcessMaker');
$otp->setLabel($user->username);

Expand All @@ -71,6 +107,18 @@
return $otp;
}

private function createOtpInstance(User $user, bool $forGoogleAuthApp = false)
{
$secret = $forGoogleAuthApp
? $this->resolveAuthenticatorSecret($user)
: $this->getUserDeliveryTotpSecret($user);

// Config OTP
$otp = $this->configureOtp(TOTP::createFromSecret($secret), $user, $forGoogleAuthApp);

Check warning on line 117 in ProcessMaker/TwoFactorAuthentication.php

View check run for this annotation

Decisions SonarQube / SonarQube Code Analysis

Immediately return this expression instead of assigning it to the temporary variable "$otp".

[S1488] Local variables should not be declared and then immediately returned or thrown See more on https://builds.decisions.com:9000/project/issues?id=ProcessMaker_processmaker_AYkzkfKexYvY_isvKt07&pullRequest=9127&issues=d3ebcaa3-3156-461f-b828-8c172575c9b2&open=d3ebcaa3-3156-461f-b828-8c172575c9b2

return $otp;
}

private function getCodeForEmailSms(User $user): string
{
// Create OTP instance
Expand All @@ -82,14 +130,36 @@

public function validateCode(User $user, string $code)
{
// The code is for Google Authenticator app?
$forGoogleAuthApp = strlen($code) === 6;
$methods = $user->getValid2FAPreferences();
$valid = false;

// Create OTP instance
$otp = $this->createOtpInstance($user, $forGoogleAuthApp);
// The code is for Google Authenticator app?
if (strlen($code) === 6) {
$authSecret = $this->resolveAuthenticatorSecret($user);
if (in_array(self::AUTH_APP, $methods, true) && $authSecret !== null) {
// Create OTP instance
$otp = $this->createOtpInstance($user, true);

// Validate code
$valid = $otp->verify($code);
if ($valid && empty($user->two_factor_secret)) {
$user->two_factor_secret = $authSecret;
$user->saveQuietly();
session()->forget(self::PENDING_AUTHENTICATOR_SECRET);
}
}
} elseif (
(in_array(self::EMAIL, $methods, true) || in_array(self::SMS, $methods, true))
&& !empty($user->two_factor_delivery_secret)
) {
// Create OTP instance
$otp = $this->createOtpInstance($user, false);

// Validate code
$valid = $otp->verify($code);
}

// Validate code
return $otp->verify($code);
return $valid;
}

/**
Expand Down Expand Up @@ -154,7 +224,13 @@

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);
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

$otp = $this->configureOtp(TOTP::createFromSecret($secret), $user, true);

$g2faUrl = $otp->getProvisioningUri();

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->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']);
});
}
};
Loading
Loading