Beschriftung const AUDIT_AREAS = [ 'users' => 'Benutzer & Rechte', 'security' => 'Sicherheit', 'raids' => 'Raids', 'premades' => 'Premades', 'events' => 'Events', 'map' => 'Karte', 'warehouse' => 'Lagerhaus', 'contributions' => 'Lumipunkte', 'shop' => 'Lumishop', 'dues' => 'Legionsbeiträge', 'members' => 'Profile', 'wiki' => 'Wiki', 'gear' => 'Gear-Planer', 'reports' => 'Reports', 'bugs' => 'Fehlermeldungen', 'site' => 'Wartung & Ankündigung', 'discord' => 'Discord-Bot', 'other' => 'Sonstiges', ]; // Tempolimits: Art => [hoechstens, in Sekunden] const SECURITY_LIMITS = [ 'post' => [120, 300], // abgeschickte Formulare/Aktionen pro Konto 'gear' => [1200, 300], // automatisches Speichern im Gear-Planer pro Konto (eigener Topf, statt "post") 'upload' => [30, 600], // hochgeladene Bilder pro Konto 'comment' => [6, 300], // Kommentare unter Galeriebildern pro Konto 'report' => [10, 600], // Meldungen (Melden-Knopf) pro Konto 'reaction' => [60, 300], // Reaktionen (Emojis) pro Konto 'calendar' => [8, 3600], // eigene Kalender-Termine pro Konto 'bug' => [5, 3600], // Fehlermeldungen pro Konto 'discord_sync' => [10, 3600], // "Jetzt mit Discord abgleichen" im Profil pro Konto (dazu hoechstens alle 30 s) 'export' => [6, 3600], // Datenauskunft herunterladen (eigene oder fuer andere) pro Konto 'armory' => [40, 600], // Charaktersuche bei NCSoft (Live-Daten der Profilseiten) pro Konto 'login_ip' => [15, 900], // fehlgeschlagene Logins pro IP (egal welches Konto) 'login_pair' => [5, 900], // fehlgeschlagene Logins pro IP + Benutzername 'destructive' => [20, 600], // Loeschungen pro Konto, danach automatische Sperre ]; // Diese Skripte schicken im Hintergrund viele kleine Anfragen (Zeichnen, Tour, Bot, Gear-Abgleich) - kein Tempolimit. const SECURITY_POST_EXEMPT = ['bot_api.php', 'tactics_api.php', 'tour_action.php', 'gear_items_action.php']; // Der Gear-Planer speichert jede Aenderung sofort (gear_action.php): Slots, Skills, Seiten wie Daevanion, Makros. // Wer ein Brett durchklickt oder Skills hochstuft, kaeme schnell an "post" - diese Aktionen zaehlen deshalb im Topf "gear". const SECURITY_GEAR_AUTOSAVE = ['save_slot', 'save_skills', 'save_plan', 'save_macro']; /** Bereich einer Aktion anhand des aufgerufenen Skripts (raid_delete_action.php -> raids). */ function audit_area_for_script(string $script): string { $name = basename($script, '.php'); $prefixes = [ 'raid' => 'raids', 'premade' => 'premades', 'event' => 'events', 'tactics' => 'map', 'map' => 'map', 'warehouse' => 'warehouse', 'contributions' => 'contributions', 'shop' => 'shop', 'dues' => 'dues', 'member' => 'members', 'gallery' => 'members', 'moderation' => 'members', 'reaction' => 'members', 'calendar' => 'events', 'wiki' => 'wiki', 'gear' => 'gear', 'report' => 'reports', 'bug' => 'bugs', 'user' => 'users', 'role' => 'users', 'discord' => 'users', 'settings' => 'users', 'consilium' => 'users', 'site' => 'site', 'announcement' => 'site', 'bot' => 'discord', ]; foreach ($prefixes as $prefix => $area) { if (strpos($name, $prefix) === 0) { return $area; } } return 'other'; } /** IP des Besuchers, gekuerzt (IPv4: letzter Block 0, IPv6: nur die ersten vier Bloecke). */ function client_ip_masked(): ?string { $ip = (string) ($_SERVER['REMOTE_ADDR'] ?? ''); if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { return preg_replace('/\.\d+$/', '.0', $ip); } if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { return implode(':', array_slice(explode(':', $ip), 0, 4)) . '::'; } return null; } /** Schluessel fuer die IP in den Tempolimits (gehasht, die Tabelle wird nach 2 Tagen geleert). */ function client_ip_key(): string { return substr(hash('sha256', 'ip|' . ($_SERVER['REMOTE_ADDR'] ?? '')), 0, 40); } /** * Discord-Codes im Text lesbar machen: Rollen (<@&id>) werden ueber die verknuepften * Berechtigungsgruppen benannt, Kanaele (<#id>) und einzelne Nutzer (<@id>) bekommen einen * Klartext statt der rohen Syntax. */ function audit_readable_discord(string $value): string { $value = preg_replace_callback('/<@&(\d+)>/', static function (array $m): string { try { $stmt = db()->prepare("SELECT COALESCE(NULLIF(display_name, ''), name) FROM roles WHERE discord_role_id = ?"); $stmt->execute([$m[1]]); $name = $stmt->fetchColumn(); } catch (PDOException $e) { $name = false; } return $name !== false ? '@' . $name : 'Discord-Rolle ' . $m[1]; }, $value) ?? $value; $value = preg_replace('/<#(\d+)>/', 'Kanal-ID $1', $value) ?? $value; return preg_replace_callback('/<@!?(\d+)>/', static fn (array $m): string => function_exists('admin_log_discord_name') ? admin_log_discord_name($m[1]) : 'Discord-ID ' . $m[1], $value) ?? $value; } // So lange bleiben Eintraege im Audit-Log (steht so in der Datenschutzerklaerung) const AUDIT_LOG_KEEP_MONTHS = 12; /** * Eintrag ins Audit-Log. Discord-Erwaehnungen "(<@123>)" hinter einem Namen werden entfernt, * uebrige Discord-Codes lesbar gemacht (audit_readable_discord). * * @param array $fields */ function audit_store(string $title, array $fields, string $tone, ?string $area = null, ?array $actor = null): void { $actor = $actor ?? current_user(); $clean = []; foreach ($fields as $name => $value) { $value = trim(audit_readable_discord(preg_replace('/\s*\(<@!?\d+>\)/', '', (string) $value) ?? '')); if ($value !== '') { $clean[(string) $name] = mb_substr($value, 0, 1000); } } $actorName = ''; if ($actor) { $actorName = ($actor['display_name'] ?? '') !== '' ? (string) $actor['display_name'] : (string) ($actor['username'] ?? ''); } try { db()->prepare( 'INSERT INTO audit_log (user_id, actor_name, area, title, details, tone, ip) VALUES (?, ?, ?, ?, ?, ?, ?)' )->execute([ !empty($actor['id']) ? (int) $actor['id'] : null, // ohne id: System (z.B. abgelaufene Loeschfrist) mb_substr($actorName, 0, 100), $area ?? audit_area_for_script((string) ($_SERVER['SCRIPT_NAME'] ?? '')), mb_substr($title, 0, 256), $clean ? json_encode($clean, JSON_UNESCAPED_UNICODE) : null, $tone, client_ip_masked(), ]); // Nebenbei aufraeumen: Eintraege aelter als AUDIT_LOG_KEEP_MONTHS (Speicherdauer laut datenschutz.php) if (random_int(1, 50) === 1) { db()->prepare('DELETE FROM audit_log WHERE created_at < ?') ->execute([date('Y-m-d H:i:s', (int) strtotime('-' . AUDIT_LOG_KEEP_MONTHS . ' months'))]); } } catch (PDOException $e) { // Tabelle fehlt (noch) - die eigentliche Aktion soll daran nicht scheitern. } } /** Sicherheitsereignis: Audit-Log (Bereich "Sicherheit") und Discord-Log. */ function security_log(string $title, array $fields = [], string $tone = 'warning', ?array $actor = null): void { admin_log($title, $fields, $tone, 'security', $actor); } // ---- Tempolimits ---- function rate_limit_count(string $bucket, string $subject, int $windowSeconds): int { try { $stmt = db()->prepare( 'SELECT COUNT(*) FROM rate_limits WHERE bucket = ? AND subject = ? AND created_at > ?' ); $stmt->execute([$bucket, $subject, date('Y-m-d H:i:s', time() - $windowSeconds)]); return (int) $stmt->fetchColumn(); } catch (PDOException $e) { return 0; } } function rate_limit_add(string $bucket, string $subject, int $times = 1): void { try { $insert = db()->prepare('INSERT INTO rate_limits (bucket, subject) VALUES (?, ?)'); for ($i = 0; $i < $times; $i++) { $insert->execute([$bucket, $subject]); } // Ab und zu aufraeumen - laenger als zwei Tage braucht kein Limit zurueckzuschauen. if (random_int(1, 50) === 1) { db()->prepare('DELETE FROM rate_limits WHERE created_at < ?')->execute([date('Y-m-d H:i:s', time() - 172800)]); } } catch (PDOException $e) { // Tabelle fehlt (noch) } } /** * Prueft ein Tempolimit fuer das angemeldete Konto und zaehlt die Aktion mit. * Beim ersten Ueberschreiten im Zeitfenster gibt es einen Eintrag im Audit- und Discord-Log. * * @return bool true = erlaubt */ function security_throttle(string $bucket, int $amount = 1): bool { $user = current_user(); if (!$user || !isset(SECURITY_LIMITS[$bucket])) { return true; } [$max, $window] = SECURITY_LIMITS[$bucket]; $subject = 'u' . (int) $user['id']; if (rate_limit_count($bucket, $subject, $window) + $amount > $max) { if (rate_limit_count('notice_' . $bucket, $subject, $window) === 0) { rate_limit_add('notice_' . $bucket, $subject); security_log('⏱️ Tempolimit erreicht', [ 'Art' => security_bucket_label($bucket), 'Limit' => $max . ' in ' . round($window / 60) . ' Minuten', 'Seite' => basename((string) ($_SERVER['SCRIPT_NAME'] ?? '')), ]); } return false; } rate_limit_add($bucket, $subject, $amount); return true; } function security_bucket_label(string $bucket): string { return [ 'post' => 'Aktionen/Formulare', 'gear' => 'Gear-Planer (automatisches Speichern)', 'upload' => 'Bilder hochladen', 'comment' => 'Kommentare', 'report' => 'Meldungen', 'reaction' => 'Reaktionen', 'calendar' => 'Kalender-Termine', 'bug' => 'Fehlermeldungen', 'discord_sync' => 'Discord-Abgleich im Profil', 'export' => 'Datenauskunft herunterladen', 'armory' => 'Charaktersuche (Aion 2)', 'destructive' => 'Löschungen', ][$bucket] ?? $bucket; } /** Meldung und zurueck zur vorigen Seite (bzw. JSON-Fehler bei Hintergrund-Anfragen). */ function security_reject(string $message): void { $accept = (string) ($_SERVER['HTTP_ACCEPT'] ?? ''); if (stripos($accept, 'application/json') !== false || !empty($_SERVER['HTTP_X_REQUESTED_WITH'])) { http_response_code(429); header('Content-Type: application/json; charset=UTF-8'); echo json_encode(['ok' => false, 'error' => $message], JSON_UNESCAPED_UNICODE); exit; } set_flash('error', $message); $back = (string) ($_SERVER['HTTP_REFERER'] ?? ''); $host = (string) ($_SERVER['HTTP_HOST'] ?? ''); $path = parse_url($back, PHP_URL_HOST) === $host ? (string) parse_url($back, PHP_URL_PATH) : ''; $query = (string) parse_url($back, PHP_URL_QUERY); redirect($path !== '' ? $path . ($query !== '' ? '?' . $query : '') : '/dashboard.php'); } /** Allgemeines Tempolimit fuer alle abgeschickten Formulare angemeldeter Konten (aus bootstrap.php). */ function security_guard_post(): void { if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST' || empty($_SESSION['user_id'])) { return; } $script = basename((string) ($_SERVER['SCRIPT_NAME'] ?? '')); // Die Live-Vorschau im Wiki-Editor schickt beim Tippen laufend Anfragen, beim Abhaken der Legionsbeitraege kommt // ein Klick nach dem anderen (nur mit dues.manage, jeder steht im Audit-Log). if (in_array($script, SECURITY_POST_EXEMPT, true) || ($_POST['action'] ?? '') === 'preview' || ($script === 'dues_action.php' && ($_POST['action'] ?? '') === 'toggle')) { return; } // Automatisches Speichern im Gear-Planer: eigener, grosser Topf - eifriges Planen blockiert so weder den Planer // noch den Rest der Website, ein durchdrehendes Skript bremst er trotzdem if ($script === 'gear_action.php' && in_array($_POST['action'] ?? '', SECURITY_GEAR_AUTOSAVE, true)) { if (!security_throttle('gear')) { security_reject('Sehr viele Änderungen in kurzer Zeit – der Gear-Planer speichert gerade nicht. Bitte warte ein paar Minuten.'); } return; } if (!security_throttle('post')) { security_reject('Zu viele Aktionen in kurzer Zeit. Bitte warte ein paar Minuten und versuche es dann erneut.'); } } // ---- Login-Bremse ---- /** Leer = Login-Versuch erlaubt, sonst die Meldung fuer die Login-Seite. */ function login_throttle_check(string $username): string { [$maxIp, $window] = SECURITY_LIMITS['login_ip']; [$maxPair] = SECURITY_LIMITS['login_pair']; if (rate_limit_count('login_ip', client_ip_key(), $window) >= $maxIp || rate_limit_count('login_pair', login_pair_key($username), $window) >= $maxPair) { return 'Zu viele fehlgeschlagene Anmeldungen von deinem Anschluss. Bitte warte 15 Minuten ' . 'und versuche es dann erneut - oder melde dich über Discord an.'; } return ''; } function login_pair_key(string $username): string { return substr(hash('sha256', 'pair|' . ($_SERVER['REMOTE_ADDR'] ?? '') . '|' . mb_strtolower(trim($username))), 0, 40); } /** Fehlversuch zaehlen; beim Erreichen einer Sperre ein Eintrag im Audit- und Discord-Log. */ function login_throttle_fail(string $username): void { [$maxIp, $window] = SECURITY_LIMITS['login_ip']; [$maxPair] = SECURITY_LIMITS['login_pair']; rate_limit_add('login_ip', client_ip_key()); rate_limit_add('login_pair', login_pair_key($username)); $ipCount = rate_limit_count('login_ip', client_ip_key(), $window); $pairCount = rate_limit_count('login_pair', login_pair_key($username), $window); if ($ipCount === $maxIp || $pairCount === $maxPair) { security_log('🔐 Login-Sperre nach Fehlversuchen', [ 'Benutzername' => mb_substr($username, 0, 60), 'IP (gekürzt)' => (string) client_ip_masked(), 'Gesperrt' => $ipCount >= $maxIp ? 'diese IP für alle Konten (15 Min.)' : 'diese IP für dieses Konto (15 Min.)', ], 'warning', []); } } // ---- Notbremse und Sitzungen ---- /** Wird bei jeder Loeschung (admin_log mit Ton "danger") aufgerufen. */ function security_note_destructive(): void { $user = current_user(); if (!$user) { return; } [$max, $window] = SECURITY_LIMITS['destructive']; $subject = 'u' . (int) $user['id']; rate_limit_add('destructive', $subject); if (rate_limit_count('destructive', $subject, $window) !== $max + 1) { return; } // Entwickler werden nicht gesperrt (sonst kaeme niemand mehr an ihr Konto), aber gemeldet. if (is_developer($user)) { security_log('🚨 Auffällig viele Löschungen (Entwickler-Konto, nicht gesperrt)', [ 'Konto' => admin_log_user((int) $user['id']), 'Löschungen' => 'mehr als ' . $max . ' in ' . round($window / 60) . ' Minuten', ], 'danger'); return; } security_lock_account((int) $user['id'], 'Mehr als ' . $max . ' Löschungen in ' . round($window / 60) . ' Minuten', true); } /** Konto sperren und alle Sitzungen beenden. */ function security_lock_account(int $userId, string $reason, bool $automatic = false): void { db()->prepare("UPDATE users SET status = 'disabled', session_epoch = session_epoch + 1 WHERE id = ?")->execute([$userId]); security_log($automatic ? '🚨 Konto automatisch gesperrt' : '🔒 Konto gesperrt und abgemeldet', [ 'Konto' => admin_log_user($userId), 'Grund' => $reason, 'Hinweis' => $automatic ? 'Möglicherweise gehackt - bitte prüfen. Entsperren über die Benutzerverwaltung (Status „Aktiv“).' : '', ], 'danger'); } /** Alle Sitzungen eines Kontos beenden (naechster Seitenaufruf meldet ab). */ function security_end_sessions(int $userId): void { db()->prepare('UPDATE users SET session_epoch = session_epoch + 1 WHERE id = ?')->execute([$userId]); }