Send a Content-Security-Policy and security headers on every response
- New SecurityHeadersMiddleware (outermost): CSP with a per-request script nonce, framing (SAMEORIGIN, embeds via frame-ancestors), nosniff, Referrer- and Permissions-Policy. JSON, files and error pages are covered now, not only rendered HTML; headers set by controllers still win. - The inline theme script carries the nonce; flash messages are dismissed via data-dismiss instead of inline onclick handlers, and the flash elements share one template. - reCAPTCHA sources are only allowed when it is enabled. - The embed CSRF exception and framing use the same isEmbed() check. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6912d045cf
commit
2a53675ce5
15 files changed
+290
-66
No files matched your search
+5
-4
@@ -17,6 +17,7 @@ declare(strict_types=1);
|
||||
namespace App;
|
||||
|
||||
use App\Middleware\HostHeaderMiddleware;
|
||||
use App\Middleware\SecurityHeadersMiddleware;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Core\ContainerInterface;
|
||||
use Cake\Datasource\FactoryLocator;
|
||||
@@ -67,6 +68,9 @@ class Application extends BaseApplication
|
||||
public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
|
||||
{
|
||||
$middlewareQueue
|
||||
// Outermost, so error pages get the security headers (CSP, framing, nosniff) too.
|
||||
->add(new SecurityHeadersMiddleware())
|
||||
|
||||
// Catch any exceptions in the lower layers,
|
||||
// and make an error page/response
|
||||
->add(new ErrorHandlerMiddleware(Configure::read('Error'), $this))
|
||||
@@ -98,10 +102,7 @@ class Application extends BaseApplication
|
||||
'httponly' => true,
|
||||
]))->skipCheckCallback(
|
||||
// Embedded slides run in third-party iframes (no cookies); the secret key is the authorisation.
|
||||
fn(ServerRequestInterface $request): bool => (bool)preg_match(
|
||||
'/^embed(:|$)/',
|
||||
(string)($request->getAttribute('params')['_name'] ?? ''),
|
||||
),
|
||||
fn(ServerRequestInterface $request): bool => SecurityHeadersMiddleware::isEmbed($request),
|
||||
));
|
||||
|
||||
return $middlewareQueue;
|
||||
|
||||
@@ -6,11 +6,11 @@ namespace App\Controller;
|
||||
use App\Service\ThrottleService;
|
||||
use Cake\Controller\Controller;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Event\EventInterface;
|
||||
use Cake\Http\Response;
|
||||
|
||||
/**
|
||||
* Base controller of PlenarIO.
|
||||
* Base controller of PlenarIO. Security headers (CSP, framing, nosniff) are set for every
|
||||
* response by \App\Middleware\SecurityHeadersMiddleware.
|
||||
*/
|
||||
class AppController extends Controller
|
||||
{
|
||||
@@ -24,22 +24,6 @@ class AppController extends Controller
|
||||
$this->loadComponent('Flash');
|
||||
}
|
||||
|
||||
/**
|
||||
* Security headers for every HTML response.
|
||||
*
|
||||
* @param \Cake\Event\EventInterface<\Cake\Controller\Controller> $event Event
|
||||
* @return void
|
||||
*/
|
||||
public function beforeRender(EventInterface $event): void
|
||||
{
|
||||
parent::beforeRender($event);
|
||||
|
||||
$this->response = $this->response
|
||||
->withHeader('X-Content-Type-Options', 'nosniff')
|
||||
->withHeader('X-Frame-Options', 'SAMEORIGIN')
|
||||
->withHeader('Referrer-Policy', 'same-origin');
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a hit of the client IP in a throttle bucket (see ThrottleService).
|
||||
*
|
||||
|
||||
@@ -26,7 +26,7 @@ use Cake\Routing\Router;
|
||||
* heartbeats stop, PollsTable::pauseIfEmbedStale() pauses the poll.
|
||||
*
|
||||
* Runs in third-party iframes: no CSRF check (see Application::middleware()),
|
||||
* framing allowed via CSP frame-ancestors (Plenario.embed.frameAncestors).
|
||||
* framing allowed via CSP frame-ancestors (Plenario.embed.frameAncestors, see SecurityHeadersMiddleware).
|
||||
*/
|
||||
class EmbedController extends AppController
|
||||
{
|
||||
@@ -76,7 +76,7 @@ class EmbedController extends AppController
|
||||
|
||||
/**
|
||||
* Like admin pages: never leak the key as referrer, never index or cache.
|
||||
* Unlike everything else, framing by other sites is allowed.
|
||||
* Framing by other sites is allowed by SecurityHeadersMiddleware (embed paths).
|
||||
*
|
||||
* @param \Cake\Event\EventInterface<\Cake\Controller\Controller> $event Event
|
||||
* @return void
|
||||
@@ -84,9 +84,7 @@ class EmbedController extends AppController
|
||||
public function beforeRender(EventInterface $event): void
|
||||
{
|
||||
parent::beforeRender($event);
|
||||
$this->response = $this->protect($this->response)
|
||||
->withoutHeader('X-Frame-Options')
|
||||
->withHeader('Content-Security-Policy', 'frame-ancestors ' . $this->frameAncestors());
|
||||
$this->response = $this->protect($this->response);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -210,14 +208,4 @@ class EmbedController extends AppController
|
||||
{
|
||||
return ['_name' => $name, 'key' => (string)$this->poll->embed_key, 'id' => $this->slide->id];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string CSP source list; falls back to 'self' for anything unexpected
|
||||
*/
|
||||
protected function frameAncestors(): string
|
||||
{
|
||||
$value = trim((string)Configure::read('Plenario.embed.frameAncestors', '*'));
|
||||
|
||||
return preg_match('#^[A-Za-z0-9*:/.\' -]+$#', $value) ? $value : "'self'";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Middleware;
|
||||
|
||||
use Cake\Core\Configure;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Psr\Http\Server\MiddlewareInterface;
|
||||
use Psr\Http\Server\RequestHandlerInterface;
|
||||
|
||||
/**
|
||||
* Security headers for every response: HTML, JSON, files and error pages.
|
||||
*
|
||||
* - Content-Security-Policy: scripts only from this site (plus reCAPTCHA if enabled) and inline
|
||||
* scripts carrying the per-request nonce (request attribute `cspScriptNonce`, see element theme_init).
|
||||
* - Framing: SAMEORIGIN everywhere, except embedded slides (/e/{key}/{id}), which may be framed
|
||||
* by the sites in `Plenario.embed.frameAncestors` (CSP frame-ancestors).
|
||||
* - nosniff, Referrer-Policy same-origin, Permissions-Policy.
|
||||
*
|
||||
* Headers a controller has set itself win (e.g. `Referrer-Policy: no-referrer` in the admin area).
|
||||
* Added as the outermost middleware so error pages are covered too; therefore embed requests are
|
||||
* recognised by their path (relative to the app base), not by route name.
|
||||
*/
|
||||
class SecurityHeadersMiddleware implements MiddlewareInterface
|
||||
{
|
||||
public const NONCE_ATTRIBUTE = 'cspScriptNonce';
|
||||
|
||||
/**
|
||||
* Same key/id patterns as the embed routes in config/routes.php.
|
||||
*/
|
||||
protected const EMBED_PATH = '#^/e/[A-Za-z0-9_-]{20,64}/\d+(/|$)#';
|
||||
|
||||
/**
|
||||
* Whether the request targets an embedded slide (/e/{key}/{id}/...).
|
||||
*
|
||||
* @param \Psr\Http\Message\ServerRequestInterface $request Request
|
||||
* @return bool
|
||||
*/
|
||||
public static function isEmbed(ServerRequestInterface $request): bool
|
||||
{
|
||||
return (bool)preg_match(self::EMBED_PATH, $request->getUri()->getPath());
|
||||
}
|
||||
|
||||
/**
|
||||
* CSP source list for frame-ancestors of embedded slides; 'self' for anything unexpected.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function embedFrameAncestors(): string
|
||||
{
|
||||
$value = trim((string)Configure::read('Plenario.embed.frameAncestors', '*'));
|
||||
|
||||
return preg_match('#^[A-Za-z0-9*:/.\' -]+$#', $value) ? $value : "'self'";
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Psr\Http\Message\ServerRequestInterface $request The request.
|
||||
* @param \Psr\Http\Server\RequestHandlerInterface $handler The request handler.
|
||||
* @return \Psr\Http\Message\ResponseInterface
|
||||
*/
|
||||
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
|
||||
{
|
||||
$nonce = base64_encode(random_bytes(16));
|
||||
$response = $handler->handle($request->withAttribute(self::NONCE_ATTRIBUTE, $nonce));
|
||||
$embed = static::isEmbed($request);
|
||||
|
||||
$headers = [
|
||||
'X-Content-Type-Options' => 'nosniff',
|
||||
'Referrer-Policy' => 'same-origin',
|
||||
'Permissions-Policy' => 'camera=(), microphone=(), geolocation=(), payment=(), usb=()',
|
||||
];
|
||||
if (!$this->isDebugKit($request)) {
|
||||
$headers['Content-Security-Policy'] = $this->policy($nonce, $embed);
|
||||
}
|
||||
if (!$embed) {
|
||||
$headers['X-Frame-Options'] = 'SAMEORIGIN';
|
||||
}
|
||||
foreach ($headers as $name => $value) {
|
||||
if (!$response->hasHeader($name)) {
|
||||
$response = $response->withHeader($name, $value);
|
||||
}
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $nonce Nonce of this request
|
||||
* @param bool $embed Embedded slide
|
||||
* @return string
|
||||
*/
|
||||
protected function policy(string $nonce, bool $embed): string
|
||||
{
|
||||
$scripts = ["'self'", "'nonce-" . $nonce . "'"];
|
||||
// Presenter: YouTube player (privacy-enhanced mode); 'self' for the DebugKit toolbar.
|
||||
$frames = ["'self'", 'https://www.youtube-nocookie.com'];
|
||||
if (strtolower((string)Configure::read('Plenario.captcha.type')) === 'recaptcha') {
|
||||
$scripts[] = 'https://www.google.com/recaptcha/';
|
||||
$scripts[] = 'https://www.gstatic.com/recaptcha/';
|
||||
$frames[] = 'https://www.google.com/recaptcha/';
|
||||
$frames[] = 'https://recaptcha.google.com/recaptcha/';
|
||||
}
|
||||
|
||||
return implode('; ', [
|
||||
"default-src 'self'",
|
||||
'script-src ' . implode(' ', $scripts),
|
||||
// Inline style attributes are used for bar widths and drag & drop (no scripts).
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"img-src 'self' data:",
|
||||
"connect-src 'self'",
|
||||
'frame-src ' . implode(' ', $frames),
|
||||
"object-src 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self'",
|
||||
'frame-ancestors ' . ($embed ? static::embedFrameAncestors() : "'self'"),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* DebugKit's own pages use inline scripts; it only runs with debug on.
|
||||
*
|
||||
* @param \Psr\Http\Message\ServerRequestInterface $request Request
|
||||
* @return bool
|
||||
*/
|
||||
protected function isDebugKit(ServerRequestInterface $request): bool
|
||||
{
|
||||
return Configure::read('debug') && str_starts_with($request->getUri()->getPath(), '/debug-kit/');
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user