security: Andere Geräte abmelden, IP-weites Login-Limit, dauerhafte Sperrmarke, Passwortregeln, CSP im Melde-Modus
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 <noreply@anthropic.com>
This commit is contained in:
parent
9c4962fbe0
commit
5dfd622141
27 changed files with 601 additions and 39 deletions
|
|
@ -353,3 +353,5 @@ IMAGE_PRECHECK_STAGE=1
|
||||||
# HSTS: ohne Angabe nur bei APP_ENV=production an, max-age 1 Jahr.
|
# HSTS: ohne Angabe nur bei APP_ENV=production an, max-age 1 Jahr.
|
||||||
# SECURITY_HSTS=
|
# SECURITY_HSTS=
|
||||||
# SECURITY_HSTS_MAX_AGE=31536000
|
# 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=
|
||||||
|
|
|
||||||
65
app/Http/Controllers/CspReportController.php
Normal file
65
app/Http/Controllers/CspReportController.php
Normal file
|
|
@ -0,0 +1,65 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Response;
|
||||||
|
use Illuminate\Support\Facades\Cache;
|
||||||
|
use Illuminate\Support\Facades\Log;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Nimmt CSP-Meldungen der Browser entgegen (ContentSecurityPolicy, Melde-
|
||||||
|
* Modus) und schreibt sie nach storage/logs/csp-*.log. Gleiche Meldungen
|
||||||
|
* landen höchstens einmal pro Stunde im Log. Adressen werden ohne Query und
|
||||||
|
* ohne tokenartige Pfadsegmente gespeichert — signierte Links und
|
||||||
|
* Anmeldelinks gehören nicht ins Log.
|
||||||
|
*/
|
||||||
|
class CspReportController extends Controller
|
||||||
|
{
|
||||||
|
private const MAX_BYTES = 16384;
|
||||||
|
|
||||||
|
public function __invoke(Request $request): Response
|
||||||
|
{
|
||||||
|
$body = $request->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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -2,6 +2,7 @@
|
||||||
|
|
||||||
namespace App\Http\Middleware;
|
namespace App\Http\Middleware;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
use App\Services\Auth\SessionRevocation;
|
use App\Services\Auth\SessionRevocation;
|
||||||
use Closure;
|
use Closure;
|
||||||
use Illuminate\Auth\SessionGuard;
|
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
|
* Meldet eine Session ab, die vor der letzten Sperre ihres Kontos entstanden
|
||||||
* ist (SessionRevocation, Audit K-04). Kostet je angemeldetem Request einen
|
* ist (SessionRevocation, Audit K-04). Die Marke steht am geladenen User;
|
||||||
* Cache-Zugriff; Gäste lösen keinen aus.
|
* bis zum Release nach v1.6.0 kommt ein Cache-Zugriff dazu (Übergang).
|
||||||
*/
|
*/
|
||||||
class EnsureSessionIsNotRevoked
|
class EnsureSessionIsNotRevoked
|
||||||
{
|
{
|
||||||
|
|
@ -33,7 +34,7 @@ class EnsureSessionIsNotRevoked
|
||||||
|
|
||||||
$user = $guard->user();
|
$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);
|
return $next($request);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@
|
||||||
|
|
||||||
namespace App\Http\Middleware;
|
namespace App\Http\Middleware;
|
||||||
|
|
||||||
|
use App\Support\ContentSecurityPolicy;
|
||||||
use Closure;
|
use Closure;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Symfony\Component\HttpFoundation\Response;
|
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.
|
* Reverse-Proxy gesetzt, damit der Schutz auch bei Proxy-Wechsel bleibt.
|
||||||
* Bereits vorhandene Header (z. B. vom Proxy) werden nicht überschrieben.
|
* Bereits vorhandene Header (z. B. vom Proxy) werden nicht überschrieben.
|
||||||
* HSTS nur auf HTTPS-Antworten und laut config/security.php.
|
* HSTS nur auf HTTPS-Antworten und laut config/security.php.
|
||||||
* CSP fehlt absichtlich: Livewire/Alpine/Vite brauchen eine eigene
|
* CSP vorerst nur im Melde-Modus (ContentSecurityPolicy, config/security.php).
|
||||||
* Inline-Script-Strategie — separat einführen, nicht nebenbei.
|
|
||||||
*/
|
*/
|
||||||
class SecurityHeaders
|
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')) {
|
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'));
|
$response->headers->set('Strict-Transport-Security', 'max-age='.(int) config('security.hsts.max_age'));
|
||||||
}
|
}
|
||||||
|
|
|
||||||
25
app/Listeners/CountFailedLoginsPerIp.php
Normal file
25
app/Listeners/CountFailedLoginsPerIp.php
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Listeners;
|
||||||
|
|
||||||
|
use App\Services\Auth\LoginIpThrottle;
|
||||||
|
use Illuminate\Auth\Events\Failed;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Zählt jede fehlgeschlagene Web-Anmeldung für die IP-weite Obergrenze
|
||||||
|
* (LoginIpThrottle) — gleich, ob über die Livewire-Anmeldung oder Fortifys
|
||||||
|
* `POST /login`.
|
||||||
|
*/
|
||||||
|
class CountFailedLoginsPerIp
|
||||||
|
{
|
||||||
|
public function __construct(private readonly LoginIpThrottle $throttle) {}
|
||||||
|
|
||||||
|
public function handle(Failed $event): void
|
||||||
|
{
|
||||||
|
if ($event->guard !== 'web' || ! app()->bound('request')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->throttle->recordFailure(request()->ip());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -87,6 +87,7 @@ class User extends Authenticatable implements MustVerifyEmail, PasskeyUser
|
||||||
'deleted_at' => 'datetime',
|
'deleted_at' => 'datetime',
|
||||||
'password' => 'hashed',
|
'password' => 'hashed',
|
||||||
'press_release_quota_used_this_month' => 'integer',
|
'press_release_quota_used_this_month' => 'integer',
|
||||||
|
'sessions_revoked_at_ms' => 'integer',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -66,6 +66,7 @@ use Illuminate\Support\Facades\Gate;
|
||||||
use Illuminate\Support\Facades\Queue;
|
use Illuminate\Support\Facades\Queue;
|
||||||
use Illuminate\Support\Facades\URL;
|
use Illuminate\Support\Facades\URL;
|
||||||
use Illuminate\Support\ServiceProvider;
|
use Illuminate\Support\ServiceProvider;
|
||||||
|
use Illuminate\Validation\Rules\Password;
|
||||||
use Laravel\Cashier\Cashier;
|
use Laravel\Cashier\Cashier;
|
||||||
use Laravel\Fortify\Events\TwoFactorAuthenticationFailed;
|
use Laravel\Fortify\Events\TwoFactorAuthenticationFailed;
|
||||||
use Livewire\Livewire;
|
use Livewire\Livewire;
|
||||||
|
|
@ -108,6 +109,18 @@ class AppServiceProvider extends ServiceProvider
|
||||||
// Ausgelieferte Version in `php artisan about` (Datei RELEASE bzw. APP_VERSION).
|
// Ausgelieferte Version in `php artisan about` (Datei RELEASE bzw. APP_VERSION).
|
||||||
AboutCommand::add('Pressekonto', fn (): array => ['Version' => config('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.
|
// Die Generations-Nummer der Seiten-Caches wird prozessintern gemerkt.
|
||||||
// Ein Queue-Worker lebt über beliebig viele Jobs hinweg und würde sonst
|
// Ein Queue-Worker lebt über beliebig viele Jobs hinweg und würde sonst
|
||||||
// dauerhaft mit dem Stand seines ersten Zugriffs arbeiten — Keys einer
|
// dauerhaft mit dem Stand seines ersten Zugriffs arbeiten — Keys einer
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@ use App\Http\Responses\FailedTwoFactorChallengeResponse;
|
||||||
use App\Http\Responses\PasskeyLoginResponse;
|
use App\Http\Responses\PasskeyLoginResponse;
|
||||||
use App\Http\Responses\RoleAwareLoginResponse;
|
use App\Http\Responses\RoleAwareLoginResponse;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Services\Auth\LoginIpThrottle;
|
||||||
use Illuminate\Cache\RateLimiting\Limit;
|
use Illuminate\Cache\RateLimiting\Limit;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\RateLimiter;
|
use Illuminate\Support\Facades\RateLimiter;
|
||||||
|
|
@ -53,6 +54,20 @@ class FortifyServiceProvider extends ServiceProvider
|
||||||
// Keine View-Definitionen, die Auth-Seiten sind Livewire-Komponenten
|
// Keine View-Definitionen, die Auth-Seiten sind Livewire-Komponenten
|
||||||
|
|
||||||
RateLimiter::for('login', function (Request $request) {
|
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());
|
$throttleKey = Str::transliterate(Str::lower($request->input(Fortify::username())).'|'.$request->ip());
|
||||||
|
|
||||||
return Limit::perMinute(5)->by($throttleKey);
|
return Limit::perMinute(5)->by($throttleKey);
|
||||||
|
|
|
||||||
43
app/Services/Auth/LoginIpThrottle.php
Normal file
43
app/Services/Auth/LoginIpThrottle.php
Normal file
|
|
@ -0,0 +1,43 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Auth;
|
||||||
|
|
||||||
|
use Illuminate\Support\Facades\RateLimiter;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Obergrenze für fehlgeschlagene Anmeldungen je IP-Adresse über alle Konten
|
||||||
|
* hinweg (Sicherheitsaudit 07.10.2026, Phase 4). Das Limit je Adresse und IP
|
||||||
|
* (5 pro Minute) bremst kein Durchprobieren vieler fremder Adressen von einer
|
||||||
|
* Quelle — davon kamen laut Monitoring rund 250 Versuche am Tag. Gezählt
|
||||||
|
* wird über das `Failed`-Event, damit Livewire-Anmeldung und Fortifys
|
||||||
|
* `POST /login` denselben Zähler teilen. Erfolgreiche Anmeldungen setzen ihn
|
||||||
|
* bewusst nicht zurück — sonst reichte ein eigenes Konto zum Entsperren.
|
||||||
|
* Wirkt erst, seit gefälschte X-Forwarded-For-Header ignoriert werden
|
||||||
|
* (config/trustedproxy.php).
|
||||||
|
*/
|
||||||
|
class LoginIpThrottle
|
||||||
|
{
|
||||||
|
public const MAX_FAILURES = 20;
|
||||||
|
|
||||||
|
public const DECAY_SECONDS = 900;
|
||||||
|
|
||||||
|
public function recordFailure(?string $ip): void
|
||||||
|
{
|
||||||
|
RateLimiter::hit($this->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');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -6,6 +6,7 @@ use App\Models\User;
|
||||||
use Illuminate\Auth\Events\Login;
|
use Illuminate\Auth\Events\Login;
|
||||||
use Illuminate\Contracts\Session\Session;
|
use Illuminate\Contracts\Session\Session;
|
||||||
use Illuminate\Support\Facades\Cache;
|
use Illuminate\Support\Facades\Cache;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Beendet alle offenen Browser-Sessions eines Kontos (Umsetzungsaudit
|
* 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
|
* ein Zeitstempel je Konto: Jede Anmeldung schreibt ihren Zeitpunkt in die
|
||||||
* Session (`Login`-Event), `revokeAllFor()` merkt sich „ungültig vor jetzt",
|
* Session (`Login`-Event), `revokeAllFor()` merkt sich „ungültig vor jetzt",
|
||||||
* und die Middleware EnsureSessionIsNotRevoked meldet jede ältere Session
|
* und die Middleware EnsureSessionIsNotRevoked meldet jede ältere Session
|
||||||
* beim nächsten Request ab. Die Marke lebt so lange wie eine Session
|
* beim nächsten Request ab. Remember-Cookies deckt das Rotieren von
|
||||||
* (`session.lifetime`) — danach ist jede ältere Session ohnehin abgelaufen.
|
* `remember_token` ab, API-Tokens löscht der Aufrufer.
|
||||||
* 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
|
class SessionRevocation
|
||||||
{
|
{
|
||||||
|
|
@ -35,11 +38,10 @@ class SessionRevocation
|
||||||
{
|
{
|
||||||
$revokedAt = now()->getTimestampMs();
|
$revokedAt = now()->getTimestampMs();
|
||||||
|
|
||||||
Cache::put(
|
// Ohne Model-Events und ohne updated_at: Die Marke ist keine
|
||||||
$this->cacheKey((int) $user->getKey()),
|
// inhaltliche Änderung am Konto und soll keine Observer auslösen.
|
||||||
$revokedAt,
|
$user->newQuery()->whereKey($user->getKey())->update(['sessions_revoked_at_ms' => $revokedAt]);
|
||||||
now()->addMinutes(max(1, (int) config('session.lifetime', 120)) + 5),
|
$user->forceFill(['sessions_revoked_at_ms' => $revokedAt])->syncOriginalAttribute('sessions_revoked_at_ms');
|
||||||
);
|
|
||||||
|
|
||||||
return $revokedAt;
|
return $revokedAt;
|
||||||
}
|
}
|
||||||
|
|
@ -57,6 +59,18 @@ class SessionRevocation
|
||||||
$current->migrate(true);
|
$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.
|
* Listener für `Login`: Zeitpunkt der Anmeldung in der Session.
|
||||||
* Die Methode heißt bewusst nicht `handle*` (Event-Discovery).
|
* 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.
|
* Session stammt aus der Zeit vor der letzten Sperre dieses Kontos.
|
||||||
* Ohne Anmeldezeitpunkt (Session von vor dem Deploy) gilt sie als alt.
|
* 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 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
73
app/Support/ContentSecurityPolicy.php
Normal file
73
app/Support/ContentSecurityPolicy.php
Normal file
|
|
@ -0,0 +1,73 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Support;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Content Security Policy, vorerst nur im Melde-Modus
|
||||||
|
* (`Content-Security-Policy-Report-Only`, Sicherheitsaudit 07.10.2026,
|
||||||
|
* Phase 4). Browser blockieren nichts, sondern melden Verstöße an
|
||||||
|
* `/csp-report` (storage/logs/csp-*.log). Erst wenn die Meldungen zeigen,
|
||||||
|
* dass die Liste vollständig ist, wird sie scharf geschaltet.
|
||||||
|
*
|
||||||
|
* `'unsafe-inline'` und `'unsafe-eval'` sind für Livewire/Alpine und die
|
||||||
|
* Inline-Skripte der Layouts vorerst nötig; die Policy begrenzt daher vor
|
||||||
|
* allem, von wo Skripte geladen und wohin Daten geschickt werden dürfen,
|
||||||
|
* sowie Einbettung, Formularziele und `<base>`.
|
||||||
|
*/
|
||||||
|
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<string>
|
||||||
|
*/
|
||||||
|
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'] : '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
use App\Http\Controllers\CspReportController;
|
||||||
use App\Http\Controllers\HealthController;
|
use App\Http\Controllers\HealthController;
|
||||||
use App\Http\Middleware\BasicAuthMiddleware;
|
use App\Http\Middleware\BasicAuthMiddleware;
|
||||||
use App\Http\Middleware\EnsureSessionIsNotRevoked;
|
use App\Http\Middleware\EnsureSessionIsNotRevoked;
|
||||||
|
|
@ -12,6 +13,7 @@ use App\Http\Middleware\ReportErrorSignals;
|
||||||
use App\Http\Middleware\SecurityHeaders;
|
use App\Http\Middleware\SecurityHeaders;
|
||||||
use App\Http\Middleware\SetCurrentPortal;
|
use App\Http\Middleware\SetCurrentPortal;
|
||||||
use App\Http\Middleware\SetEdition;
|
use App\Http\Middleware\SetEdition;
|
||||||
|
use App\Support\ContentSecurityPolicy;
|
||||||
use Illuminate\Foundation\Application;
|
use Illuminate\Foundation\Application;
|
||||||
use Illuminate\Foundation\Configuration\Exceptions;
|
use Illuminate\Foundation\Configuration\Exceptions;
|
||||||
use Illuminate\Foundation\Configuration\Middleware;
|
use Illuminate\Foundation\Configuration\Middleware;
|
||||||
|
|
@ -38,6 +40,12 @@ return Application::configure(basePath: dirname(__DIR__))
|
||||||
Route::get('/health', HealthController::class)
|
Route::get('/health', HealthController::class)
|
||||||
->middleware('throttle:30,1')
|
->middleware('throttle:30,1')
|
||||||
->name('health.deep');
|
->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) {
|
->withMiddleware(function (Middleware $middleware) {
|
||||||
|
|
|
||||||
|
|
@ -116,6 +116,9 @@ return [
|
||||||
|
|
||||||
'market' => $topicChannel('market'),
|
'market' => $topicChannel('market'),
|
||||||
|
|
||||||
|
// CSP-Meldungen der Browser (Melde-Modus, CspReportController).
|
||||||
|
'csp' => $topicChannel('csp'),
|
||||||
|
|
||||||
'admin_slow' => [
|
'admin_slow' => [
|
||||||
'driver' => 'daily',
|
'driver' => 'daily',
|
||||||
'path' => storage_path('logs/admin-slow.log'),
|
'path' => storage_path('logs/admin-slow.log'),
|
||||||
|
|
|
||||||
|
|
@ -20,4 +20,20 @@ return [
|
||||||
'max_age' => (int) env('SECURITY_HSTS_MAX_AGE', 31536000),
|
'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'),
|
||||||
|
],
|
||||||
|
|
||||||
];
|
];
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,30 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sperrmarke für Browser-Sessions dauerhaft am Konto (Sicherheitsaudit
|
||||||
|
* 07.10.2026, Phase 4). Bisher lag sie nur im Cache — ein Leeren des Caches
|
||||||
|
* hätte beendete Sessions wieder gültig gemacht. Millisekunden wie der
|
||||||
|
* Anmeldezeitpunkt in der Session (SessionRevocation::SESSION_KEY).
|
||||||
|
* `users` trägt FULLTEXT-Indizes (ALGORITHM=COPY), ist aber klein genug für
|
||||||
|
* einen Umbau in Sekunden (CLAUDE.md, Schema changes).
|
||||||
|
*/
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('users', function (Blueprint $table) {
|
||||||
|
$table->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');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
@ -48,9 +48,10 @@
|
||||||
<server name="MONITORING_NTFY_URL" value="" force="true"/>
|
<server name="MONITORING_NTFY_URL" value="" force="true"/>
|
||||||
<server name="MONITORING_NTFY_TOPIC" value="" force="true"/>
|
<server name="MONITORING_NTFY_TOPIC" value="" force="true"/>
|
||||||
<server name="MONITORING_NTFY_TOKEN" value="" force="true"/>
|
<server name="MONITORING_NTFY_TOKEN" value="" force="true"/>
|
||||||
<!-- Proxy-Vertrauen und HSTS testen die Tests selbst; Standard wie auf Live. -->
|
<!-- Proxy-Vertrauen, HSTS und CSP testen die Tests selbst. -->
|
||||||
<env name="TRUSTED_PROXIES" value="" force="true"/>
|
<env name="TRUSTED_PROXIES" value="" force="true"/>
|
||||||
<env name="SECURITY_HSTS" value="false" force="true"/>
|
<env name="SECURITY_HSTS" value="false" force="true"/>
|
||||||
|
<env name="SECURITY_CSP_REPORT_ONLY" value="false" force="true"/>
|
||||||
<env name="MAIL_MAILER" value="array"/>
|
<env name="MAIL_MAILER" value="array"/>
|
||||||
<env name="PULSE_ENABLED" value="false"/>
|
<env name="PULSE_ENABLED" value="false"/>
|
||||||
<env name="QUEUE_CONNECTION" value="sync"/>
|
<env name="QUEUE_CONNECTION" value="sync"/>
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@
|
||||||
|
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Services\Auth\LoginCompletion;
|
use App\Services\Auth\LoginCompletion;
|
||||||
|
use App\Services\Auth\LoginIpThrottle;
|
||||||
use App\Support\LoginRedirect;
|
use App\Support\LoginRedirect;
|
||||||
use Illuminate\Auth\Events\Failed;
|
use Illuminate\Auth\Events\Failed;
|
||||||
use Illuminate\Auth\Events\Lockout;
|
use Illuminate\Auth\Events\Lockout;
|
||||||
|
|
@ -99,7 +100,12 @@ new #[Layout('components.layouts.auth.pressekonto', ['heading' => 'Willkommen zu
|
||||||
*/
|
*/
|
||||||
protected function ensureIsNotRateLimited(): void
|
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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -107,7 +113,9 @@ new #[Layout('components.layouts.auth.pressekonto', ['heading' => 'Willkommen zu
|
||||||
// für den Aktivitäts-Verlauf mitgeben.
|
// für den Aktivitäts-Verlauf mitgeben.
|
||||||
event(new Lockout(request()->duplicate(request: ['email' => $this->email])));
|
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([
|
throw ValidationException::withMessages([
|
||||||
'email' => __('auth.throttle', [
|
'email' => __('auth.throttle', [
|
||||||
|
|
|
||||||
|
|
@ -117,7 +117,7 @@ new #[Layout('components.layouts.auth.pressekonto', ['heading' => 'Konto erstell
|
||||||
name="password"
|
name="password"
|
||||||
:label="__('Passwort')"
|
:label="__('Passwort')"
|
||||||
autocomplete="new-password"
|
autocomplete="new-password"
|
||||||
:placeholder="__('Mindestens 8 Zeichen')"
|
:placeholder="__('Mindestens 12 Zeichen')"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<x-password-input
|
<x-password-input
|
||||||
|
|
|
||||||
|
|
@ -69,7 +69,7 @@ new #[Layout('components.layouts.auth.pressekonto', ['heading' => 'Neues Passwor
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<p class="text-[13.5px] text-ink-2 leading-[1.6] !-mt-4 mb-6">
|
<p class="text-[13.5px] text-ink-2 leading-[1.6] !-mt-4 mb-6">
|
||||||
{{ __('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.') }}
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<form wire:submit="resetPassword" class="space-y-[18px]" novalidate>
|
<form wire:submit="resetPassword" class="space-y-[18px]" novalidate>
|
||||||
|
|
@ -94,7 +94,7 @@ new #[Layout('components.layouts.auth.pressekonto', ['heading' => 'Neues Passwor
|
||||||
name="password"
|
name="password"
|
||||||
:label="__('Neues Passwort')"
|
:label="__('Neues Passwort')"
|
||||||
autocomplete="new-password"
|
autocomplete="new-password"
|
||||||
:placeholder="__('Mindestens 8 Zeichen')"
|
:placeholder="__('Mindestens 12 Zeichen')"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<x-password-input
|
<x-password-input
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@ use App\Mail\EmailChangeConfirmation;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Services\Auth\PasswordChanger;
|
use App\Services\Auth\PasswordChanger;
|
||||||
use App\Services\Auth\SecurityNotifier;
|
use App\Services\Auth\SecurityNotifier;
|
||||||
|
use App\Services\Auth\SessionRevocation;
|
||||||
use App\Services\Auth\StrongAuthentication;
|
use App\Services\Auth\StrongAuthentication;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Auth;
|
use Illuminate\Support\Facades\Auth;
|
||||||
|
|
@ -255,6 +256,20 @@ new #[Layout('components.layouts.app'), Title('Konto-Sicherheit')] class extends
|
||||||
session()->flash('security-status', __('Passkey entfernt.'));
|
session()->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
|
private function ensureNotImpersonating(): void
|
||||||
{
|
{
|
||||||
abort_if(app(UserImpersonation::class)->isActive(), 403, __('Während der Benutzer-Impersonation können keine Passkeys verwaltet werden.'));
|
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
|
||||||
</div>
|
</div>
|
||||||
<form wire:submit="updatePassword" class="p-5 space-y-4">
|
<form wire:submit="updatePassword" class="p-5 space-y-4">
|
||||||
<flux:input wire:model="current_password" type="password" :label="__('Aktuelles Passwort')" autocomplete="current-password" required />
|
<flux:input wire:model="current_password" type="password" :label="__('Aktuelles Passwort')" autocomplete="current-password" required />
|
||||||
<flux:input wire:model="password" type="password" :label="__('Neues Passwort')" autocomplete="new-password" required />
|
<flux:input wire:model="password" type="password" :label="__('Neues Passwort')" :description:trailing="__('Mindestens 12 Zeichen.')" autocomplete="new-password" required />
|
||||||
<flux:input wire:model="password_confirmation" type="password" :label="__('Neues Passwort bestätigen')" autocomplete="new-password" required />
|
<flux:input wire:model="password_confirmation" type="password" :label="__('Neues Passwort bestätigen')" autocomplete="new-password" required />
|
||||||
<div class="flex justify-end pt-2 border-t border-[color:var(--color-bg-rule)]">
|
<div class="flex justify-end pt-2 border-t border-[color:var(--color-bg-rule)]">
|
||||||
<flux:button type="submit" variant="primary">{{ __('Passwort speichern') }}</flux:button>
|
<flux:button type="submit" variant="primary">{{ __('Passwort speichern') }}</flux:button>
|
||||||
|
|
@ -598,10 +613,15 @@ new #[Layout('components.layouts.app'), Title('Konto-Sicherheit')] class extends
|
||||||
{{ $sessions->count() }} {{ __('Einträge') }}
|
{{ $sessions->count() }} {{ __('Einträge') }}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="px-5 pb-2 pt-3">
|
<div class="flex flex-col gap-3 px-5 pb-2 pt-3 sm:flex-row sm:items-center sm:justify-between">
|
||||||
<p class="text-[12.5px] text-[color:var(--color-ink-3)] m-0">
|
<p class="text-[12.5px] text-[color:var(--color-ink-3)] m-0 max-w-[560px]">
|
||||||
{{ __('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.') }}
|
||||||
</p>
|
</p>
|
||||||
|
<flux:button size="sm" variant="filled" icon="arrow-right-start-on-rectangle"
|
||||||
|
wire:click="logoutOtherDevices"
|
||||||
|
wire:confirm="{{ __('Alle anderen Geräte abmelden?') }}">
|
||||||
|
{{ __('Andere Geräte abmelden') }}
|
||||||
|
</flux:button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="divide-y divide-[color:var(--color-bg-rule)]">
|
<div class="divide-y divide-[color:var(--color-bg-rule)]">
|
||||||
|
|
|
||||||
|
|
@ -25,8 +25,8 @@ test('a self registration is recorded in the activity log', function () {
|
||||||
Livewire::test('auth.register')
|
Livewire::test('auth.register')
|
||||||
->set('name', 'Verlauf Tester')
|
->set('name', 'Verlauf Tester')
|
||||||
->set('email', 'verlauf@example.com')
|
->set('email', 'verlauf@example.com')
|
||||||
->set('password', 'password')
|
->set('password', 'sicheres-passwort-2026')
|
||||||
->set('password_confirmation', 'password')
|
->set('password_confirmation', 'sicheres-passwort-2026')
|
||||||
->set('terms_accepted', true)
|
->set('terms_accepted', true)
|
||||||
->call('register');
|
->call('register');
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,14 @@
|
||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
use App\Actions\Admin\UserImpersonation;
|
||||||
use App\Enums\SecurityChange;
|
use App\Enums\SecurityChange;
|
||||||
use App\Mail\SecurityChangeNotice;
|
use App\Mail\SecurityChangeNotice;
|
||||||
use App\Models\MagicLink;
|
use App\Models\MagicLink;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Services\Auth\SessionRevocation;
|
use App\Services\Auth\SessionRevocation;
|
||||||
use Database\Seeders\RolesAndPermissionsSeeder;
|
use Database\Seeders\RolesAndPermissionsSeeder;
|
||||||
|
use Illuminate\Support\Facades\Cache;
|
||||||
|
use Illuminate\Support\Facades\Hash;
|
||||||
use Illuminate\Support\Facades\Mail;
|
use Illuminate\Support\Facades\Mail;
|
||||||
use Illuminate\Support\Facades\Password;
|
use Illuminate\Support\Facades\Password;
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
@ -131,3 +134,71 @@ test('livewire requests pass the session revocation check', function () {
|
||||||
expect($route)->not->toBeNull()
|
expect($route)->not->toBeNull()
|
||||||
->and($route->gatherMiddleware())->toContain('web');
|
->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();
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -53,8 +53,8 @@ test('password can be reset with valid token', function () {
|
||||||
Notification::assertSentTo($user, ResetPassword::class, function ($notification) use ($user) {
|
Notification::assertSentTo($user, ResetPassword::class, function ($notification) use ($user) {
|
||||||
$response = Livewire::test('auth.reset-password', ['token' => $notification->token])
|
$response = Livewire::test('auth.reset-password', ['token' => $notification->token])
|
||||||
->set('email', $user->email)
|
->set('email', $user->email)
|
||||||
->set('password', 'password')
|
->set('password', 'sicheres-passwort-2026')
|
||||||
->set('password_confirmation', 'password')
|
->set('password_confirmation', 'sicheres-passwort-2026')
|
||||||
->call('resetPassword');
|
->call('resetPassword');
|
||||||
|
|
||||||
$response
|
$response
|
||||||
|
|
|
||||||
|
|
@ -25,8 +25,8 @@ test('new users register inactive and are sent to the verification notice', func
|
||||||
Livewire::test('auth.register')
|
Livewire::test('auth.register')
|
||||||
->set('name', 'Test User')
|
->set('name', 'Test User')
|
||||||
->set('email', 'test@example.com')
|
->set('email', 'test@example.com')
|
||||||
->set('password', 'password')
|
->set('password', 'sicheres-passwort-2026')
|
||||||
->set('password_confirmation', 'password')
|
->set('password_confirmation', 'sicheres-passwort-2026')
|
||||||
->set('terms_accepted', true)
|
->set('terms_accepted', true)
|
||||||
->call('register')
|
->call('register')
|
||||||
->assertHasNoErrors()
|
->assertHasNoErrors()
|
||||||
|
|
@ -55,8 +55,8 @@ test('registration requires accepting the terms', function () {
|
||||||
Livewire::test('auth.register')
|
Livewire::test('auth.register')
|
||||||
->set('name', 'Test User')
|
->set('name', 'Test User')
|
||||||
->set('email', 'terms@example.com')
|
->set('email', 'terms@example.com')
|
||||||
->set('password', 'password')
|
->set('password', 'sicheres-passwort-2026')
|
||||||
->set('password_confirmation', 'password')
|
->set('password_confirmation', 'sicheres-passwort-2026')
|
||||||
->set('terms_accepted', false)
|
->set('terms_accepted', false)
|
||||||
->call('register')
|
->call('register')
|
||||||
->assertHasErrors(['terms_accepted']);
|
->assertHasErrors(['terms_accepted']);
|
||||||
|
|
|
||||||
|
|
@ -27,6 +27,7 @@ test('every topic channel writes its own daily file with the shared retention',
|
||||||
'ki' => ['ki', 'ki'],
|
'ki' => ['ki', 'ki'],
|
||||||
'monitoring' => ['monitoring', 'monitoring'],
|
'monitoring' => ['monitoring', 'monitoring'],
|
||||||
'market' => ['market', 'market'],
|
'market' => ['market', 'market'],
|
||||||
|
'csp' => ['csp', 'csp'],
|
||||||
'admin_slow' => ['admin_slow', 'admin-slow'],
|
'admin_slow' => ['admin_slow', 'admin-slow'],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,12 +2,18 @@
|
||||||
|
|
||||||
use App\Models\Company;
|
use App\Models\Company;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Services\Auth\LoginIpThrottle;
|
||||||
use Database\Seeders\RolesAndPermissionsSeeder;
|
use Database\Seeders\RolesAndPermissionsSeeder;
|
||||||
use Illuminate\Http\UploadedFile;
|
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\Process;
|
||||||
use Illuminate\Support\Facades\RateLimiter;
|
use Illuminate\Support\Facades\RateLimiter;
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
use Illuminate\Support\Facades\Storage;
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Illuminate\Support\Facades\Validator;
|
||||||
|
use Illuminate\Validation\Rules\Password;
|
||||||
use Livewire\Livewire;
|
use Livewire\Livewire;
|
||||||
use Tests\TestCase;
|
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.topic'))->toBeEmpty()
|
||||||
->and(config('monitoring.alerts.ntfy.token'))->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);
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -74,7 +74,7 @@ abstract class TestCase extends BaseTestCase
|
||||||
{
|
{
|
||||||
$testing = config('logging.channels.testing');
|
$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);
|
config()->set("logging.channels.{$channel}", $testing);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue