| 1 |
<?php |
| 2 |
|
| 3 |
namespace ipl\Web\Common; |
| 4 |
|
| 5 |
use Error; |
| 6 |
use ipl\Html\Contract\FormElement; |
| 7 |
use ipl\Html\FormElement\HiddenElement; |
| 8 |
|
| 9 |
trait CsrfCounterMeasure |
| 10 |
{ |
| 11 |
/** @var ?string The ID of the CSRF form element */ |
| 12 |
private ?string $csrfCounterMeasureId = null; |
| 13 |
|
| 14 |
/** @var bool Whether to actually add the CSRF element to the form */ |
| 15 |
private bool $csrfCounterMeasureEnabled = true; |
| 16 |
|
| 17 |
/** |
| 18 |
* Set the ID for the CSRF form element |
| 19 |
* |
| 20 |
* @param string $id A unique ID that persists through different requests |
| 21 |
* |
| 22 |
* @return $this |
| 23 |
*/ |
| 24 |
public function setCsrfCounterMeasureId(string $id): static |
| 25 |
{ |
| 26 |
$this->csrfCounterMeasureId = $id; |
| 27 |
|
| 28 |
return $this; |
| 29 |
} |
| 30 |
|
| 31 |
/** |
| 32 |
* Disable the CSRF form element |
| 33 |
* |
| 34 |
* @return void |
| 35 |
*/ |
| 36 |
public function disableCsrfCounterMeasure(): void |
| 37 |
{ |
| 38 |
$this->csrfCounterMeasureEnabled = false; |
| 39 |
} |
| 40 |
|
| 41 |
/** |
| 42 |
* Create a form element to countermeasure CSRF attacks |
| 43 |
* |
| 44 |
* If the {@see requestIsSafe()} check concludes the request is safe, returns a dummy element that accepts any |
| 45 |
* value. If it concludes the request is unsafe, throws an {@see Error}. If the check is inconclusive (legacy |
| 46 |
* browser), creates a token-based CSRF element validated against $uniqueId. |
| 47 |
* |
| 48 |
* @param string $uniqueId A unique ID that persists through different requests |
| 49 |
* |
| 50 |
* @return FormElement |
| 51 |
* |
| 52 |
* @throws Error If {@see requestIsSafe()} returns false |
| 53 |
* |
| 54 |
* @deprecated Use {@see addCsrfCounterMeasure()} instead |
| 55 |
*/ |
| 56 |
protected function createCsrfCounterMeasure($uniqueId) |
| 57 |
{ |
| 58 |
$requestIsSafe = $this->requestIsSafe(); |
| 59 |
|
| 60 |
if ($requestIsSafe !== null) { |
| 61 |
if (! $requestIsSafe) { |
| 62 |
throw new Error('Rejecting cross-site request'); |
| 63 |
} |
| 64 |
|
| 65 |
return new HiddenElement('CSRFToken', [ |
| 66 |
'ignore' => true, |
| 67 |
'validators' => ['Callback' => function () { |
| 68 |
return true; |
| 69 |
}] |
| 70 |
]); |
| 71 |
} |
| 72 |
|
| 73 |
$hashAlgo = in_array('sha3-256', hash_algos(), true) ? 'sha3-256' : 'sha256'; |
| 74 |
|
| 75 |
$seed = random_bytes(16); |
| 76 |
$token = base64_encode($seed) . '|' . hash($hashAlgo, $uniqueId . $seed); |
| 77 |
|
| 78 |
$options = [ |
| 79 |
'ignore' => true, |
| 80 |
'required' => true, |
| 81 |
'validators' => ['Callback' => function ($token) use ($uniqueId, $hashAlgo) { |
| 82 |
if (empty($token) || strpos($token, '|') === false) { |
| 83 |
throw new Error('Invalid CSRF token provided'); |
| 84 |
} |
| 85 |
|
| 86 |
list($seed, $hash) = explode('|', $token); |
| 87 |
|
| 88 |
if ($hash !== hash($hashAlgo, $uniqueId . base64_decode($seed))) { |
| 89 |
throw new Error('Invalid CSRF token provided'); |
| 90 |
} |
| 91 |
|
| 92 |
return true; |
| 93 |
}] |
| 94 |
]; |
| 95 |
|
| 96 |
$element = new class ('CSRFToken', $options) extends HiddenElement { |
| 97 |
public function hasValue(): bool |
| 98 |
{ |
| 99 |
return true; // The validator must run even if the value is empty |
| 100 |
} |
| 101 |
}; |
| 102 |
|
| 103 |
$element->getAttributes()->registerAttributeCallback('value', function () use ($token) { |
| 104 |
return $token; |
| 105 |
}); |
| 106 |
|
| 107 |
return $element; |
| 108 |
} |
| 109 |
|
| 110 |
/** |
| 111 |
* Add the CSRF form element to this form |
| 112 |
* |
| 113 |
* Does nothing if disabled via {@see disableCsrfCounterMeasure()}. |
| 114 |
* Unless passed as argument, requires a unique ID to be set via {@see setCsrfCounterMeasureId()}. |
| 115 |
* |
| 116 |
* @param ?string $uniqueId A unique ID that persists through different requests |
| 117 |
* |
| 118 |
* @return void |
| 119 |
*/ |
| 120 |
protected function addCsrfCounterMeasure(?string $uniqueId = null): void |
| 121 |
{ |
| 122 |
if (! $this->csrfCounterMeasureEnabled) { |
| 123 |
return; |
| 124 |
} |
| 125 |
|
| 126 |
if ($uniqueId === null && $this->csrfCounterMeasureId === null) { |
| 127 |
throw new Error('No CSRF counter measure ID set'); |
| 128 |
} |
| 129 |
|
| 130 |
$this->addElement($this->createCsrfCounterMeasure($uniqueId ?? $this->csrfCounterMeasureId)); |
| 131 |
} |
| 132 |
|
| 133 |
/** |
| 134 |
* Get whether the request is safe from CSRF based on the Sec-Fetch-Site header |
| 135 |
* |
| 136 |
* Returns true if the header indicates a same-origin request or a user-originated operation (e.g. typing a URL), |
| 137 |
* both of which cannot be forged by a cross-site attacker. Returns false if the header indicates a cross-site |
| 138 |
* request. Returns null in two cases where a token-based fallback should be used instead: when the request uses an |
| 139 |
* RFC 9110 safe method (GET, HEAD, OPTIONS, TRACE), which cannot carry CSRF side effects by definition, or when |
| 140 |
* the header is absent, indicating a legacy browser that must be validated via the CSRF token. |
| 141 |
* |
| 142 |
* @see https://datatracker.ietf.org/doc/html/rfc9110#section-9.2.1 |
| 143 |
* |
| 144 |
* @return ?bool |
| 145 |
*/ |
| 146 |
protected function requestIsSafe(): ?bool |
| 147 |
{ |
| 148 |
if (in_array($_SERVER['REQUEST_METHOD'] ?? null, ['GET', 'HEAD', 'OPTIONS', 'TRACE'], true)) { |
| 149 |
return null; |
| 150 |
} |
| 151 |
|
| 152 |
return match ($_SERVER['HTTP_SEC_FETCH_SITE'] ?? null) { |
| 153 |
'same-origin' => true, // same scheme, host and port |
| 154 |
'none' => true, // a user-originated operation |
| 155 |
null => null, // legacy browser without Sec-Fetch-Site support |
| 156 |
default => false, |
| 157 |
}; |
| 158 |
} |
| 159 |
} |