LuminaWebsite/includes/security.php
Maaxxs 5dabbccbd7 Gear planner, dashboard polish, images on bug reports
Gear planner:
- Personal gear sets (18 slots) with enchant, exceed, soul imprint and manastones,
  stat totals by source and side-by-side comparison of 2-4 sets
- Sets can be shown on the own profile page (read-only for other members)
- Admin catalog: import items from aion2hub.com (Global client), compare stored
  values with the source one by one or all at once, at most one request per second
- New permissions gear.view (all with dashboard access) and gear.manage

Dashboard:
- Role badges ordered like the member list (roster_order)
- Stronger hover effect on "Rangliste & Verlauf" / "Zum Lumishop", no more blue
  hover on secondary buttons
- "Anstehende Raids" box links to the raids page, next raids link to the raid
  and to the calendar day
- Raid attendance only knows present/absent (old "excused" entries count as unset)

Bug reports:
- Up to 5 images per report, pasting copied images with Ctrl+V (also for the gallery)
- Images are only served to the reporter and bugs.manage via bug_image.php

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 09:27:09 +02:00

319 lines
13 KiB
PHP

<?php
declare(strict_types=1);
/**
* Schutz vor Missbrauch und Audit-Log:
* - Audit-Log: jede Verwaltungsaktion (admin_log) und jedes Sicherheitsereignis landet dauerhaft
* in der Datenbank - unabhaengig davon, ob der Discord-Bot gerade erreichbar ist.
* - Tempolimits pro Konto (Formulare, Uploads, Kommentare, Fehlermeldungen).
* - Login-Bremse nach Fehlversuchen - pro IP bzw. IP + Benutzername, NICHT pro Konto: sonst
* koennte jemand ein bekanntes Konto mit Absicht dauerhaft sperren.
* - Notbremse: Wer in kurzer Zeit auffaellig viel loescht, wird automatisch gesperrt (gehacktes Konto).
* - Sitzungen eines Kontos sofort beenden (users.session_epoch).
*/
// Bereiche im Audit-Log: Schluessel => Beschriftung
const AUDIT_AREAS = [
'users' => 'Benutzer & Rechte',
'security' => 'Sicherheit',
'raids' => 'Raids',
'premades' => 'Premades',
'events' => 'Events',
'map' => 'Karte',
'warehouse' => 'Lagerhaus',
'contributions' => 'Lumipunkte',
'shop' => 'Lumishop',
'members' => 'Profile',
'wiki' => 'Wiki',
'gear' => 'Gear-Planer',
'reports' => 'Reports',
'bugs' => 'Fehlermeldungen',
'other' => 'Sonstiges',
];
// Tempolimits: Art => [hoechstens, in Sekunden]
const SECURITY_LIMITS = [
'post' => [120, 300], // abgeschickte Formulare/Aktionen pro Konto
'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
'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'];
/** 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',
'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',
];
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);
}
/**
* Eintrag ins Audit-Log. Discord-Erwaehnungen "(<@123>)" werden fuer die Anzeige entfernt.
*
* @param array<string, scalar|null> $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(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([
$actor ? (int) $actor['id'] : null,
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(),
]);
} 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',
'upload' => 'Bilder hochladen',
'comment' => 'Kommentare',
'report' => 'Meldungen',
'reaction' => 'Reaktionen',
'calendar' => 'Kalender-Termine',
'bug' => 'Fehlermeldungen',
'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.
if (in_array($script, SECURITY_POST_EXEMPT, true) || ($_POST['action'] ?? '') === 'preview') {
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]);
}