| 1 |
<?php |
| 2 |
|
| 3 |
namespace ipl\Web\Common; |
| 4 |
|
| 5 |
use InvalidArgumentException; |
| 6 |
use Stringable; |
| 7 |
|
| 8 |
/** |
| 9 |
* Content Security Policy (CSP) header |
| 10 |
* |
| 11 |
* Provides an additive builder for CSP headers: directives and their expressions are |
| 12 |
* accumulated via {@see add()}, with duplicates silently ignored. Expressions are |
| 13 |
* validated against the CSP spec: {@link https://www.w3.org/TR/CSP3/} |
| 14 |
* |
| 15 |
* Fetch directives fall back through their inheritance chain to `default-src` when |
| 16 |
* queried via {@see getDirective()}, but {@see getRawDirective()} and |
| 17 |
* {@see hasRawDirective()} skip inheritance. |
| 18 |
* |
| 19 |
* The first nonce encountered across all directives is exposed via {@see getNonce()}. |
| 20 |
* |
| 21 |
* {@see fromString()} parses an existing CSP header string back into a `Csp` instance, |
| 22 |
* and {@see merge()} combines multiple `Csp` instances into one, deduplicating |
| 23 |
* expressions and preserving the base nonce. |
| 24 |
*/ |
| 25 |
class Csp implements Stringable |
| 26 |
{ |
| 27 |
/** @var list<string> The hash algorithms that can be used in the Csp header */ |
| 28 |
protected const AVAILABLE_HASHES = [ |
| 29 |
'sha256', |
| 30 |
'sha384', |
| 31 |
'sha512', |
| 32 |
]; |
| 33 |
|
| 34 |
/** @var list<string> The keywords that can be used in the Csp header */ |
| 35 |
protected const AVAILABLE_KEYWORDS = [ |
| 36 |
"'self'", |
| 37 |
"'none'", |
| 38 |
"'strict-dynamic'", |
| 39 |
"'report-sample'", |
| 40 |
"'unsafe-inline'", |
| 41 |
"'unsafe-eval'", |
| 42 |
"'unsafe-hashes'", |
| 43 |
"'wasm-unsafe-eval'", |
| 44 |
"'allow-duplicates'", |
| 45 |
]; |
| 46 |
|
| 47 |
/** @var list<string> The keywords that can be used in the Csp header without quotes */ |
| 48 |
protected const AVAILABLE_UNQUOTED_KEYWORDS = [ |
| 49 |
'allow-downloads', |
| 50 |
'allow-forms', |
| 51 |
'allow-modals', |
| 52 |
'allow-orientation-lock', |
| 53 |
'allow-pointer-lock', |
| 54 |
'allow-popups', |
| 55 |
'allow-popups-to-escape-sandbox', |
| 56 |
'allow-presentation', |
| 57 |
'allow-same-origin', |
| 58 |
'allow-scripts', |
| 59 |
'allow-storage-access-by-user-activation', |
| 60 |
'allow-top-navigation', |
| 61 |
'allow-top-navigation-by-user-activation', |
| 62 |
'allow-top-navigation-to-custom-protocols', |
| 63 |
]; |
| 64 |
|
| 65 |
/** @var array<string, string> The characters that can't appear in expressions */ |
| 66 |
protected const EXPRESSION_FORBIDDEN_CHARACTERS = [ |
| 67 |
';' => ';', |
| 68 |
"\r" => '\r', |
| 69 |
"\n" => '\n', |
| 70 |
"\t" => '\t', |
| 71 |
"\0" => '\0', |
| 72 |
]; |
| 73 |
|
| 74 |
/** |
| 75 |
* Fetch directive inheritance map |
| 76 |
* |
| 77 |
* All fetch directives eventually have the `default-src` directive as their parent. |
| 78 |
* |
| 79 |
* @var array<string, ?string> |
| 80 |
*/ |
| 81 |
protected const FETCH_DIRECTIVES = [ |
| 82 |
'child-src' => 'default-src', |
| 83 |
'connect-src' => 'default-src', |
| 84 |
'default-src' => null, |
| 85 |
'fenced-frame-src' => 'default-src', |
| 86 |
'font-src' => 'default-src', |
| 87 |
'frame-src' => 'default-src', |
| 88 |
'img-src' => 'default-src', |
| 89 |
'manifest-src' => 'default-src', |
| 90 |
'media-src' => 'default-src', |
| 91 |
'object-src' => 'default-src', |
| 92 |
'prefetch-src' => 'default-src', |
| 93 |
'script-src' => 'default-src', |
| 94 |
'script-src-attr' => 'script-src', |
| 95 |
'script-src-elem' => 'script-src', |
| 96 |
'style-src' => 'default-src', |
| 97 |
'style-src-attr' => 'style-src', |
| 98 |
'style-src-elem' => 'style-src', |
| 99 |
]; |
| 100 |
|
| 101 |
/** @var list<string> The directives that must be empty */ |
| 102 |
protected const MANDATORY_EMPTY_DIRECTIVES = [ |
| 103 |
'block-all-mixed-content', |
| 104 |
'upgrade-insecure-requests', |
| 105 |
]; |
| 106 |
|
| 107 |
/** @var list<string> The directives that can be empty */ |
| 108 |
protected const POSSIBLE_EMPTY_DIRECTIVES = [ |
| 109 |
'sandbox', |
| 110 |
]; |
| 111 |
|
| 112 |
/** @var array<string, list<string>> The directives and their values */ |
| 113 |
protected array $directives = []; |
| 114 |
|
| 115 |
/** |
| 116 |
* First nonce found in the directives |
| 117 |
* |
| 118 |
* This assumes there will only ever be one nonce. |
| 119 |
* |
| 120 |
* @var ?string |
| 121 |
*/ |
| 122 |
protected ?string $nonce = null; |
| 123 |
|
| 124 |
/** |
| 125 |
* Create a new CSP from a string |
| 126 |
* |
| 127 |
* @param string $header The CSP header string |
| 128 |
* |
| 129 |
* @return static A new CSP containing all directives from the input header |
| 130 |
* |
| 131 |
* @throws InvalidArgumentException If the input header contains an invalid |
| 132 |
* directive or expression. |
| 133 |
*/ |
| 134 |
public static function fromString(string $header): static |
| 135 |
{ |
| 136 |
$header = str_replace(["\r\n", "\n", "\r"], ' ', $header); |
| 137 |
$result = new static(); |
| 138 |
foreach (explode(';', $header) as $directive) { |
| 139 |
$directive = trim($directive); |
| 140 |
if (empty($directive)) { |
| 141 |
continue; |
| 142 |
} |
| 143 |
|
| 144 |
$parts = preg_split('/\s+/', $directive, 2); |
| 145 |
if ($parts === false) { |
| 146 |
throw new InvalidArgumentException("Failed to split directive: $directive"); |
| 147 |
} |
| 148 |
|
| 149 |
if (count($parts) === 1) { |
| 150 |
$name = $parts[0]; |
| 151 |
if (! $result->canDirectiveBeEmpty($name)) { |
| 152 |
throw new InvalidArgumentException( |
| 153 |
"Directives must contain the directive name and at least one expression. Directive: $directive" |
| 154 |
); |
| 155 |
} |
| 156 |
|
| 157 |
$result->add($name, null); |
| 158 |
} else { |
| 159 |
$result->add(...$parts); |
| 160 |
} |
| 161 |
} |
| 162 |
|
| 163 |
return $result; |
| 164 |
} |
| 165 |
|
| 166 |
/** |
| 167 |
* Check whether a given directive can be empty |
| 168 |
* |
| 169 |
* Only a subset of directives can be empty. Allowing them to be empty does not mean |
| 170 |
* they cannot have a value, only that it can be omitted. |
| 171 |
* |
| 172 |
* @param string $directive The directive name |
| 173 |
* |
| 174 |
* @return bool |
| 175 |
*/ |
| 176 |
protected function canDirectiveBeEmpty(string $directive): bool |
| 177 |
{ |
| 178 |
return in_array($directive, static::POSSIBLE_EMPTY_DIRECTIVES, true) |
| 179 |
|| in_array($directive, static::MANDATORY_EMPTY_DIRECTIVES, true); |
| 180 |
} |
| 181 |
|
| 182 |
/** |
| 183 |
* Add a directive with an expression or a list of expressions to the CSP |
| 184 |
* |
| 185 |
* @param string $directive The directive name |
| 186 |
* @param string|list<string>|null $value The expression or list of expressions to |
| 187 |
* add. Note that adding multiple expressions with an array or a space-separated |
| 188 |
* string is equivalent to adding each expression individually one by one, the |
| 189 |
* behavior is therefore not atomic. |
| 190 |
* |
| 191 |
* @return $this |
| 192 |
* |
| 193 |
* @throws InvalidArgumentException If the directive name, expression, or directive |
| 194 |
* value state is invalid. |
| 195 |
*/ |
| 196 |
public function add(string $directive, string|array|null $value): static |
| 197 |
{ |
| 198 |
if (! preg_match('/^[a-z\-]+$/', $directive)) { |
| 199 |
throw new InvalidArgumentException( |
| 200 |
"Directive names contain only lowercase letters and '-'. Directive: $directive", |
| 201 |
); |
| 202 |
} |
| 203 |
|
| 204 |
if ($value !== null && in_array($directive, static::MANDATORY_EMPTY_DIRECTIVES, true)) { |
| 205 |
throw new InvalidArgumentException( |
| 206 |
"Directive $directive can't have a value." |
| 207 |
); |
| 208 |
} |
| 209 |
|
| 210 |
if ($value === null) { |
| 211 |
if (! $this->canDirectiveBeEmpty($directive)) { |
| 212 |
throw new InvalidArgumentException( |
| 213 |
"Directive $directive can't be empty." |
| 214 |
); |
| 215 |
} |
| 216 |
$this->directives[$directive] ??= []; |
| 217 |
} elseif (is_string($value)) { |
| 218 |
$value = trim($value, ' '); |
| 219 |
|
| 220 |
if (str_contains($value, ' ')) { |
| 221 |
$values = preg_split('/\s+/', trim($value)); |
| 222 |
if ($values === false) { |
| 223 |
throw new InvalidArgumentException("Failed to split expression: $value"); |
| 224 |
} |
| 225 |
|
| 226 |
return $this->add($directive, $values); |
| 227 |
} |
| 228 |
|
| 229 |
$this->validateExpression($directive, $value); |
| 230 |
|
| 231 |
if (in_array($value, $this->directives[$directive] ?? [], true)) { |
| 232 |
return $this; |
| 233 |
} |
| 234 |
|
| 235 |
if ($this->nonce === null && $this->isNonce($value)) { |
| 236 |
$this->nonce = substr($value, 7, -1); |
| 237 |
} |
| 238 |
|
| 239 |
$this->directives[$directive][] = $value; |
| 240 |
} else { |
| 241 |
if ($value === []) { |
| 242 |
return $this->add($directive, null); |
| 243 |
} |
| 244 |
foreach ($value as $expression) { |
| 245 |
$this->add($directive, $expression); |
| 246 |
} |
| 247 |
} |
| 248 |
|
| 249 |
return $this; |
| 250 |
} |
| 251 |
|
| 252 |
/** |
| 253 |
* Validate an expression |
| 254 |
* |
| 255 |
* Throws an exception if the expression is invalid. |
| 256 |
* |
| 257 |
* @param string $directive The directive name |
| 258 |
* @param string $expression The expression to validate |
| 259 |
* |
| 260 |
* @return void |
| 261 |
* |
| 262 |
* @throws InvalidArgumentException If the expression is invalid. |
| 263 |
*/ |
| 264 |
protected function validateExpression(string $directive, string $expression): void |
| 265 |
{ |
| 266 |
if ($expression === '') { |
| 267 |
throw new InvalidArgumentException('Expression must not be empty.'); |
| 268 |
} |
| 269 |
|
| 270 |
if ($expression === '*') { |
| 271 |
return; |
| 272 |
} |
| 273 |
|
| 274 |
foreach (static::EXPRESSION_FORBIDDEN_CHARACTERS as $char => $str) { |
| 275 |
if (str_contains($expression, $char)) { |
| 276 |
throw new InvalidArgumentException( |
| 277 |
sprintf("Expression must not contain '%s'.", $str), |
| 278 |
); |
| 279 |
} |
| 280 |
} |
| 281 |
|
| 282 |
// Reporting names |
| 283 |
if ($directive === 'report-to' && preg_match('/^[a-zA-Z0-9_-]+$/', $expression)) { |
| 284 |
return; |
| 285 |
} |
| 286 |
|
| 287 |
if (in_array($expression, static::AVAILABLE_UNQUOTED_KEYWORDS, true)) { |
| 288 |
return; |
| 289 |
} |
| 290 |
|
| 291 |
if ( |
| 292 |
(str_starts_with($expression, "'") && ! str_ends_with($expression, "'")) |
| 293 |
|| ! str_starts_with($expression, "'") && str_ends_with($expression, "'") |
| 294 |
) { |
| 295 |
throw new InvalidArgumentException( |
| 296 |
"Quoted expression must be fully surrounded by single quotes. Expression: $expression", |
| 297 |
); |
| 298 |
} |
| 299 |
|
| 300 |
if (str_starts_with($expression, "'") && str_ends_with($expression, "'")) { |
| 301 |
if (str_starts_with($expression, "'nonce-")) { |
| 302 |
if (strlen($expression) < 9) { |
| 303 |
throw new InvalidArgumentException("Nonce must have a value. Expression: $expression"); |
| 304 |
} |
| 305 |
|
| 306 |
return; |
| 307 |
} |
| 308 |
|
| 309 |
if (str_starts_with($expression, "'report-") && $expression !== "'report-sample'") { |
| 310 |
foreach (static::AVAILABLE_HASHES as $hash) { |
| 311 |
if ($expression === sprintf("'report-%s'", $hash)) { |
| 312 |
return; |
| 313 |
} |
| 314 |
} |
| 315 |
throw new InvalidArgumentException("Unsupported hash type. Expression: $expression"); |
| 316 |
} |
| 317 |
|
| 318 |
if (preg_match('/^\'([a-zA-Z0-9]+)-/', $expression, $matches)) { |
| 319 |
$hash = $matches[1]; |
| 320 |
if (in_array($hash, static::AVAILABLE_HASHES, true)) { |
| 321 |
if (strlen($expression) <= strlen($hash) + 3) { |
| 322 |
throw new InvalidArgumentException("Hash must have a value. Expression: $expression"); |
| 323 |
} |
| 324 |
|
| 325 |
return; |
| 326 |
} |
| 327 |
} |
| 328 |
|
| 329 |
if (! in_array($expression, static::AVAILABLE_KEYWORDS, true)) { |
| 330 |
throw new InvalidArgumentException("Unsupported keyword. Expression: $expression"); |
| 331 |
} |
| 332 |
|
| 333 |
return; |
| 334 |
} |
| 335 |
|
| 336 |
// scheme: and scheme://* |
| 337 |
if (preg_match('/^[a-z]+:(\/\/\*)?$/', $expression)) { |
| 338 |
return; |
| 339 |
} |
| 340 |
|
| 341 |
preg_match( |
| 342 |
'/^(?:(?<scheme>[a-z]+):\/\/)?(?<host>(?:[a-z0-9_*-]+\.)*[a-z0-9*]+)' |
| 343 |
. '(?::(?<port>-?[0-9]+|\*))?(?<path>(?:\/[a-z0-9%_.\-*]+)*)\/?$/i', |
| 344 |
$expression, |
| 345 |
$parsedUrl, |
| 346 |
); |
| 347 |
|
| 348 |
if (($parsedUrl['host'] ?? '') === '') { |
| 349 |
throw new InvalidArgumentException("Expression URL must specify a host. Expression: $expression"); |
| 350 |
} |
| 351 |
|
| 352 |
if (substr_count($parsedUrl['host'], '*') > 1) { |
| 353 |
throw new InvalidArgumentException( |
| 354 |
"Expression URL can't contain more than one wildcard. Expression: $expression", |
| 355 |
); |
| 356 |
} |
| 357 |
|
| 358 |
if (str_starts_with($parsedUrl['host'], '*')) { |
| 359 |
if (! str_starts_with($parsedUrl['host'], '*.')) { |
| 360 |
throw new InvalidArgumentException("Wildcard host must be a full subdomain. Expression: $expression"); |
| 361 |
} |
| 362 |
} elseif (str_contains($parsedUrl['host'], '*')) { |
| 363 |
throw new InvalidArgumentException( |
| 364 |
"Wildcards can only be used at the start of the host. Expression: $expression", |
| 365 |
); |
| 366 |
} |
| 367 |
|
| 368 |
if ($parsedUrl['path'] !== '' && str_contains($parsedUrl['path'], '*')) { |
| 369 |
throw new InvalidArgumentException("Wildcards can't be used in the path. Expression: $expression"); |
| 370 |
} |
| 371 |
|
| 372 |
if ($parsedUrl['port'] !== '') { |
| 373 |
if ($parsedUrl['port'] === '*') { |
| 374 |
return; |
| 375 |
} |
| 376 |
|
| 377 |
if (! is_numeric($parsedUrl['port'])) { |
| 378 |
throw new InvalidArgumentException("Port must be a number. Expression: $expression"); |
| 379 |
} |
| 380 |
|
| 381 |
if ($parsedUrl['port'] <= 0 || $parsedUrl['port'] > 0xFFFF) { |
| 382 |
throw new InvalidArgumentException("Port must be between 1 and 65535. Expression: $expression"); |
| 383 |
} |
| 384 |
} |
| 385 |
} |
| 386 |
|
| 387 |
/** |
| 388 |
* Check whether an expression is a nonce |
| 389 |
* |
| 390 |
* @param string $expression The expression to check |
| 391 |
* |
| 392 |
* @return bool |
| 393 |
*/ |
| 394 |
protected function isNonce(string $expression): bool |
| 395 |
{ |
| 396 |
return str_starts_with($expression, "'nonce-") && str_ends_with($expression, "'"); |
| 397 |
} |
| 398 |
|
| 399 |
/** |
| 400 |
* Get the fully formatted CSP header string |
| 401 |
* |
| 402 |
* This can be used directly in the Content-Security-Policy header. |
| 403 |
* |
| 404 |
* @return string The CSP header string |
| 405 |
*/ |
| 406 |
public function getHeader(): string |
| 407 |
{ |
| 408 |
$directiveStrings = []; |
| 409 |
foreach ($this->directives as $directive => $expressions) { |
| 410 |
$directiveStrings[] = implode(' ', array_merge([$directive], $expressions)); |
| 411 |
} |
| 412 |
return implode('; ', $directiveStrings); |
| 413 |
} |
| 414 |
|
| 415 |
/** |
| 416 |
* Get the values of a directive |
| 417 |
* |
| 418 |
* @param string $directive The directive name. Note that this can be a fetch directive, |
| 419 |
* in which case the values will be fetched from its designated parent directive. |
| 420 |
* |
| 421 |
* @return list<string> |
| 422 |
*/ |
| 423 |
public function getDirective(string $directive): array |
| 424 |
{ |
| 425 |
if (isset($this->directives[$directive])) { |
| 426 |
return $this->directives[$directive]; |
| 427 |
} elseif (isset(static::FETCH_DIRECTIVES[$directive])) { |
| 428 |
return $this->getDirective(static::FETCH_DIRECTIVES[$directive]); |
| 429 |
} |
| 430 |
|
| 431 |
return []; |
| 432 |
} |
| 433 |
|
| 434 |
/** |
| 435 |
* Get all directives |
| 436 |
* |
| 437 |
* @return array<string, list<string>> |
| 438 |
*/ |
| 439 |
public function getDirectives(): array |
| 440 |
{ |
| 441 |
return $this->directives; |
| 442 |
} |
| 443 |
|
| 444 |
/** |
| 445 |
* Get the first nonce found in the directives |
| 446 |
* |
| 447 |
* This can be used to set the nonce in a script or style tag. |
| 448 |
* |
| 449 |
* @return ?string The first nonce found in the directives. |
| 450 |
*/ |
| 451 |
public function getNonce(): ?string |
| 452 |
{ |
| 453 |
return $this->nonce; |
| 454 |
} |
| 455 |
|
| 456 |
/** |
| 457 |
* Get the values of a directive without inheritance fallback |
| 458 |
* |
| 459 |
* @param string $directive The directive name |
| 460 |
* |
| 461 |
* @return ?list<string> |
| 462 |
*/ |
| 463 |
public function getRawDirective(string $directive): ?array |
| 464 |
{ |
| 465 |
return $this->directives[$directive] ?? null; |
| 466 |
} |
| 467 |
|
| 468 |
/** |
| 469 |
* Check whether a directive is present |
| 470 |
* |
| 471 |
* This follows the fetch directive inheritance chain. |
| 472 |
* |
| 473 |
* @param string $directive The directive name |
| 474 |
* |
| 475 |
* @return bool |
| 476 |
*/ |
| 477 |
public function hasDirective(string $directive): bool |
| 478 |
{ |
| 479 |
if ($this->hasRawDirective($directive)) { |
| 480 |
return true; |
| 481 |
} elseif (isset(static::FETCH_DIRECTIVES[$directive])) { |
| 482 |
return $this->hasDirective(static::FETCH_DIRECTIVES[$directive]); |
| 483 |
} |
| 484 |
|
| 485 |
return false; |
| 486 |
} |
| 487 |
|
| 488 |
/** |
| 489 |
* Check whether a directive is present |
| 490 |
* |
| 491 |
* @param string $directive The directive name |
| 492 |
* |
| 493 |
* @return bool |
| 494 |
*/ |
| 495 |
public function hasRawDirective(string $directive): bool |
| 496 |
{ |
| 497 |
return isset($this->directives[$directive]); |
| 498 |
} |
| 499 |
|
| 500 |
/** |
| 501 |
* Check whether the CSP does not contain any directives |
| 502 |
* |
| 503 |
* @return bool |
| 504 |
*/ |
| 505 |
public function isEmpty(): bool |
| 506 |
{ |
| 507 |
return $this->directives === []; |
| 508 |
} |
| 509 |
|
| 510 |
/** |
| 511 |
* Merge multiple CSPs into the current one |
| 512 |
* |
| 513 |
* @param Csp ...$csps The CSPs to merge |
| 514 |
* |
| 515 |
* @return $this |
| 516 |
*/ |
| 517 |
public function merge(Csp ...$csps): static |
| 518 |
{ |
| 519 |
foreach ($csps as $csp) { |
| 520 |
foreach ($csp->directives as $directive => $values) { |
| 521 |
$this->add($directive, $values === [] ? null : $values); |
| 522 |
} |
| 523 |
} |
| 524 |
|
| 525 |
return $this; |
| 526 |
} |
| 527 |
|
| 528 |
public function __toString(): string |
| 529 |
{ |
| 530 |
return $this->getHeader(); |
| 531 |
} |
| 532 |
} |