From 5dfd6221418f65c5eff901e43890760d32929641 Mon Sep 17 00:00:00 2001 From: Kevin Adametz Date: Thu, 8 Oct 2026 13:02:49 +0000 Subject: [PATCH] =?UTF-8?q?security:=20Andere=20Ger=C3=A4te=20abmelden,=20?= =?UTF-8?q?IP-weites=20Login-Limit,=20dauerhafte=20Sperrmarke,=20Passwortr?= =?UTF-8?q?egeln,=20CSP=20im=20Melde-Modus?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Restliche Phase 4 aus dem Sicherheitsaudit 07.10.2026: - Sicherheitsseite: „Andere Geräte abmelden“ rotiert remember_token und beendet alle anderen Sessions, die aktuelle bleibt (nicht während einer Impersonation). - LoginIpThrottle: 20 Fehlversuche je IP in 15 Minuten über alle Konten. Gezählt über das Failed-Event, damit Livewire-Login und Fortifys POST /login denselben Zähler teilen; Erfolg setzt ihn nicht zurück. - Sperrmarke für Sessions in users.sessions_revoked_at_ms statt nur im Cache — übersteht cache:clear. Die alte Cache-Marke zählt übergangsweise mit und kann im nächsten Release entfallen. - Neue und geänderte Passwörter: mindestens 12 Zeichen, in Produktion zusätzlich uncompromised() (HIBP, k-Anonymität). Bestehende bleiben gültig. - Content-Security-Policy-Report-Only in Produktion; Meldungen über /csp-report nach storage/logs/csp-*.log, je Meldung höchstens einmal pro Stunde, ohne Query und tokenartige Pfadsegmente. Migration: users.sessions_revoked_at_ms (users hat FULLTEXT, 25 MB, Sekunden). Co-Authored-By: Claude Opus 5.5 --- .env.example | 2 + app/Http/Controllers/CspReportController.php | 65 ++++++++ .../Middleware/EnsureSessionIsNotRevoked.php | 7 +- app/Http/Middleware/SecurityHeaders.php | 10 +- app/Listeners/CountFailedLoginsPerIp.php | 25 ++++ app/Models/User.php | 1 + app/Providers/AppServiceProvider.php | 13 ++ app/Providers/FortifyServiceProvider.php | 15 ++ app/Services/Auth/LoginIpThrottle.php | 43 ++++++ app/Services/Auth/SessionRevocation.php | 49 ++++-- app/Support/ContentSecurityPolicy.php | 73 +++++++++ bootstrap/app.php | 8 + config/logging.php | 3 + config/security.php | 16 ++ ..._sessions_revoked_at_ms_to_users_table.php | 30 ++++ phpunit.xml | 3 +- resources/views/livewire/auth/login.blade.php | 12 +- .../views/livewire/auth/register.blade.php | 2 +- .../livewire/auth/reset-password.blade.php | 4 +- .../livewire/customer/security.blade.php | 28 +++- tests/Feature/ActivityLogTest.php | 4 +- .../PasswordChangeRevokesSessionsTest.php | 71 +++++++++ tests/Feature/Auth/PasswordResetTest.php | 4 +- tests/Feature/Auth/RegistrationTest.php | 8 +- tests/Feature/LogChannelsTest.php | 1 + tests/Feature/SecurityHardeningTest.php | 141 ++++++++++++++++++ tests/TestCase.php | 2 +- 27 files changed, 601 insertions(+), 39 deletions(-) create mode 100644 app/Http/Controllers/CspReportController.php create mode 100644 app/Listeners/CountFailedLoginsPerIp.php create mode 100644 app/Services/Auth/LoginIpThrottle.php create mode 100644 app/Support/ContentSecurityPolicy.php create mode 100644 database/migrations/2026_10_08_142917_add_sessions_revoked_at_ms_to_users_table.php diff --git a/.env.example b/.env.example index 73d3253c..3aae8d25 100644 --- a/.env.example +++ b/.env.example @@ -353,3 +353,5 @@ IMAGE_PRECHECK_STAGE=1 # HSTS: ohne Angabe nur bei APP_ENV=production an, max-age 1 Jahr. # SECURITY_HSTS= # SECURITY_HSTS_MAX_AGE=31536000 +# CSP im Melde-Modus: ohne Angabe nur bei APP_ENV=production an, Meldungen in storage/logs/csp-*.log. +# SECURITY_CSP_REPORT_ONLY= diff --git a/app/Http/Controllers/CspReportController.php b/app/Http/Controllers/CspReportController.php new file mode 100644 index 00000000..8d3cf253 --- /dev/null +++ b/app/Http/Controllers/CspReportController.php @@ -0,0 +1,65 @@ +getContent(); + + if (! config('security.csp.report_only') || $body === '' || strlen($body) > self::MAX_BYTES) { + return response()->noContent(); + } + + $report = json_decode($body, true)['csp-report'] ?? null; + + if (! is_array($report)) { + return response()->noContent(); + } + + $entry = [ + 'directive' => mb_substr((string) ($report['effective-directive'] ?? $report['violated-directive'] ?? ''), 0, 60), + 'blocked' => $this->scrub($report['blocked-uri'] ?? ''), + 'document' => $this->scrub($report['document-uri'] ?? ''), + 'source' => $this->scrub($report['source-file'] ?? ''), + 'line' => (int) ($report['line-number'] ?? 0), + 'sample' => mb_substr((string) ($report['script-sample'] ?? ''), 0, 40), + ]; + + if (Cache::add('csp-report.'.sha1(json_encode($entry)), true, now()->addHour())) { + Log::channel('csp')->warning('CSP-Verstoß (nur gemeldet)', $entry); + } + + return response()->noContent(); + } + + private function scrub(mixed $value): string + { + $value = mb_substr(is_string($value) ? $value : '', 0, 500); + $parts = parse_url($value); + + // Schlüsselwörter wie „inline“, „eval“, „data“ unverändert. + if (! is_array($parts) || empty($parts['host'])) { + return mb_substr(strtok($value, '?#') ?: '', 0, 60); + } + + $path = preg_replace('#/[A-Za-z0-9_-]{32,}(?=/|$)#', '/[Filtered]', $parts['path'] ?? ''); + + return mb_substr(($parts['scheme'] ?? 'https').'://'.$parts['host'].$path, 0, 200); + } +} diff --git a/app/Http/Middleware/EnsureSessionIsNotRevoked.php b/app/Http/Middleware/EnsureSessionIsNotRevoked.php index 10b61adf..71081acb 100644 --- a/app/Http/Middleware/EnsureSessionIsNotRevoked.php +++ b/app/Http/Middleware/EnsureSessionIsNotRevoked.php @@ -2,6 +2,7 @@ namespace App\Http\Middleware; +use App\Models\User; use App\Services\Auth\SessionRevocation; use Closure; use Illuminate\Auth\SessionGuard; @@ -11,8 +12,8 @@ use Symfony\Component\HttpFoundation\Response; /** * Meldet eine Session ab, die vor der letzten Sperre ihres Kontos entstanden - * ist (SessionRevocation, Audit K-04). Kostet je angemeldetem Request einen - * Cache-Zugriff; Gäste lösen keinen aus. + * ist (SessionRevocation, Audit K-04). Die Marke steht am geladenen User; + * bis zum Release nach v1.6.0 kommt ein Cache-Zugriff dazu (Übergang). */ class EnsureSessionIsNotRevoked { @@ -33,7 +34,7 @@ class EnsureSessionIsNotRevoked $user = $guard->user(); - if ($user === null || ! $this->revocation->isRevoked((int) $user->getAuthIdentifier(), $request->session())) { + if (! $user instanceof User || ! $this->revocation->isRevoked($user, $request->session())) { return $next($request); } diff --git a/app/Http/Middleware/SecurityHeaders.php b/app/Http/Middleware/SecurityHeaders.php index 9f237846..9d7a47ea 100644 --- a/app/Http/Middleware/SecurityHeaders.php +++ b/app/Http/Middleware/SecurityHeaders.php @@ -2,6 +2,7 @@ namespace App\Http\Middleware; +use App\Support\ContentSecurityPolicy; use Closure; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; @@ -11,8 +12,7 @@ use Symfony\Component\HttpFoundation\Response; * Reverse-Proxy gesetzt, damit der Schutz auch bei Proxy-Wechsel bleibt. * Bereits vorhandene Header (z. B. vom Proxy) werden nicht überschrieben. * HSTS nur auf HTTPS-Antworten und laut config/security.php. - * CSP fehlt absichtlich: Livewire/Alpine/Vite brauchen eine eigene - * Inline-Script-Strategie — separat einführen, nicht nebenbei. + * CSP vorerst nur im Melde-Modus (ContentSecurityPolicy, config/security.php). */ class SecurityHeaders { @@ -31,6 +31,12 @@ class SecurityHeaders } } + if (config('security.csp.report_only') + && str_contains((string) $response->headers->get('Content-Type'), 'text/html') + && ! $response->headers->has('Content-Security-Policy-Report-Only')) { + $response->headers->set('Content-Security-Policy-Report-Only', ContentSecurityPolicy::header()); + } + if ($request->isSecure() && config('security.hsts.enabled') && ! $response->headers->has('Strict-Transport-Security')) { $response->headers->set('Strict-Transport-Security', 'max-age='.(int) config('security.hsts.max_age')); } diff --git a/app/Listeners/CountFailedLoginsPerIp.php b/app/Listeners/CountFailedLoginsPerIp.php new file mode 100644 index 00000000..655ac3fd --- /dev/null +++ b/app/Listeners/CountFailedLoginsPerIp.php @@ -0,0 +1,25 @@ +guard !== 'web' || ! app()->bound('request')) { + return; + } + + $this->throttle->recordFailure(request()->ip()); + } +} diff --git a/app/Models/User.php b/app/Models/User.php index 1a5d3232..d323a24d 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -87,6 +87,7 @@ class User extends Authenticatable implements MustVerifyEmail, PasskeyUser 'deleted_at' => 'datetime', 'password' => 'hashed', 'press_release_quota_used_this_month' => 'integer', + 'sessions_revoked_at_ms' => 'integer', ]; } diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 58543206..d78c2514 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -66,6 +66,7 @@ use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Queue; use Illuminate\Support\Facades\URL; use Illuminate\Support\ServiceProvider; +use Illuminate\Validation\Rules\Password; use Laravel\Cashier\Cashier; use Laravel\Fortify\Events\TwoFactorAuthenticationFailed; use Livewire\Livewire; @@ -108,6 +109,18 @@ class AppServiceProvider extends ServiceProvider // Ausgelieferte Version in `php artisan about` (Datei RELEASE bzw. APP_VERSION). AboutCommand::add('Pressekonto', fn (): array => ['Version' => config('app.version') ?? '—']); + // Passwortregeln für neue und geänderte Passwörter (Sicherheitsaudit + // 07.10.2026, Phase 4). Bestehende kürzere Passwörter bleiben gültig. + // Der Leak-Abgleich fragt Have I Been Pwned per k-Anonymität ab (nur + // die ersten 5 Zeichen des SHA-1-Hashes verlassen den Server) und + // lässt das Passwort durch, wenn der Dienst nicht antwortet — daher + // nur in Produktion, Tests und lokale Entwicklung bleiben offline. + Password::defaults(function (): Password { + $rule = Password::min(12); + + return $this->app->isProduction() ? $rule->uncompromised() : $rule; + }); + // Die Generations-Nummer der Seiten-Caches wird prozessintern gemerkt. // Ein Queue-Worker lebt über beliebig viele Jobs hinweg und würde sonst // dauerhaft mit dem Stand seines ersten Zugriffs arbeiten — Keys einer diff --git a/app/Providers/FortifyServiceProvider.php b/app/Providers/FortifyServiceProvider.php index 9a5cb476..5c2df3c4 100644 --- a/app/Providers/FortifyServiceProvider.php +++ b/app/Providers/FortifyServiceProvider.php @@ -9,6 +9,7 @@ use App\Http\Responses\FailedTwoFactorChallengeResponse; use App\Http\Responses\PasskeyLoginResponse; use App\Http\Responses\RoleAwareLoginResponse; use App\Models\User; +use App\Services\Auth\LoginIpThrottle; use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Http\Request; use Illuminate\Support\Facades\RateLimiter; @@ -53,6 +54,20 @@ class FortifyServiceProvider extends ServiceProvider // Keine View-Definitionen, die Auth-Seiten sind Livewire-Komponenten RateLimiter::for('login', function (Request $request) { + // IP-weite Obergrenze über alle Konten (LoginIpThrottle) — der + // Zähler ist derselbe wie in der Livewire-Anmeldung. + $ipThrottle = app(LoginIpThrottle::class); + + if ($ipThrottle->isBlocked($request->ip())) { + $seconds = $ipThrottle->availableIn($request->ip()); + + return $request->expectsJson() + ? response()->json(['message' => __('auth.throttle', ['seconds' => $seconds, 'minutes' => ceil($seconds / 60)])], 429, ['Retry-After' => $seconds]) + : back()->withInput($request->only(Fortify::username()))->withErrors([ + Fortify::username() => __('auth.throttle', ['seconds' => $seconds, 'minutes' => ceil($seconds / 60)]), + ]); + } + $throttleKey = Str::transliterate(Str::lower($request->input(Fortify::username())).'|'.$request->ip()); return Limit::perMinute(5)->by($throttleKey); diff --git a/app/Services/Auth/LoginIpThrottle.php b/app/Services/Auth/LoginIpThrottle.php new file mode 100644 index 00000000..90c3dcf1 --- /dev/null +++ b/app/Services/Auth/LoginIpThrottle.php @@ -0,0 +1,43 @@ +key($ip), self::DECAY_SECONDS); + } + + public function isBlocked(?string $ip): bool + { + return RateLimiter::tooManyAttempts($this->key($ip), self::MAX_FAILURES); + } + + public function availableIn(?string $ip): int + { + return RateLimiter::availableIn($this->key($ip)); + } + + private function key(?string $ip): string + { + return 'login-failures-ip|'.($ip ?? 'unknown'); + } +} diff --git a/app/Services/Auth/SessionRevocation.php b/app/Services/Auth/SessionRevocation.php index cf67ebb6..ac18ac98 100644 --- a/app/Services/Auth/SessionRevocation.php +++ b/app/Services/Auth/SessionRevocation.php @@ -6,6 +6,7 @@ use App\Models\User; use Illuminate\Auth\Events\Login; use Illuminate\Contracts\Session\Session; use Illuminate\Support\Facades\Cache; +use Illuminate\Support\Str; /** * Beendet alle offenen Browser-Sessions eines Kontos (Umsetzungsaudit @@ -16,10 +17,12 @@ use Illuminate\Support\Facades\Cache; * ein Zeitstempel je Konto: Jede Anmeldung schreibt ihren Zeitpunkt in die * Session (`Login`-Event), `revokeAllFor()` merkt sich „ungültig vor jetzt", * und die Middleware EnsureSessionIsNotRevoked meldet jede ältere Session - * beim nächsten Request ab. Die Marke lebt so lange wie eine Session - * (`session.lifetime`) — danach ist jede ältere Session ohnehin abgelaufen. - * Remember-Cookies deckt das Rotieren von `remember_token` ab, API-Tokens - * löscht der Aufrufer. + * beim nächsten Request ab. Remember-Cookies deckt das Rotieren von + * `remember_token` ab, API-Tokens löscht der Aufrufer. + * + * Die Marke steht seit v1.6.0 in `users.sessions_revoked_at_ms` und übersteht + * so ein Leeren des Caches (Sicherheitsaudit 07.10.2026, Phase 4). Die + * Middleware liest sie am ohnehin geladenen User — kein zusätzlicher Zugriff. */ class SessionRevocation { @@ -35,11 +38,10 @@ class SessionRevocation { $revokedAt = now()->getTimestampMs(); - Cache::put( - $this->cacheKey((int) $user->getKey()), - $revokedAt, - now()->addMinutes(max(1, (int) config('session.lifetime', 120)) + 5), - ); + // Ohne Model-Events und ohne updated_at: Die Marke ist keine + // inhaltliche Änderung am Konto und soll keine Observer auslösen. + $user->newQuery()->whereKey($user->getKey())->update(['sessions_revoked_at_ms' => $revokedAt]); + $user->forceFill(['sessions_revoked_at_ms' => $revokedAt])->syncOriginalAttribute('sessions_revoked_at_ms'); return $revokedAt; } @@ -57,6 +59,18 @@ class SessionRevocation $current->migrate(true); } + /** + * „Andere Geräte abmelden“ auf der Sicherheitsseite: Remember-Cookies + * anderer Geräte werden ungültig (neuer `remember_token`), alle anderen + * Sessions enden beim nächsten Request, die aktuelle bleibt angemeldet. + */ + public function logoutOtherDevices(User $user, Session $current): void + { + $user->forceFill(['remember_token' => Str::random(60)])->save(); + + $this->revokeOthersFor($user, $current); + } + /** * Listener für `Login`: Zeitpunkt der Anmeldung in der Session. * Die Methode heißt bewusst nicht `handle*` (Event-Discovery). @@ -74,19 +88,24 @@ class SessionRevocation * Session stammt aus der Zeit vor der letzten Sperre dieses Kontos. * Ohne Anmeldezeitpunkt (Session von vor dem Deploy) gilt sie als alt. */ - public function isRevoked(int $userId, Session $session): bool + public function isRevoked(User $user, Session $session): bool { - $revokedAt = Cache::get($this->cacheKey($userId)); + $revokedAt = max((int) $user->sessions_revoked_at_ms, $this->legacyCachedMark((int) $user->getKey())); - if ($revokedAt === null) { + if ($revokedAt === 0) { return false; } - return (int) $session->get(self::SESSION_KEY, 0) < (int) $revokedAt; + return (int) $session->get(self::SESSION_KEY, 0) < $revokedAt; } - private function cacheKey(int $userId): string + /** + * Übergang: Bis v1.5.0 lag die Marke nur im Cache, mit Ablauf nach + * `session.lifetime` + 5 Minuten. Sperren aus dieser Zeit sollen über den + * Deploy hinweg gelten. Kann im Release nach v1.6.0 entfallen. + */ + private function legacyCachedMark(int $userId): int { - return 'auth.sessions-revoked-at.'.$userId; + return (int) Cache::get('auth.sessions-revoked-at.'.$userId, 0); } } diff --git a/app/Support/ContentSecurityPolicy.php b/app/Support/ContentSecurityPolicy.php new file mode 100644 index 00000000..dc3ad8ae --- /dev/null +++ b/app/Support/ContentSecurityPolicy.php @@ -0,0 +1,73 @@ +`. + */ +class ContentSecurityPolicy +{ + public const REPORT_PATH = '/csp-report'; + + public static function header(): string + { + $own = array_merge(["'self'"], self::ownOrigins()); + $umami = config('services.umami.enabled') ? self::originOf((string) config('services.umami.script_url')) : null; + $errors = self::originOf((string) config('monitoring.browser.dsn')); + + $directives = [ + 'default-src' => ["'self'"], + 'script-src' => [...$own, "'unsafe-inline'", "'unsafe-eval'", $umami], + 'style-src' => [...$own, "'unsafe-inline'"], + 'img-src' => [...$own, 'data:', 'blob:', 'https:'], + 'font-src' => [...$own, 'data:'], + 'connect-src' => [...$own, $umami, $errors], + 'media-src' => [...$own], + 'object-src' => ["'none'"], + 'frame-src' => ["'self'"], + 'frame-ancestors' => ["'self'"], + 'base-uri' => ["'self'"], + 'form-action' => [...$own, 'https://accounts.google.com', 'https://checkout.stripe.com', 'https://billing.stripe.com'], + 'report-uri' => [self::REPORT_PATH], + ]; + + return collect($directives) + ->map(fn (array $sources, string $directive): string => trim($directive.' '.implode(' ', array_unique(array_filter($sources))))) + ->implode('; '); + } + + /** + * Die drei Domains der Anwendung — Formulare und Assets können + * domainübergreifend auf die anderen zeigen. + * + * @return list + */ + private static function ownOrigins(): array + { + return collect([ + config('domains.domain_portal'), + config('domains.domain_presseecho'), + config('domains.domain_businessportal'), + ])->filter()->map(fn (string $host): string => 'https://'.$host)->values()->all(); + } + + private static function originOf(string $url): ?string + { + $parts = parse_url($url); + + if (! is_array($parts) || empty($parts['host'])) { + return null; + } + + return ($parts['scheme'] ?? 'https').'://'.$parts['host'].(isset($parts['port']) ? ':'.$parts['port'] : ''); + } +} diff --git a/bootstrap/app.php b/bootstrap/app.php index 00135b26..0ff845d2 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -1,5 +1,6 @@ middleware('throttle:30,1') ->name('health.deep'); + + // CSP-Meldungen der Browser (Melde-Modus, Sicherheitsaudit + // 07.10.2026) — ohne web-Gruppe: keine Session, kein CSRF. + Route::post(ContentSecurityPolicy::REPORT_PATH, CspReportController::class) + ->middleware('throttle:60,1') + ->name('csp.report'); }, ) ->withMiddleware(function (Middleware $middleware) { diff --git a/config/logging.php b/config/logging.php index 98eded0f..d074d3c4 100644 --- a/config/logging.php +++ b/config/logging.php @@ -116,6 +116,9 @@ return [ 'market' => $topicChannel('market'), + // CSP-Meldungen der Browser (Melde-Modus, CspReportController). + 'csp' => $topicChannel('csp'), + 'admin_slow' => [ 'driver' => 'daily', 'path' => storage_path('logs/admin-slow.log'), diff --git a/config/security.php b/config/security.php index c0491f6a..cbcc643b 100644 --- a/config/security.php +++ b/config/security.php @@ -20,4 +20,20 @@ return [ 'max_age' => (int) env('SECURITY_HSTS_MAX_AGE', 31536000), ], + /* + |-------------------------------------------------------------------------- + | Content Security Policy (Melde-Modus) + |-------------------------------------------------------------------------- + | + | Setzt `Content-Security-Policy-Report-Only` auf HTML-Antworten + | (App\Support\ContentSecurityPolicy). Browser blockieren nichts, sie + | melden Verstöße an /csp-report → storage/logs/csp-*.log. Standardmäßig + | nur in Produktion. + | + */ + + 'csp' => [ + 'report_only' => (bool) env('SECURITY_CSP_REPORT_ONLY', env('APP_ENV') === 'production'), + ], + ]; diff --git a/database/migrations/2026_10_08_142917_add_sessions_revoked_at_ms_to_users_table.php b/database/migrations/2026_10_08_142917_add_sessions_revoked_at_ms_to_users_table.php new file mode 100644 index 00000000..288383f9 --- /dev/null +++ b/database/migrations/2026_10_08_142917_add_sessions_revoked_at_ms_to_users_table.php @@ -0,0 +1,30 @@ +unsignedBigInteger('sessions_revoked_at_ms')->nullable()->after('remember_token'); + }); + } + + public function down(): void + { + Schema::table('users', function (Blueprint $table) { + $table->dropColumn('sessions_revoked_at_ms'); + }); + } +}; diff --git a/phpunit.xml b/phpunit.xml index 35fa9bcb..8d8c6946 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -48,9 +48,10 @@ - + + diff --git a/resources/views/livewire/auth/login.blade.php b/resources/views/livewire/auth/login.blade.php index e59836b0..63c376f2 100644 --- a/resources/views/livewire/auth/login.blade.php +++ b/resources/views/livewire/auth/login.blade.php @@ -2,6 +2,7 @@ use App\Models\User; use App\Services\Auth\LoginCompletion; +use App\Services\Auth\LoginIpThrottle; use App\Support\LoginRedirect; use Illuminate\Auth\Events\Failed; use Illuminate\Auth\Events\Lockout; @@ -99,7 +100,12 @@ new #[Layout('components.layouts.auth.pressekonto', ['heading' => 'Willkommen zu */ protected function ensureIsNotRateLimited(): void { - if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) { + // Zwei Grenzen: je Adresse und IP sowie IP-weit über alle Konten + // (LoginIpThrottle, Fehlversuche zählt CountFailedLoginsPerIp). + $ipThrottle = app(LoginIpThrottle::class); + $accountLimited = RateLimiter::tooManyAttempts($this->throttleKey(), 5); + + if (! $accountLimited && ! $ipThrottle->isBlocked(request()->ip())) { return; } @@ -107,7 +113,9 @@ new #[Layout('components.layouts.auth.pressekonto', ['heading' => 'Willkommen zu // für den Aktivitäts-Verlauf mitgeben. event(new Lockout(request()->duplicate(request: ['email' => $this->email]))); - $seconds = RateLimiter::availableIn($this->throttleKey()); + $seconds = $accountLimited + ? RateLimiter::availableIn($this->throttleKey()) + : $ipThrottle->availableIn(request()->ip()); throw ValidationException::withMessages([ 'email' => __('auth.throttle', [ diff --git a/resources/views/livewire/auth/register.blade.php b/resources/views/livewire/auth/register.blade.php index ea9362c6..8fb165b0 100644 --- a/resources/views/livewire/auth/register.blade.php +++ b/resources/views/livewire/auth/register.blade.php @@ -117,7 +117,7 @@ new #[Layout('components.layouts.auth.pressekonto', ['heading' => 'Konto erstell name="password" :label="__('Passwort')" autocomplete="new-password" - :placeholder="__('Mindestens 8 Zeichen')" + :placeholder="__('Mindestens 12 Zeichen')" /> 'Neues Passwor

- {{ __('Vergeben Sie ein neues Passwort für Ihr Konto. Mindestens 8 Zeichen, idealerweise eine Kombination aus Buchstaben, Zahlen und Sonderzeichen.') }} + {{ __('Vergeben Sie ein neues Passwort für Ihr Konto. Mindestens 12 Zeichen — am einfachsten eine Folge mehrerer Wörter.') }}

@@ -94,7 +94,7 @@ new #[Layout('components.layouts.auth.pressekonto', ['heading' => 'Neues Passwor name="password" :label="__('Neues Passwort')" autocomplete="new-password" - :placeholder="__('Mindestens 8 Zeichen')" + :placeholder="__('Mindestens 12 Zeichen')" /> flash('security-status', __('Passkey entfernt.')); } + /** + * Beendet alle anderen Anmeldungen des Kontos, die aktuelle bleibt + * (Sicherheitsaudit 07.10.2026, Phase 4). Nicht während einer + * Impersonation — das träfe die Geräte des Kunden. + */ + public function logoutOtherDevices(): void + { + abort_if(app(UserImpersonation::class)->isActive(), 403, __('Während der Benutzer-Impersonation können keine Geräte abgemeldet werden.')); + + app(SessionRevocation::class)->logoutOtherDevices(Auth::user(), session()->driver()); + + session()->flash('security-status', __('Alle anderen Geräte wurden abgemeldet. Dieses Gerät bleibt angemeldet.')); + } + private function ensureNotImpersonating(): void { abort_if(app(UserImpersonation::class)->isActive(), 403, __('Während der Benutzer-Impersonation können keine Passkeys verwaltet werden.')); @@ -406,7 +421,7 @@ new #[Layout('components.layouts.app'), Title('Konto-Sicherheit')] class extends
- +
{{ __('Passwort speichern') }} @@ -598,10 +613,15 @@ new #[Layout('components.layouts.app'), Title('Konto-Sicherheit')] class extends {{ $sessions->count() }} {{ __('Einträge') }}
-
-

- {{ __('Hier sehen Sie die letzten bekannten Web-Sessions Ihres Kontos. Abmelden erfolgt aktuell über das Nutzer-Menü.') }} +

+

+ {{ __('Sind Sie noch auf einem fremden oder verlorenen Gerät angemeldet? Hier beenden Sie alle anderen Anmeldungen — auch dauerhafte („Angemeldet bleiben“). Dieses Gerät bleibt angemeldet.') }}

+ + {{ __('Andere Geräte abmelden') }} +
diff --git a/tests/Feature/ActivityLogTest.php b/tests/Feature/ActivityLogTest.php index ab322393..22a9e4a1 100644 --- a/tests/Feature/ActivityLogTest.php +++ b/tests/Feature/ActivityLogTest.php @@ -25,8 +25,8 @@ test('a self registration is recorded in the activity log', function () { Livewire::test('auth.register') ->set('name', 'Verlauf Tester') ->set('email', 'verlauf@example.com') - ->set('password', 'password') - ->set('password_confirmation', 'password') + ->set('password', 'sicheres-passwort-2026') + ->set('password_confirmation', 'sicheres-passwort-2026') ->set('terms_accepted', true) ->call('register'); diff --git a/tests/Feature/Auth/PasswordChangeRevokesSessionsTest.php b/tests/Feature/Auth/PasswordChangeRevokesSessionsTest.php index bc0042f4..7400b97b 100644 --- a/tests/Feature/Auth/PasswordChangeRevokesSessionsTest.php +++ b/tests/Feature/Auth/PasswordChangeRevokesSessionsTest.php @@ -1,11 +1,14 @@ not->toBeNull() ->and($route->gatherMiddleware())->toContain('web'); }); + +test('logging out other devices keeps this session and ends every other one', function () { + /** @var TestCase $this */ + [$user, $otherSessionStamp] = accountWithOtherSession(); + + $this->actingAs($user)->withSession([SessionRevocation::SESSION_KEY => $otherSessionStamp]); + + Livewire::test('customer.security') + ->call('logoutOtherDevices') + ->assertHasNoErrors(); + + $this->get(route('me.security'))->assertSuccessful(); + + $this->withSession([SessionRevocation::SESSION_KEY => $otherSessionStamp]) + ->get(route('me.security')) + ->assertRedirect(route('login')); + $this->assertGuest(); + + // Remember-Cookies anderer Geräte werden ungültig, das Passwort bleibt. + $user->refresh(); + expect($user->remember_token)->not->toBe('old-remember-token') + ->and(Hash::check('password', $user->password))->toBeTrue() + ->and($user->tokens()->count())->toBe(1); +}); + +test('other devices cannot be logged out during impersonation', function () { + /** @var TestCase $this */ + [$user] = accountWithOtherSession(); + $admin = User::factory()->create(); + + $this->actingAs($user)->withSession([UserImpersonation::SessionKey => $admin->id]); + + Livewire::test('customer.security') + ->call('logoutOtherDevices') + ->assertForbidden(); + + expect($user->fresh()->remember_token)->toBe('old-remember-token') + ->and($user->fresh()->sessions_revoked_at_ms)->toBeNull(); +}); + +test('the revocation mark is stored on the account and survives a cache flush', function () { + /** @var TestCase $this */ + [$user, $otherSessionStamp] = accountWithOtherSession(); + + $revokedAt = app(SessionRevocation::class)->revokeAllFor($user); + Cache::flush(); + + expect($user->fresh()->sessions_revoked_at_ms)->toBe($revokedAt); + + $this->actingAs($user->fresh()) + ->withSession([SessionRevocation::SESSION_KEY => $otherSessionStamp]) + ->get(route('me.security')) + ->assertRedirect(route('login')); + $this->assertGuest(); +}); + +test('a revocation from before v1.6.0 that only lives in the cache still applies', function () { + /** @var TestCase $this */ + [$user, $otherSessionStamp] = accountWithOtherSession(); + + Cache::put('auth.sessions-revoked-at.'.$user->id, now()->getTimestampMs(), now()->addHour()); + + $this->actingAs($user->fresh()) + ->withSession([SessionRevocation::SESSION_KEY => $otherSessionStamp]) + ->get(route('me.security')) + ->assertRedirect(route('login')); + $this->assertGuest(); +}); diff --git a/tests/Feature/Auth/PasswordResetTest.php b/tests/Feature/Auth/PasswordResetTest.php index a351f13c..05254d3e 100644 --- a/tests/Feature/Auth/PasswordResetTest.php +++ b/tests/Feature/Auth/PasswordResetTest.php @@ -53,8 +53,8 @@ test('password can be reset with valid token', function () { Notification::assertSentTo($user, ResetPassword::class, function ($notification) use ($user) { $response = Livewire::test('auth.reset-password', ['token' => $notification->token]) ->set('email', $user->email) - ->set('password', 'password') - ->set('password_confirmation', 'password') + ->set('password', 'sicheres-passwort-2026') + ->set('password_confirmation', 'sicheres-passwort-2026') ->call('resetPassword'); $response diff --git a/tests/Feature/Auth/RegistrationTest.php b/tests/Feature/Auth/RegistrationTest.php index 9b6215d7..1945f5d7 100644 --- a/tests/Feature/Auth/RegistrationTest.php +++ b/tests/Feature/Auth/RegistrationTest.php @@ -25,8 +25,8 @@ test('new users register inactive and are sent to the verification notice', func Livewire::test('auth.register') ->set('name', 'Test User') ->set('email', 'test@example.com') - ->set('password', 'password') - ->set('password_confirmation', 'password') + ->set('password', 'sicheres-passwort-2026') + ->set('password_confirmation', 'sicheres-passwort-2026') ->set('terms_accepted', true) ->call('register') ->assertHasNoErrors() @@ -55,8 +55,8 @@ test('registration requires accepting the terms', function () { Livewire::test('auth.register') ->set('name', 'Test User') ->set('email', 'terms@example.com') - ->set('password', 'password') - ->set('password_confirmation', 'password') + ->set('password', 'sicheres-passwort-2026') + ->set('password_confirmation', 'sicheres-passwort-2026') ->set('terms_accepted', false) ->call('register') ->assertHasErrors(['terms_accepted']); diff --git a/tests/Feature/LogChannelsTest.php b/tests/Feature/LogChannelsTest.php index cc1c370e..7abb8333 100644 --- a/tests/Feature/LogChannelsTest.php +++ b/tests/Feature/LogChannelsTest.php @@ -27,6 +27,7 @@ test('every topic channel writes its own daily file with the shared retention', 'ki' => ['ki', 'ki'], 'monitoring' => ['monitoring', 'monitoring'], 'market' => ['market', 'market'], + 'csp' => ['csp', 'csp'], 'admin_slow' => ['admin_slow', 'admin-slow'], ]); diff --git a/tests/Feature/SecurityHardeningTest.php b/tests/Feature/SecurityHardeningTest.php index dc0d3e44..b05c2ee3 100644 --- a/tests/Feature/SecurityHardeningTest.php +++ b/tests/Feature/SecurityHardeningTest.php @@ -2,12 +2,18 @@ use App\Models\Company; use App\Models\User; +use App\Services\Auth\LoginIpThrottle; use Database\Seeders\RolesAndPermissionsSeeder; use Illuminate\Http\UploadedFile; +use Illuminate\Support\Facades\Hash; +use Illuminate\Support\Facades\Http; +use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Process; use Illuminate\Support\Facades\RateLimiter; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Storage; +use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\Rules\Password; use Livewire\Livewire; use Tests\TestCase; @@ -148,3 +154,138 @@ test('the test suite never sends real ntfy pushes', function () { ->and(config('monitoring.alerts.ntfy.topic'))->toBeEmpty() ->and(config('monitoring.alerts.ntfy.token'))->toBeEmpty(); }); + +test('too many failed logins from one ip block further logins for every account', function () { + /** @var TestCase $this */ + $user = User::factory()->create(['is_active' => true]); + + foreach (range(1, LoginIpThrottle::MAX_FAILURES) as $i) { + Livewire::test('auth.login') + ->set('email', "unbekannt{$i}@example.test") + ->set('password', 'falsches-passwort') + ->call('login') + ->assertHasErrors(['email']); + } + + // Richtige Zugangsdaten eines anderen Kontos helfen von dieser IP nicht. + Livewire::test('auth.login') + ->set('email', $user->email) + ->set('password', 'password') + ->call('login') + ->assertHasErrors(['email']); + + $this->assertGuest(); +}); + +test('the fortify login post shares the per-ip limit', function () { + /** @var TestCase $this */ + $user = User::factory()->create(['is_active' => true]); + + foreach (range(1, LoginIpThrottle::MAX_FAILURES) as $i) { + $this->postJson('/login', ['email' => "unbekannt{$i}@example.test", 'password' => 'falsch'])->assertUnprocessable(); + } + + $this->postJson('/login', ['email' => $user->email, 'password' => 'password']) + ->assertStatus(429) + ->assertHeader('Retry-After'); + + $this->assertGuest(); +}); + +test('failed logins below the per-ip limit do not block other accounts', function () { + /** @var TestCase $this */ + $user = User::factory()->create(['is_active' => true]); + $throttle = app(LoginIpThrottle::class); + + foreach (range(1, LoginIpThrottle::MAX_FAILURES - 1) as $i) { + $throttle->recordFailure('127.0.0.1'); + } + + Livewire::test('auth.login') + ->set('email', $user->email) + ->set('password', 'password') + ->call('login') + ->assertHasNoErrors(); + + $this->assertAuthenticatedAs($user); +}); + +test('new passwords need at least twelve characters', function () { + /** @var TestCase $this */ + $user = User::factory()->create(['is_active' => true]); + + $this->actingAs($user); + + Livewire::test('customer.security') + ->set('current_password', 'password') + ->set('password', 'kurz-12345') + ->set('password_confirmation', 'kurz-12345') + ->call('updatePassword') + ->assertHasErrors(['password']); + + expect(Hash::check('password', $user->fresh()->password))->toBeTrue(); +}); + +test('in production new passwords are checked against known leaks', function () { + $password = 'korrekt-pferd-batterie'; + $hash = strtoupper(sha1($password)); + + Http::fake(['api.pwnedpasswords.com/range/'.substr($hash, 0, 5) => Http::response(substr($hash, 5).":42\r\n")]); + + app()->instance('env', 'production'); + + try { + expect(Validator::make(['password' => $password], ['password' => Password::defaults()])->fails())->toBeTrue() + ->and(Validator::make(['password' => 'ein-anderes-passwort'], ['password' => Password::defaults()])->fails())->toBeFalse(); + } finally { + app()->instance('env', 'testing'); + } +}); + +test('html responses carry a report-only content security policy when enabled', function () { + /** @var TestCase $this */ + $this->get('https://presseecho.test/de')->assertHeaderMissing('Content-Security-Policy-Report-Only'); + + config()->set('security.csp.report_only', true); + + $policy = $this->get('https://presseecho.test/de') + ->assertHeaderMissing('Content-Security-Policy') + ->headers->get('Content-Security-Policy-Report-Only'); + + expect($policy)->toContain("default-src 'self'") + ->toContain("object-src 'none'") + ->toContain("frame-ancestors 'self'") + ->toContain('report-uri /csp-report'); + + $this->getJson('/api/v1/categories')->assertHeaderMissing('Content-Security-Policy-Report-Only'); +}); + +test('csp reports are logged once per hour without query strings or tokens', function () { + /** @var TestCase $this */ + config()->set('security.csp.report_only', true); + + $logged = []; + Log::shouldReceive('channel')->with('csp')->andReturnSelf(); + Log::shouldReceive('warning')->andReturnUsing(function (string $message, array $context) use (&$logged) { + $logged[] = $context; + }); + + $report = json_encode(['csp-report' => [ + 'document-uri' => 'https://pressekonto.test/magic-login/'.str_repeat('a1B2', 10).'?signature=geheim', + 'effective-directive' => 'script-src-elem', + 'blocked-uri' => 'https://evil.example/x.js?k=1', + 'line-number' => 3, + ]]); + + foreach (range(1, 2) as $i) { + $this->call('POST', '/csp-report', [], [], [], ['CONTENT_TYPE' => 'application/csp-report'], $report)->assertNoContent(); + } + + expect($logged)->toHaveCount(1) + ->and($logged[0]['document'])->toBe('https://pressekonto.test/magic-login/[Filtered]') + ->and($logged[0]['blocked'])->toBe('https://evil.example/x.js') + ->and($logged[0]['directive'])->toBe('script-src-elem'); + + $this->call('POST', '/csp-report', [], [], [], ['CONTENT_TYPE' => 'application/csp-report'], 'kein json')->assertNoContent(); + expect($logged)->toHaveCount(1); +}); diff --git a/tests/TestCase.php b/tests/TestCase.php index 42bd3dd0..0d724a52 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -74,7 +74,7 @@ abstract class TestCase extends BaseTestCase { $testing = config('logging.channels.testing'); - foreach (['billing', 'ki', 'monitoring', 'market'] as $channel) { + foreach (['billing', 'ki', 'monitoring', 'market', 'csp'] as $channel) { config()->set("logging.channels.{$channel}", $testing); } }