fix(security): make session-cookie hardening work under TLS termination

The passive scan flagged 3x MEDIUM 'PHPSESSID missing Secure' and an
admin-login cookie missing HttpOnly. Root cause was not the cookie code
but scheme detection: every call site read $_SERVER['HTTPS'] directly,
which is unset when TLS is terminated in front of PHP-FPM, so the Secure
flag was silently dropped.

Add RequestUtil::isSecure()/baseUrl() as the single scheme detector:
  1. $_SERVER['HTTPS'] (direct TLS)
  2. X-Forwarded-Proto — only from a loopback/private peer, so a remote
     client cannot spoof it
  3. SERVER_PORT == 443
Replace all 8 inline $_SERVER['HTTPS'] idioms (App, AdminAuth, 4x filepond
endpoints, validate-access, admin/acces, SystemController self-ping).

nginx: forward the scheme to php-fpm in all 4 fastcgi blocks
(fastcgi_param HTTPS $https + X-Forwarded-Proto $scheme) and uncomment
server_tokens off. Config validated with nginx -t (real config, alpine
container).

AdminAuth: logout() now clears the session cookie with the same
path/domain/secure/httponly/samesite it was set with, instead of the
legacy positional setcookie() that dropped SameSite.

Tests (+24, 340 total):
  - RequestUtilTest: scheme detection incl. proxy trust boundaries
  - SessionCookieTest: logout emits a hardened deletion cookie
  - PeerTubeIntegrationTest: PeerTube keeps using its absolute instance_url
    and is unaffected by scheme changes (Guzzle MockHandler)
  - NginxConfigTest: pins HTTPS forwarding, HSTS includeSubDomains,
    server_tokens off

PeerTube uses an absolute instance_url from the DB and never derives URLs
from the request, so the integration is unchanged — the regression tests
lock that invariant in.
This commit is contained in:
Pontoporeia committed 2026-10-14 10:31:23 +02:00
1 parent e1f9cc9a9a
commit 554fc57455
17 files changed
+652 -29

No files matched your search

+2 -2
View File
@@ -11,8 +11,8 @@ $shareLink = ShareLink::make();
$links = $shareLink->listActive();
$archivedLinks = $shareLink->listArchived();
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$baseUrl = $protocol . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
require_once APP_ROOT . '/src/RequestUtil.php';
$baseUrl = RequestUtil::baseUrl();
// ── Demandes d'accès aux fichiers ─────────────────────────────────────────────
require_once APP_ROOT . '/src/Database.php';
+2 -1
View File
@@ -14,7 +14,8 @@ require_once __DIR__ . '/../../../../src/FilepondHandler.php';
// ── Start session ────────────────────────────────────────────────────────
if (session_status() === PHP_SESSION_NONE) {
$isSecure = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
require_once APP_ROOT . '/src/RequestUtil.php';
$isSecure = RequestUtil::isSecure();
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
@@ -16,7 +16,8 @@ require_once __DIR__ . '/../../../../src/FilepondHandler.php';
// ── Start session ────────────────────────────────────────────────────────
if (session_status() === PHP_SESSION_NONE) {
$isSecure = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
require_once APP_ROOT . '/src/RequestUtil.php';
$isSecure = RequestUtil::isSecure();
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
@@ -13,7 +13,8 @@ require_once __DIR__ . '/../../../../src/FilepondHandler.php';
// ── Start session ────────────────────────────────────────────────────────
if (session_status() === PHP_SESSION_NONE) {
$isSecure = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
require_once APP_ROOT . '/src/RequestUtil.php';
$isSecure = RequestUtil::isSecure();
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
@@ -13,7 +13,8 @@ require_once __DIR__ . '/../../../../src/FilepondHandler.php';
// ── Start session ────────────────────────────────────────────────────────
if (session_status() === PHP_SESSION_NONE) {
$isSecure = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
require_once APP_ROOT . '/src/RequestUtil.php';
$isSecure = RequestUtil::isSecure();
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
+2 -1
View File
@@ -164,8 +164,9 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$sessionToken = $db->createAccessSession($redemption['request_id'], 30);
// Set HttpOnly, Secure, SameSite=Strict cookie (long-lived session)
require_once APP_ROOT . '/src/RequestUtil.php';
$cookieName = 'tfe_access_' . $thesisId;
$cookieSecure = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
$cookieSecure = RequestUtil::isSecure();
setcookie($cookieName, $sessionToken, [
'expires' => time() + 30 * 86400,
+30 -12
View File
@@ -67,6 +67,9 @@ class AdminAuth
return;
}
// Harden session cookie (item #8)
// Secure is always on for admin: the panel is only reachable over
// HTTPS in production, and the cli-server dev exception is scoped to
// the built-in server that cannot do TLS anyway.
session_set_cookie_params([
'lifetime' => self::COOKIE_LIFETIME_SECONDS,
'path' => '/admin',
@@ -77,6 +80,32 @@ class AdminAuth
session_start();
}
/**
* Clear the session cookie with the same attributes used to set it.
*
* A deletion cookie must repeat the original path/domain/secure/httponly
* (and samesite, for consistency) or browsers keep the stale cookie.
*/
private static function clearSessionCookie(): void
{
if (!ini_get('session.use_cookies')) {
return;
}
$p = session_get_cookie_params();
setcookie(
session_name(),
'',
[
'expires' => time() - 86400,
'path' => $p['path'],
'domain' => $p['domain'],
'secure' => $p['secure'],
'httponly' => $p['httponly'],
'samesite' => $p['samesite'],
]
);
}
/**
* Enforce server-side idle + absolute timeouts on an authenticated session.
*
@@ -382,18 +411,7 @@ class AdminAuth
}
self::startSession();
$_SESSION = [];
if (ini_get('session.use_cookies')) {
$p = session_get_cookie_params();
setcookie(
session_name(),
'',
time() - 86400,
$p['path'],
$p['domain'],
$p['secure'],
$p['httponly']
);
}
self::clearSessionCookie();
session_destroy();
}
}
+2 -1
View File
@@ -24,7 +24,8 @@ class App
self::$booted = true;
}
if (session_status() === PHP_SESSION_NONE) {
$isSecure = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
require_once APP_ROOT . '/src/RequestUtil.php';
$isSecure = RequestUtil::isSecure();
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
+4 -2
View File
@@ -510,8 +510,10 @@ class SystemController
'detail' => null,
];
// Site HTTP ping
$siteUrl = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost') . '/';
// Site HTTP ping — use the same scheme detection as the rest of the
// app so the self-check follows TLS termination (reverse proxy).
require_once APP_ROOT . '/src/RequestUtil.php';
$siteUrl = RequestUtil::baseUrl() . '/';
$httpResult = $this->localHttpCheck($siteUrl);
$checks['site_http'] = [
'label' => 'Site HTTP',
+9
View File
@@ -37,6 +37,15 @@ class PeerTubeService
/** @var Client|null Shared Guzzle client (lazy-init). */
private static ?Client $httpClient = null;
/**
* Inject an HTTP client (used by integration tests with Guzzle MockHandler).
* Pass null to reset to the lazy default client.
*/
public static function setHttpClient(?Client $client): void
{
self::$httpClient = $client;
}
// -------------------------------------------------------------------------
// DB CRUD
// -------------------------------------------------------------------------
+102
View File
@@ -0,0 +1,102 @@
<?php
/**
* RequestUtil — request-level helpers shared across the app.
*
* Centralises scheme detection so that session cookies, absolute URLs and
* system checks all agree on whether the current request is secure.
*
* Detection order (first match wins):
* 1. $_SERVER['HTTPS'] — set to a truthy value ("on", "1", "https") by
* nginx/apache when the request is served over TLS. This is the
* canonical signal and covers the non-proxied case.
* 2. X-Forwarded-Proto — set by a TLS-terminating reverse proxy in front
* of PHP-FPM. We only trust it when the direct peer is a loopback or
* private address, so a remote client cannot spoof it by sending the
* header itself.
* 3. SERVER_PORT === 443 — last resort for setups that expose the port but
* neither of the above.
*
* Always prefer isSecure() over reading $_SERVER['HTTPS'] inline: under TLS
* termination (the production topology) $_SERVER['HTTPS'] is unset and the
* inline idiom silently drops the session cookie Secure flag.
*/
class RequestUtil
{
/**
* Whether the current request arrived over HTTPS.
*
* @param array<string,mixed>|null $server Override for $_SERVER (tests).
*/
public static function isSecure(?array $server = null): bool
{
$server ??= $_SERVER;
// 1. Direct TLS: nginx sets HTTPS=on. Treat "off"/"" as insecure.
$https = $server['HTTPS'] ?? null;
if ($https !== null && $https !== '' && strtolower((string) $https) !== 'off') {
return true;
}
// 2. Reverse-proxy TLS termination. Only trust the header from a
// trusted (loopback/private) peer — otherwise a client could send
// X-Forwarded-Proto: https over plain HTTP and get Secure cookies
// issued (which is harmless) or, worse, poison cached URLs.
$proto = $server['HTTP_X_FORWARDED_PROTO'] ?? '';
if ($proto !== '' && self::isTrustedProxy($server)) {
$first = strtolower(trim(explode(',', (string) $proto)[0]));
if ($first === 'https') {
return true;
}
}
// 3. Port fallback.
if (($server['SERVER_PORT'] ?? null) == 443) {
return true;
}
return false;
}
/**
* Whether the direct peer (REMOTE_ADDR) is a loopback / private address,
* i.e. a proxy we control rather than an arbitrary internet client.
*
* @param array<string,mixed> $server
*/
public static function isTrustedProxy(array $server): bool
{
$remote = (string) ($server['REMOTE_ADDR'] ?? '');
if ($remote === '') {
return false;
}
// Loopback IPv4/IPv6.
if ($remote === '127.0.0.1' || $remote === '::1') {
return true;
}
// Private ranges (RFC 1918 + link-local + unique-local IPv6).
$isPrivate = filter_var(
$remote,
FILTER_VALIDATE_IP,
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
) === false;
return $isPrivate;
}
/**
* Absolute base URL for the current request (scheme://host), respecting
* proxy TLS termination. Used for links and system self-checks.
*
* @param array<string,mixed>|null $server Override for $_SERVER (tests).
*/
public static function baseUrl(?array $server = null): string
{
$server ??= $_SERVER;
$scheme = self::isSecure($server) ? 'https' : 'http';
$host = $server['HTTP_HOST'] ?? 'localhost';
return $scheme . '://' . $host;
}
}