enabled()) { return false; } if (config('manager.two_factor.super_admins', true) && method_exists($user, 'isManagerSuperAdmin') && $user->isManagerSuperAdmin()) { return true; } return method_exists($user, 'managerGroups') && $user->managerGroups()->where('require_two_factor', true)->exists(); } public function record(object $user): ?TwoFactor { return TwoFactor::query()->where('user_id', $user->getKey())->first(); } public function enrolled(object $user): bool { $record = $this->record($user); return $record !== null && $record->confirmed_at !== null && $record->secret !== null; } /** When the grace period of an account that has to have a second step and has none ends: thirty days (`grace_days`) after it was first seen so. */ public function graceEnds(object $user): ?CarbonImmutable { if (! $this->required($user) || $this->enrolled($user)) { return null; } $record = TwoFactor::query()->firstOrCreate(['user_id' => $user->getKey()]); if ($record->required_since === null) { $record->forceFill(['required_since' => now()])->save(); } return CarbonImmutable::instance($record->required_since)->addDays(max(0, (int) config('manager.two_factor.grace_days', 30))); } /** @return array{state: string, enrolled: bool, required: bool, grace_ends_at: ?string, days_left: ?int, recovery_left: int} */ public function state(?object $user): array { $none = ['state' => 'off', 'enrolled' => false, 'required' => false, 'grace_ends_at' => null, 'days_left' => null, 'recovery_left' => 0]; if ($user === null || ! $this->enabled()) { return $none; } $enrolled = $this->enrolled($user); $required = $this->required($user); $ends = $this->graceEnds($user); $state = $enrolled ? ($this->passed($user) ? 'ok' : 'challenge') : ($ends !== null && $ends->isPast() ? 'setup_required' : 'ok'); return [ 'state' => $state, 'enrolled' => $enrolled, 'required' => $required, 'grace_ends_at' => $ends?->toIso8601String(), 'days_left' => $ends === null ? null : max(0, (int) ceil(now()->diffInSeconds($ends, false) / 86400)), 'recovery_left' => $enrolled ? count($this->record($user)?->recovery_codes ?? []) : 0, ]; } /** Whether this account may use the manager now (also for what is served outside the manager and honours its rights, such as a page preview). */ public function allows(?object $user): bool { return in_array($this->state($user)['state'], ['off', 'ok'], true); } public function passed(object $user): bool { return app()->bound('request') && request()->hasSession() && request()->session()->get(self::SESSION) === $user->getKey(); } /** The session now holds the proof, under a new session id (so one that was seen before is worthless). */ public function mark(object $user): void { $session = request()->session(); $session->regenerate(); $session->put(self::SESSION, $user->getKey()); } /** * Whether a code is right: the six digits of the app (each step once) or a recovery code (once). Counts every wrong try against * the account; too many and nothing is accepted for a while, right code or not. */ public function attempt(object $user, string $code): bool { $id = $user->getKey(); $minute = "manager-2fa:minute:{$id}"; $day = "manager-2fa:day:{$id}"; if (RateLimiter::tooManyAttempts($minute, self::PER_MINUTE) || RateLimiter::tooManyAttempts($day, self::PER_DAY)) { throw new HttpResponseException(response()->json(['message' => $wait = __('Too many wrong codes. Try again later.'), 'errors' => ['code' => [$wait]]], 429)); } if ($this->check($user, $code)) { RateLimiter::clear($minute); return true; } RateLimiter::hit($minute, 60); RateLimiter::hit($day, 86400); return false; } private function check(object $user, string $code): bool { $record = $this->record($user); if ($record === null || $record->secret === null) { return false; } $clean = preg_replace('/\s+/', '', $code) ?? ''; if (preg_match('/^\d{6}$/', $clean) === 1) { $step = Totp::verify($record->secret, $clean, $record->last_step); // The step is written only if nothing newer was written meanwhile: two requests with the same code cannot both pass. return $step !== null && TwoFactor::query()->whereKey($record->getKey())->where(fn ($query) => $query->whereNull('last_step')->orWhere('last_step', '<', $step))->update(['last_step' => $step]) === 1; } $hash = $this->hash($clean); $codes = $record->recovery_codes ?? []; $left = array_values(array_filter($codes, fn (string $known) => ! hash_equals($known, $hash))); if (count($left) === count($codes)) { return false; } $record->forceFill(['recovery_codes' => $left])->save(); return true; } /** A new secret, not yet in use: shown to the account to put in its app. @return array{secret: string, uri: string} */ public function start(object $user): array { $secret = Totp::secret(); $record = TwoFactor::query()->firstOrCreate(['user_id' => $user->getKey()]); $record->forceFill(['secret' => $secret, 'confirmed_at' => null, 'recovery_codes' => null, 'last_step' => null])->save(); return ['secret' => $secret, 'uri' => Totp::uri($secret, (string) data_get($user, 'email', ''), $this->issuer())]; } /** * The first code from the app turns the second step on. Returns the recovery codes (shown once), or null for a wrong code. * * @return ?list */ public function confirm(object $user, string $code): ?array { $record = $this->record($user); if ($record === null || $record->secret === null || $record->confirmed_at !== null || ! $this->attempt($user, $code)) { return null; } $record->refresh(); $codes = $this->makeCodes(); $record->forceFill(['confirmed_at' => now(), 'recovery_codes' => array_map($this->hash(...), $codes)])->save(); return $codes; } /** @return list */ public function newRecoveryCodes(object $user): array { $codes = $this->makeCodes(); $this->record($user)?->forceFill(['recovery_codes' => array_map($this->hash(...), $codes)])->save(); return $codes; } /** The account has no second step any more. Its grace period is not given back: `required_since` stays. */ public function reset(object $user): void { $this->record($user)?->forceFill(['secret' => null, 'recovery_codes' => null, 'confirmed_at' => null, 'last_step' => null])->save(); } /** A line in the audit log, when the site has that module on (the log is not there otherwise). */ public function log(string $event, string $summary, ?object $user, ?object $subject = null): void { if (app(ModuleRegistry::class)->enabled('audit')) { app(AuditTrail::class)->record($event, $summary, $user, $subject); } } public function issuer(): string { return (string) (config('manager.two_factor.issuer') ?: config('manager.name') ?: config('app.name', 'Manager')); } /** @return list eight codes of ten letters and digits, without the ones that look alike */ private function makeCodes(): array { $codes = []; for ($i = 0; $i < 8; $i++) { $codes[] = rtrim(chunk_split($this->random(10), 5, '-'), '-'); } return $codes; } private function random(int $length): string { $alphabet = 'abcdefghjkmnpqrstuvwxyz23456789'; $out = ''; for ($i = 0; $i < $length; $i++) { $out .= $alphabet[random_int(0, strlen($alphabet) - 1)]; } return $out; } private function hash(string $code): string { return hash_hmac('sha256', str_replace(['-', ' '], '', Str::lower($code)), (string) config('app.key')); } }