Correções da auditoria de 24/09 (audits/fitme3070-auditoria-2026-09-24.html). Lixeira - Tudo o que é importante passa a soft delete (deleted_at + deleted_by): equipa, modalidades, eventos, mensalidades, galerias, imagens, horário, horas de funcionamento, inscrições em eventos e pedidos de inscrição. - config/functions_trash.php: um registo por tipo; apagar, restaurar, listar e eliminar leem todos dele. Eliminar de vez só com 30 dias na lixeira — a condição está no WHERE do DELETE, um POST forjado não apaga nada. - Gestão → Lixeira (views/admin/trash/index.php): lista única com quem e quando, restauro a qualquer momento. - Imagens de galeria: o site lista a pasta, por isso o ficheiro passa para .trash/ (negado pelo .htaccess) e volta no restauro. - As listagens e o site público filtram deleted_at (horário também filtra modalidades apagadas). Migração: database/migration_20260925_trash.sql (só acrescenta colunas; tem de ser aplicada antes deste código). CSRF - csrf_check() recusa qualquer pedido que não seja POST (405). Antes saía sem verificar nada em GET, e dez ações de apagar/restaurar eram GET. - Os dez handlers passaram a POST com token; links viraram formulários. Autenticação e sessão - client_ip(): X-Real-IP / último X-Forwarded-For, só vindo de proxy privado com TRUSTED_PROXY. O throttle contava o IP do proxy (limite global). - Throttle também por conta (hash do email), além do IP. - Sem oráculo de tempo: login verifica contra um hash de referência quando a conta não existe; a recuperação deixa o email na fila. - Cookie de sessão Secure/HttpOnly/SameSite=Lax e use_strict_mode. - Definições de sistema só para sysadmin; autocomplete=username. Servidor e uploads - .htaccess: nosniff, Referrer-Policy, X-Frame-Options, Permissions-Policy, CSP (frame-ancestors, base-uri, object-src, form-action); nega parciais _*.php, PHP soltos do platform-tools e *.md; 404 própria. - Uploads validados pelo conteúdo (finfo/getimagesize); SVG só sem scripts, handlers on*=, foreignObject ou hrefs externos. Testado numa cópia da BD de produção (fitme_audit_test) com um contentor temporário: 34/34 verificações HTTP ponta-a-ponta. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
78 lines
3.6 KiB
PHP
78 lines
3.6 KiB
PHP
<?php
|
|
// ─── Per-IP attempt throttling ───────────────────────────────────────────────
|
|
// Generic, scope-scoped IP throttle for endpoints where an attacker gains by
|
|
// repeating: login, password-reset requests, registration.
|
|
//
|
|
// Two limits applied together:
|
|
// - burst: N attempts per minute (default 5)
|
|
// - sustained: N attempts per hour (default 30)
|
|
//
|
|
// Counts FAILED *and* SUCCESSFUL attempts, so a guessed password can't be
|
|
// parlayed into stuffing the rest of the user list from the same IP.
|
|
//
|
|
// Schema: database/migration_20260913_local_auth.sql (`auth_attempts`).
|
|
|
|
// IP real do visitante (config/env.php). Antes era o REMOTE_ADDR, que atrás do
|
|
// proxy é o mesmo para toda a gente — o limite era global.
|
|
function _throttle_ip(): string {
|
|
return client_ip();
|
|
}
|
|
|
|
// Chave por conta: o mesmo email atacado a partir de muitos IPs só se vê
|
|
// contado pela conta. Guardada na coluna ip (VARCHAR 45) como "acct:" + hash,
|
|
// nunca o email em claro.
|
|
function throttle_account_key(string $identifier): string {
|
|
return 'acct:' . substr(hash('sha256', strtolower(trim($identifier))), 0, 40);
|
|
}
|
|
|
|
function throttle_check(PDO $pdo, string $scope, int $maxPerMinute = 5, int $maxPerHour = 30, ?string $key = null): bool {
|
|
try {
|
|
$stmt = $pdo->prepare(
|
|
"SELECT
|
|
SUM(attempted_at > DATE_SUB(NOW(), INTERVAL 1 MINUTE)) AS minute,
|
|
SUM(attempted_at > DATE_SUB(NOW(), INTERVAL 1 HOUR)) AS hour
|
|
FROM auth_attempts
|
|
WHERE ip = ? AND scope = ? AND attempted_at > DATE_SUB(NOW(), INTERVAL 1 HOUR)"
|
|
);
|
|
$stmt->execute([$key ?? _throttle_ip(), $scope]);
|
|
$row = $stmt->fetch(PDO::FETCH_ASSOC) ?: ['minute' => 0, 'hour' => 0];
|
|
} catch (PDOException $e) {
|
|
// Fail open if the table is missing (migration not applied yet during a
|
|
// deploy). Log loudly so an operator notices.
|
|
error_log('[throttle] check failed (run migration_20260913_local_auth.sql?): ' . $e->getMessage());
|
|
return true;
|
|
}
|
|
if ((int) $row['minute'] >= $maxPerMinute) return false;
|
|
if ((int) $row['hour'] >= $maxPerHour) return false;
|
|
return true;
|
|
}
|
|
|
|
function throttle_record(PDO $pdo, string $scope, ?string $key = null): void {
|
|
try {
|
|
$pdo->prepare("INSERT INTO auth_attempts (ip, scope) VALUES (?, ?)")
|
|
->execute([$key ?? _throttle_ip(), $scope]);
|
|
// Probabilistic cleanup so the table doesn't grow forever — cheap on a
|
|
// 1% sample of writes, and saves wiring up a cron for a small install.
|
|
if (random_int(0, 99) === 0) {
|
|
@$pdo->exec("DELETE FROM auth_attempts WHERE attempted_at < DATE_SUB(NOW(), INTERVAL 1 DAY)");
|
|
}
|
|
} catch (PDOException $e) {
|
|
error_log('[throttle] record failed (run migration_20260913_local_auth.sql?): ' . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
// Convenience: 429 + generic message, then exit. Callers that would rather keep
|
|
// the visitor on the form can use throttle_check() and render their own error.
|
|
function throttle_block(string $reason = ''): void {
|
|
http_response_code(429);
|
|
header('Retry-After: 60');
|
|
header('Content-Type: text/html; charset=utf-8');
|
|
echo '<!doctype html><meta charset="utf-8"><title>Demasiadas tentativas</title>'
|
|
. '<div style="font-family:sans-serif;max-width:520px;margin:80px auto;text-align:center;">'
|
|
. '<h2>Demasiadas tentativas</h2>'
|
|
. '<p>Aguarde alguns minutos antes de tentar novamente.</p>'
|
|
. '</div>';
|
|
if ($reason !== '') error_log("[throttle] blocked: {$reason} ip=" . _throttle_ip());
|
|
exit;
|
|
}
|