LuminaWebsite/includes/security.php
Maaxxs 785eab611e Legion dues: an admin page tracks who paid, with a rhythm, exemptions and suspended cycles
Asked for: the legion collects dues in Kina; a separate, purely administrative page to set a cycle and an
amount, tick off who has paid, exempt members for one or more cycles and suspend a cycle for everyone. On
the site it is called "Legionsbeiträge" and the currency "Kina", like everywhere else.

- includes/dues.php: settings dues_amount/_unit/_every/_start/_anchor (every 1-12 weeks or months). The
  cycles (dues_cycles) form a series from the anchor (months on the same day, in shorter months the last
  one) and exist up to the running one plus the next. Until something is ticked or suspended, a new setting
  rebuilds all cycles; afterwards a new amount applies to the coming cycles (optionally the running one) and
  a new rhythm starts after the last cycle that has begun or has data. The amount also takes 500k, 1,5kk or
  2 Mio.
- Who owes: every active account that was a member when the cycle started (Discord join, else account
  creation), unless exempt or the cycle is suspended; a ticked payment always counts. Former members only
  show up with payments in the visible cycles.
- admin/dues.php: key figures (running cycle, paid, collected of expected, arrears), a table of members x
  the last six cycles with paging, a click toggles a payment (dues_entries with who and when; without
  reload via assets/js/dues.js, the button sends the state it sets), search and filters (open, paid,
  exempt, arrears), suspend/resume per cycle with an optional reason, exemptions (dues_exemptions:
  members, from which cycle, 1-12 cycles or until further notice, reason; end or delete) and the settings.
  On phones the table opens at the running cycle, the exemption list stacks.
- admin/dues_action.php: settings, toggle (JSON with the redrawn cell, column figures, arrears and key
  figures), cycle, exempt_add/_end/_delete. Settings, suspensions and exemptions go to the audit log and the
  Discord log channel, ticks only to the audit log (area "Legionsbeiträge"); ticking is exempt from the
  general form rate limit.
- New right dues.manage (Administrator and the groups with roles.manage), menu item in the admin section
  with a coins icon, schema version 61 (tables also in sql/schema.sql).
- Privacy: privacy policy (what is stored, only the leadership sees it, account deletion), data export
  section legionsbeitraege, account deletion removes exemptions and keeps payments without the name, data
  reset area.
- Patch notes (leadership) and README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 23:33:22 +02:00

360 lines
15 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',
'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
'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
'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', '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',
'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<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(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',
'upload' => 'Bilder hochladen',
'comment' => 'Kommentare',
'report' => 'Meldungen',
'reaction' => 'Reaktionen',
'calendar' => 'Kalender-Termine',
'bug' => 'Fehlermeldungen',
'discord_sync' => 'Discord-Abgleich im Profil',
'export' => 'Datenauskunft herunterladen',
'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;
}
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]);
}