1
1
mirror of https://github.com/pterodactyl/panel.git synced 2024-11-25 10:32:31 +01:00

Generate recovery tokens when enabling 2FA on an account

This commit is contained in:
Dane Everitt 2020-07-02 21:55:25 -07:00
parent 7ee509d8c2
commit a998b463e3
No known key found for this signature in database
GPG Key ID: EEA66103B3D71F53
6 changed files with 145 additions and 8 deletions

View File

@ -96,9 +96,14 @@ class TwoFactorController extends ClientApiController
throw new ValidationException($validator);
}
$this->toggleTwoFactorService->handle($request->user(), $request->input('code'), true);
$tokens = $this->toggleTwoFactorService->handle($request->user(), $request->input('code'), true);
return new JsonResponse([], Response::HTTP_NO_CONTENT);
return new JsonResponse([
'object' => 'recovery_tokens',
'attributes' => [
'tokens' => $tokens,
],
]);
}
/**

View File

@ -0,0 +1,39 @@
<?php
namespace Pterodactyl\Models;
/**
* @property int $id
* @property int $user_id
* @property string $token
* @property \Carbon\CarbonImmutable $created_at
*
* @property \Pterodactyl\Models\User $user
*/
class RecoveryToken extends Model
{
/**
* There are no updates to this model, only inserts and deletes.
*/
const UPDATED_AT = null;
/**
* @var bool
*/
protected $immutableDates = true;
/**
* @var string[]
*/
public static $validationRules = [
'token' => 'required|string',
];
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo(User::class);
}
}

View File

@ -39,6 +39,7 @@ use Pterodactyl\Notifications\SendPasswordReset as ResetPasswordNotification;
* @property \Pterodactyl\Models\ApiKey[]|\Illuminate\Database\Eloquent\Collection $apiKeys
* @property \Pterodactyl\Models\Server[]|\Illuminate\Database\Eloquent\Collection $servers
* @property \Pterodactyl\Models\DaemonKey[]|\Illuminate\Database\Eloquent\Collection $keys
* @property \Pterodactyl\Models\RecoveryToken[]|\Illuminate\Database\Eloquent\Collection $recoveryCodes
*/
class User extends Model implements
AuthenticatableContract,
@ -251,4 +252,12 @@ class User extends Model implements
return $this->hasMany(ApiKey::class)
->where('key_type', ApiKey::TYPE_ACCOUNT);
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function recoveryCodes()
{
return $this->hasMany(RecoveryToken::class);
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace Pterodactyl\Repositories\Eloquent;
use Pterodactyl\Models\RecoveryToken;
class RecoveryTokenRepository extends EloquentRepository
{
/**
* @return string
*/
public function model()
{
return RecoveryToken::class;
}
}

View File

@ -3,10 +3,12 @@
namespace Pterodactyl\Services\Users;
use Carbon\Carbon;
use Illuminate\Support\Str;
use Pterodactyl\Models\User;
use PragmaRX\Google2FA\Google2FA;
use Illuminate\Contracts\Encryption\Encrypter;
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
use Pterodactyl\Repositories\Eloquent\RecoveryTokenRepository;
use Pterodactyl\Exceptions\Service\User\TwoFactorAuthenticationTokenInvalid;
class ToggleTwoFactorService
@ -26,21 +28,29 @@ class ToggleTwoFactorService
*/
private $repository;
/**
* @var \Pterodactyl\Repositories\Eloquent\RecoveryTokenRepository
*/
private $recoveryTokenRepository;
/**
* ToggleTwoFactorService constructor.
*
* @param \Illuminate\Contracts\Encryption\Encrypter $encrypter
* @param \PragmaRX\Google2FA\Google2FA $google2FA
* @param \Pterodactyl\Repositories\Eloquent\RecoveryTokenRepository $recoveryTokenRepository
* @param \Pterodactyl\Contracts\Repository\UserRepositoryInterface $repository
*/
public function __construct(
Encrypter $encrypter,
Google2FA $google2FA,
RecoveryTokenRepository $recoveryTokenRepository,
UserRepositoryInterface $repository
) {
$this->encrypter = $encrypter;
$this->google2FA = $google2FA;
$this->repository = $repository;
$this->recoveryTokenRepository = $recoveryTokenRepository;
}
/**
@ -49,7 +59,7 @@ class ToggleTwoFactorService
* @param \Pterodactyl\Models\User $user
* @param string $token
* @param bool|null $toggleState
* @return bool
* @return string[]
*
* @throws \PragmaRX\Google2FA\Exceptions\IncompatibleWithGoogleAuthenticatorException
* @throws \PragmaRX\Google2FA\Exceptions\InvalidCharactersException
@ -58,16 +68,43 @@ class ToggleTwoFactorService
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
* @throws \Pterodactyl\Exceptions\Service\User\TwoFactorAuthenticationTokenInvalid
*/
public function handle(User $user, string $token, bool $toggleState = null): bool
public function handle(User $user, string $token, bool $toggleState = null): array
{
$secret = $this->encrypter->decrypt($user->totp_secret);
$isValidToken = $this->google2FA->verifyKey($secret, $token, config()->get('pterodactyl.auth.2fa.window'));
if (! $isValidToken) {
throw new TwoFactorAuthenticationTokenInvalid(
'The token provided is not valid.'
);
throw new TwoFactorAuthenticationTokenInvalid('The token provided is not valid.');
}
// Now that we're enabling 2FA on the account, generate 10 recovery tokens for the account
// and store them hashed in the database. We'll return them to the caller so that the user
// can see and save them.
//
// If a user is unable to login with a 2FA token they can provide one of these backup codes
// which will then be marked as deleted from the database and will also bypass 2FA protections
// on their account.
$tokens = [];
if ((! $toggleState && ! $user->use_totp) || $toggleState) {
$inserts = [];
for ($i = 0; $i < 10; $i++) {
$token = Str::random(10);
$inserts[] = [
'user_id' => $user->id,
'token' => password_hash($token, PASSWORD_DEFAULT),
];
$tokens[] = $token;
}
// Bulk insert the hashed tokens.
$this->recoveryTokenRepository->insert($inserts);
} elseif ($toggleState === false || $user->use_totp) {
// If we are disabling 2FA on this account we will delete all of the recovery codes
// that exist in the database for this account.
$this->recoveryTokenRepository->deleteWhere(['user_id' => $user->id]);
}
$this->repository->withoutFreshModel()->update($user->id, [
@ -75,6 +112,6 @@ class ToggleTwoFactorService
'use_totp' => (is_null($toggleState) ? ! $user->use_totp : $toggleState),
]);
return true;
return $tokens;
}
}

View File

@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUserRecoveryTokensTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('recovery_tokens', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('recovery_tokens');
}
}