Portfolio_pero/includes/Security.php
2026-09-03 13:27:06 +02:00

484 lines
14 KiB
PHP

<?php
/**
* Security - protections centralisees.
*/
class Security
{
private static ?string $cspNonce = null;
private static bool $headersApplied = false;
/**
* Initialise les headers de securite et, si besoin, la session.
*
* @param array<string, mixed> $options
*/
public static function bootstrap(bool $withSession = true, array $options = []): void
{
if (PHP_SAPI !== 'cli') {
self::applySecurityHeaders($options);
}
if ($withSession) {
self::startSession();
}
}
/**
* Applique les headers de securite HTTP.
*
* @param array<string, mixed> $options
*/
public static function applySecurityHeaders(array $options = []): void
{
if (PHP_SAPI === 'cli' || headers_sent() || self::$headersApplied) {
return;
}
$isApi = (bool) ($options['api'] ?? false);
$noStore = (bool) ($options['no_store'] ?? false);
$allowAnalyticsCdn = (bool) ($options['allow_analytics_cdn'] ?? false);
$allowRecaptcha = (bool) ($options['recaptcha'] ?? false);
header_remove('X-Powered-By');
@ini_set('expose_php', '0');
header('X-Frame-Options: DENY');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: strict-origin-when-cross-origin');
header('Permissions-Policy: accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), microphone=(), payment=(), usb=()');
header('Cross-Origin-Opener-Policy: same-origin');
header('Cross-Origin-Resource-Policy: same-origin');
header('X-Permitted-Cross-Domain-Policies: none');
if (self::isHttps()) {
header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
}
if ($isApi || $noStore) {
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');
}
header('Content-Security-Policy: ' . self::buildCsp($allowAnalyticsCdn, $allowRecaptcha));
self::$headersApplied = true;
}
/**
* Construit la politique CSP.
*/
private static function buildCsp(bool $allowAnalyticsCdn, bool $allowRecaptcha = false): string
{
$scriptSources = [
"'self'",
"'nonce-" . self::cspNonce() . "'",
];
if ($allowAnalyticsCdn) {
$scriptSources[] = 'https://cdn.jsdelivr.net';
}
$connectSources = ["'self'"];
$frameSources = [];
$imgSources = ["'self'", 'data:'];
if ($allowRecaptcha) {
// Google reCAPTCHA v3 : script, iframe du badge, images et appels reseau.
$scriptSources[] = 'https://www.google.com';
$scriptSources[] = 'https://www.gstatic.com';
$connectSources[] = 'https://www.google.com';
$connectSources[] = 'https://www.gstatic.com';
$frameSources[] = 'https://www.google.com';
$imgSources[] = 'https://www.gstatic.com';
}
$directives = [
"default-src 'self'",
'script-src ' . implode(' ', array_unique($scriptSources)),
"style-src 'self' 'unsafe-inline'",
'img-src ' . implode(' ', array_unique($imgSources)),
"font-src 'self'",
'connect-src ' . implode(' ', array_unique($connectSources)),
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
"frame-ancestors 'none'",
"script-src-attr 'none'",
'upgrade-insecure-requests',
];
if ($frameSources !== []) {
array_splice($directives, 6, 0, ['frame-src ' . implode(' ', array_unique($frameSources))]);
}
return implode('; ', $directives) . ';';
}
/**
* Retourne le nonce CSP courant.
*/
public static function cspNonce(): string
{
if (self::$cspNonce === null) {
self::$cspNonce = rtrim(strtr(base64_encode(random_bytes(16)), '+/', '-_'), '=');
}
return self::$cspNonce;
}
/**
* Demarre la session avec des parametres securises.
*/
public static function startSession(): void
{
if (session_status() === PHP_SESSION_NONE) {
@ini_set('session.use_strict_mode', '1');
@ini_set('session.use_only_cookies', '1');
@ini_set('session.use_trans_sid', '0');
@ini_set('session.cookie_httponly', '1');
@ini_set('session.cookie_secure', self::isHttps() ? '1' : '0');
@ini_set('session.cookie_samesite', 'Strict');
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'domain' => '',
'secure' => self::isHttps(),
'httponly' => true,
'samesite' => 'Strict',
]);
session_start();
}
if (!isset($_SESSION['_created'])) {
$_SESSION['_created'] = time();
} elseif (time() - (int) $_SESSION['_created'] > 1800) {
session_regenerate_id(true);
$_SESSION['_created'] = time();
}
}
/**
* Genere (ou recupere) le token CSRF de la session courante.
*/
public static function csrfToken(): string
{
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
return $_SESSION['csrf_token'];
}
/**
* Retourne un champ CSRF pret a injecter dans un formulaire HTML.
*/
public static function csrfInput(): string
{
return '<input type="hidden" name="csrf_token" value="' . self::e(self::csrfToken()) . '">';
}
/**
* Valide le token CSRF soumis.
*/
public static function verifyCsrf(string $submitted, bool $json = false): void
{
$token = $_SESSION['csrf_token'] ?? '';
if ($token === '' || $submitted === '' || !hash_equals($token, $submitted)) {
http_response_code(403);
if ($json) {
self::jsonResponse([
'success' => false,
'message' => 'Requete invalide.',
]);
}
exit('Requete invalide.');
}
}
/**
* Verifie l'origine quand le navigateur envoie Origin/Referer.
*/
public static function enforceSameOrigin(bool $json = false): void
{
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
$referer = $_SERVER['HTTP_REFERER'] ?? '';
if ($origin !== '' && !self::matchesCurrentOrigin($origin)) {
self::abortOriginMismatch($json);
}
if ($referer !== '' && !self::matchesCurrentOrigin($referer)) {
self::abortOriginMismatch($json);
}
}
/**
* Redirige vers la page de login si aucune session admin n'est ouverte.
*/
public static function requireAdmin(): void
{
if (empty($_SESSION['admin_id'])) {
header('Location: login.php');
exit;
}
}
/**
* Retourne l'IP client.
*/
public static function clientIp(): string
{
return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}
/**
* Verifie si l'action depasse le nombre de requetes autorisees.
*/
public static function isRateLimited(PDO $db, string $action, string $ip, int $max, int $windowMinutes): bool
{
try {
$db->exec("CREATE TABLE IF NOT EXISTS rate_limits (
id INT AUTO_INCREMENT PRIMARY KEY,
action VARCHAR(64) NOT NULL,
ip VARCHAR(45) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
INDEX idx_action_ip_time (action, ip, created_at)
)");
$cutoff = (new DateTimeImmutable("-{$windowMinutes} minutes"))->format('Y-m-d H:i:s');
$stmt = $db->prepare(
'SELECT COUNT(*) FROM rate_limits
WHERE action = :action AND ip = :ip AND created_at > :cutoff'
);
$stmt->execute([
'action' => $action,
'ip' => $ip,
'cutoff' => $cutoff,
]);
return (int) $stmt->fetchColumn() >= $max;
} catch (Throwable) {
return false;
}
}
/**
* Enregistre une tentative pour le rate limiting.
*/
public static function recordAttempt(PDO $db, string $action, string $ip): void
{
try {
$db->prepare('INSERT INTO rate_limits (action, ip) VALUES (:action, :ip)')
->execute([
'action' => $action,
'ip' => $ip,
]);
$db->exec("DELETE FROM rate_limits WHERE created_at < NOW() - INTERVAL 24 HOUR");
} catch (Throwable) {
}
}
/**
* Nettoie une chaine pour l'affichage HTML.
*/
public static function e(string $str): string
{
return htmlspecialchars($str, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
/**
* Valide et nettoie un email.
*/
public static function sanitizeEmail(string $email): string|false
{
$email = filter_var(trim($email), FILTER_SANITIZE_EMAIL);
return filter_var($email, FILTER_VALIDATE_EMAIL) ? $email : false;
}
/**
* Nettoie un slug.
*/
public static function slugify(string $value): string
{
$value = mb_strtolower(trim($value), 'UTF-8');
$value = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $value) ?: $value;
$value = preg_replace('/[^a-z0-9]+/', '-', $value);
$value = trim((string) $value, '-');
return $value !== '' ? $value : 'projet';
}
/**
* Retourne true si l'URL est en HTTPS.
*/
public static function isHttps(): bool
{
if (!empty($_SERVER['HTTPS']) && strtolower((string) $_SERVER['HTTPS']) !== 'off') {
return true;
}
if ((int) ($_SERVER['SERVER_PORT'] ?? 0) === 443) {
return true;
}
if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower((string) $_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https') {
return true;
}
return false;
}
/**
* Retourne true si une URL partage la meme origine que la requete courante.
*/
private static function matchesCurrentOrigin(string $url): bool
{
$parts = parse_url($url);
if (!is_array($parts)) {
return false;
}
$host = strtolower((string) ($parts['host'] ?? ''));
$currentHost = strtolower((string) ($_SERVER['HTTP_HOST'] ?? ''));
if ($host === '' || $currentHost === '' || $host !== $currentHost) {
return false;
}
$scheme = strtolower((string) ($parts['scheme'] ?? ''));
$currentScheme = self::isHttps() ? 'https' : 'http';
return $scheme === '' || $scheme === $currentScheme;
}
/**
* Verifie un token Google reCAPTCHA v3 aupres de l'API de verification.
*
* Comportement de tolerance :
* - secret vide => reCAPTCHA non configure, on ne bloque pas (true).
* - reseau HS => on ne bloque pas les vrais visiteurs (true), les autres
* protections (honeypot, captcha maths, rate limit) restent actives.
* - token vide / score trop bas / mauvaise action => bloque (false).
*/
public static function verifyRecaptcha(
string $token,
string $secret,
string $ip,
float $minScore = 0.5,
string $expectedAction = ''
): bool {
if (trim($secret) === '') {
return true;
}
if (trim($token) === '') {
return false;
}
$payload = http_build_query([
'secret' => $secret,
'response' => $token,
'remoteip' => $ip,
]);
$endpoint = 'https://www.google.com/recaptcha/api/siteverify';
$raw = null;
if (function_exists('curl_init')) {
$ch = curl_init($endpoint);
if ($ch !== false) {
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 8,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
]);
$result = curl_exec($ch);
curl_close($ch);
if (is_string($result) && $result !== '') {
$raw = $result;
}
}
}
if ($raw === null) {
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
'content' => $payload,
'timeout' => 8,
],
]);
$result = @file_get_contents($endpoint, false, $context);
if (is_string($result) && $result !== '') {
$raw = $result;
}
}
if ($raw === null) {
error_log('[Security] reCAPTCHA : reponse reseau indisponible, tolerance appliquee.');
return true;
}
$data = json_decode($raw, true);
if (!is_array($data)) {
error_log('[Security] reCAPTCHA : reponse JSON invalide, tolerance appliquee.');
return true;
}
if (empty($data['success'])) {
return false;
}
if (isset($data['score']) && (float) $data['score'] < $minScore) {
return false;
}
if ($expectedAction !== '' && isset($data['action']) && $data['action'] !== $expectedAction) {
return false;
}
return true;
}
/**
* Retourne une reponse JSON et arrete l'execution.
*
* @param array<string, mixed> $payload
*/
public static function jsonResponse(array $payload): never
{
echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
/**
* Coupe la requete en cas d'origine non fiable.
*/
private static function abortOriginMismatch(bool $json): void
{
http_response_code(403);
if ($json) {
self::jsonResponse([
'success' => false,
'message' => 'Origine non autorisee.',
]);
}
exit('Origine non autorisee.');
}
}