class-file-tree-producer.php
6 days ago
class-hmac-client.php
6 days ago
class-hmac-server.php
6 days ago
class-http-server.php
6 days ago
class-mysql-dump-producer.php
6 days ago
class-pdo-polyfill.php
6 days ago
class-sqlite-driver-pdo.php
6 days ago
class-staged-artifacts.php
6 days ago
class-staged-endpoints.php
6 days ago
class-staged-push-stream-protocol.php
6 days ago
class-wpdb-driver-pdo.php
6 days ago
export.php
6 days ago
utils.php
6 days ago
class-hmac-server.php
354 lines
| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * HMAC Server for the Site Export API. |
| 5 | * |
| 6 | * This class verifies the HMAC-authenticated control requests generated by |
| 7 | * Site_Export_HMAC_Client. It validates the required X-Auth-* headers and |
| 8 | * checks request freshness before any caller-provided body hash is evaluated. |
| 9 | */ |
| 10 | final class Site_Export_HMAC_Server { |
| 11 | |
| 12 | /** |
| 13 | * Value of the X-Auth-Content-Hash header when the request body is |
| 14 | * deliberately not signed: this literal string stands where a body hash |
| 15 | * would otherwise be. Must match Site_Export_HMAC_Client::UNSIGNED_PAYLOAD. |
| 16 | */ |
| 17 | public const UNSIGNED_PAYLOAD = 'UNSIGNED-PAYLOAD'; |
| 18 | |
| 19 | private const DEFAULT_MAX_CONTROL_BODY_BYTES = 1048576; |
| 20 | |
| 21 | /** @var string */ |
| 22 | private $secret; |
| 23 | |
| 24 | /** @var int */ |
| 25 | private $timestamp_tolerance; |
| 26 | |
| 27 | public function __construct(string $secret, int $timestamp_tolerance = 300) { |
| 28 | $this->secret = $secret; |
| 29 | $this->timestamp_tolerance = $timestamp_tolerance; |
| 30 | } |
| 31 | |
| 32 | /** |
| 33 | * Verify a small command request with a bounded body. |
| 34 | * |
| 35 | * HMAC is the guard for small protocol commands such as preflight, session |
| 36 | * start, plan confirmation, and abort/resume. Large data uploads should use |
| 37 | * authenticated sessions plus per-chunk hashes instead of signing one |
| 38 | * multi-megabyte request body. |
| 39 | */ |
| 40 | public function verify_control_request(array $headers = [], string $body = '', ?float $now = null, ?int $max_body_bytes = null): ?string { |
| 41 | $body_limit = $max_body_bytes ?? self::DEFAULT_MAX_CONTROL_BODY_BYTES; |
| 42 | if (strlen($body) > $body_limit) { |
| 43 | return sprintf( |
| 44 | 'HMAC control request body exceeds %d bytes', |
| 45 | $body_limit |
| 46 | ); |
| 47 | } |
| 48 | |
| 49 | return $this->verify($headers, $body, [], $now); |
| 50 | } |
| 51 | |
| 52 | /** |
| 53 | * Verify a request using explicit inputs. |
| 54 | * |
| 55 | * Returns null on success, or an error string on failure. This convenience |
| 56 | * method receives the full body as a string and is only appropriate for |
| 57 | * compatibility with existing small request flows. New protocol code should |
| 58 | * use verify_control_request() for HMAC-protected commands and avoid |
| 59 | * HMAC-signing large data uploads. |
| 60 | * |
| 61 | * When $files is non-empty, the content hash is computed from uploaded file |
| 62 | * contents rather than $body so multipart uploads verify consistently. |
| 63 | */ |
| 64 | public function verify(array $headers = [], ?string $body = null, array $files = [], ?float $now = null): ?string { |
| 65 | return $this->verify_content_hash_callback( |
| 66 | $headers, |
| 67 | function () use ($body, $files): string { |
| 68 | return $this->compute_received_content_hash($body, $files); |
| 69 | }, |
| 70 | $now |
| 71 | ); |
| 72 | } |
| 73 | |
| 74 | /** |
| 75 | * Verify a request when the caller already computed the received digest. |
| 76 | * |
| 77 | * This exists for bounded protocol code that has already computed the body |
| 78 | * digest. It does not read a request body. Push chunk uploads should use |
| 79 | * session/request capabilities plus per-chunk hashes instead of routing |
| 80 | * large bodies through HMAC verification. |
| 81 | */ |
| 82 | public function verify_content_hash(array $headers, string $received_content_hash, ?float $now = null): ?string { |
| 83 | return $this->verify_content_hash_callback( |
| 84 | $headers, |
| 85 | function () use ($received_content_hash): string { |
| 86 | return $received_content_hash; |
| 87 | }, |
| 88 | $now |
| 89 | ); |
| 90 | } |
| 91 | |
| 92 | /** |
| 93 | * Verify the signed content hash header before the request body is read. |
| 94 | * |
| 95 | * This only authenticates the claim in X-Auth-Content-Hash; it does not |
| 96 | * authenticate any request bytes by itself. Callers must still compare the |
| 97 | * returned hash with the digest of a bounded control payload before acting |
| 98 | * on that payload. Do not use this as a large-upload authentication scheme. |
| 99 | * |
| 100 | * @return array{error:?string,content_hash:?string} |
| 101 | */ |
| 102 | public function verify_signed_content_hash(array $headers, ?float $now = null): array { |
| 103 | $auth = $this->collect_auth_headers($headers); |
| 104 | $auth_error = $this->verify_auth_headers($auth, $now); |
| 105 | if ($auth_error !== null) { |
| 106 | return [ |
| 107 | 'error' => $auth_error, |
| 108 | 'content_hash' => null, |
| 109 | ]; |
| 110 | } |
| 111 | |
| 112 | return [ |
| 113 | 'error' => null, |
| 114 | 'content_hash' => $auth['content_hash'], |
| 115 | ]; |
| 116 | } |
| 117 | |
| 118 | /** |
| 119 | * The received content hash must not be computed until the timestamp, |
| 120 | * nonce, and signature checks pass: bodies and multipart uploads can be |
| 121 | * large and live on slow disks, and unauthenticated callers should not be |
| 122 | * able to force the server to hash them. |
| 123 | */ |
| 124 | private function verify_content_hash_callback(array $headers, callable $received_content_hash, ?float $now = null): ?string { |
| 125 | $auth = $this->collect_auth_headers($headers); |
| 126 | $auth_error = $this->verify_auth_headers($auth, $now); |
| 127 | if ($auth_error !== null) { |
| 128 | return $auth_error; |
| 129 | } |
| 130 | |
| 131 | try { |
| 132 | $actual_content_hash = $received_content_hash(); |
| 133 | } catch (RuntimeException $e) { |
| 134 | return $e->getMessage(); |
| 135 | } |
| 136 | |
| 137 | if (!hash_equals($auth['content_hash'], $actual_content_hash)) { |
| 138 | return 'Content hash mismatch: body was modified in transit'; |
| 139 | } |
| 140 | |
| 141 | return null; |
| 142 | } |
| 143 | |
| 144 | /** |
| 145 | * Verify a request whose body is deliberately not signed. |
| 146 | * |
| 147 | * Instead of a body hash, the signature covers exactly four values: |
| 148 | * the nonce, the timestamp, the HTTP method, and the request target |
| 149 | * (the "path?query" part of the URL). A request body of any size can then |
| 150 | * stream through without either side hashing it, and a captured set of |
| 151 | * auth headers still cannot be reused for a different endpoint or |
| 152 | * method. Protecting the body from tampering is TLS's job. |
| 153 | * |
| 154 | * The X-Auth-Content-Hash header must be the literal string |
| 155 | * UNSIGNED-PAYLOAD. Because of that, headers signed for this check can |
| 156 | * never pass the body-signed checks and vice versa — the two signatures |
| 157 | * are computed over strings that can never be equal. Each route decides |
| 158 | * which check it calls, so a client cannot make a command endpoint |
| 159 | * that requires verify_control_request() accept this body-less check. |
| 160 | * |
| 161 | * @param string $request_target The "path?query" form of the request URL. |
| 162 | */ |
| 163 | public function verify_envelope(array $headers, string $method, string $request_target, ?float $now = null): ?string { |
| 164 | $auth = $this->collect_auth_headers($headers); |
| 165 | if ($auth['content_hash'] !== self::UNSIGNED_PAYLOAD) { |
| 166 | return 'Envelope verification requires the literal UNSIGNED-PAYLOAD content hash'; |
| 167 | } |
| 168 | |
| 169 | $freshness_error = $this->verify_freshness($auth, $now); |
| 170 | if ($freshness_error !== null) { |
| 171 | return $freshness_error; |
| 172 | } |
| 173 | |
| 174 | $message = $auth['nonce'] . $auth['timestamp'] . self::UNSIGNED_PAYLOAD . "\n" . strtoupper($method) . "\n" . $request_target; |
| 175 | $expected_signature = hash_hmac('sha256', $message, $this->secret); |
| 176 | if (!hash_equals($expected_signature, $auth['signature'])) { |
| 177 | return 'HMAC signature verification failed'; |
| 178 | } |
| 179 | |
| 180 | return null; |
| 181 | } |
| 182 | |
| 183 | /** |
| 184 | * Verify the current PHP request using superglobals. |
| 185 | * |
| 186 | * Returns null on success, or an error string on failure. This legacy |
| 187 | * convenience path buffers php://input and should only be used for small |
| 188 | * request bodies. New command endpoints should bound the body and call |
| 189 | * verify_control_request(). Large data routes should not use whole-body |
| 190 | * HMAC verification. |
| 191 | */ |
| 192 | public function verify_globals(?float $now = null): ?string { |
| 193 | $body = file_get_contents('php://input'); |
| 194 | if ($body === false) { |
| 195 | $body = ''; |
| 196 | } |
| 197 | |
| 198 | return $this->verify($this->collect_global_headers(), $body, $_FILES, $now); |
| 199 | } |
| 200 | |
| 201 | private function collect_auth_headers(array $headers): array { |
| 202 | return [ |
| 203 | 'signature' => $this->get_header($headers, 'X-Auth-Signature'), |
| 204 | 'nonce' => $this->get_header($headers, 'X-Auth-Nonce'), |
| 205 | 'timestamp' => $this->get_header($headers, 'X-Auth-Timestamp'), |
| 206 | 'content_hash' => $this->get_header($headers, 'X-Auth-Content-Hash'), |
| 207 | ]; |
| 208 | } |
| 209 | |
| 210 | private function verify_auth_headers(array $auth, ?float $now = null): ?string { |
| 211 | $freshness_error = $this->verify_freshness($auth, $now); |
| 212 | if ($freshness_error !== null) { |
| 213 | return $freshness_error; |
| 214 | } |
| 215 | |
| 216 | $expected_signature = hash_hmac('sha256', $auth['nonce'] . $auth['timestamp'] . $auth['content_hash'], $this->secret); |
| 217 | if (!hash_equals($expected_signature, $auth['signature'])) { |
| 218 | return 'HMAC signature verification failed'; |
| 219 | } |
| 220 | |
| 221 | return null; |
| 222 | } |
| 223 | |
| 224 | /** |
| 225 | * Checks header presence, timestamp tolerance, and nonce length — |
| 226 | * everything except the signature. Body-signed and envelope-signed |
| 227 | * requests compute their signatures over different strings, so each |
| 228 | * caller does its own signature check after this passes. |
| 229 | */ |
| 230 | private function verify_freshness(array $auth, ?float $now = null): ?string { |
| 231 | $signature = $auth['signature']; |
| 232 | $nonce = $auth['nonce']; |
| 233 | $timestamp = $auth['timestamp']; |
| 234 | $signed_content_hash = $auth['content_hash']; |
| 235 | if ($signature === null || $signature === '') { |
| 236 | return 'Missing X-Auth-Signature header'; |
| 237 | } |
| 238 | if ($nonce === null || $nonce === '') { |
| 239 | return 'Missing X-Auth-Nonce header'; |
| 240 | } |
| 241 | if ($timestamp === null || $timestamp === '') { |
| 242 | return 'Missing X-Auth-Timestamp header'; |
| 243 | } |
| 244 | if ($signed_content_hash === null || $signed_content_hash === '') { |
| 245 | return 'Missing X-Auth-Content-Hash header'; |
| 246 | } |
| 247 | |
| 248 | if (!is_numeric($timestamp)) { |
| 249 | return 'Invalid timestamp format'; |
| 250 | } |
| 251 | |
| 252 | $request_time = (float) $timestamp; |
| 253 | $current_time = $now ?? microtime(true); |
| 254 | $time_diff = abs($current_time - $request_time); |
| 255 | |
| 256 | if ($time_diff > $this->timestamp_tolerance) { |
| 257 | return sprintf( |
| 258 | 'Request timestamp expired. Difference: %.2f seconds, max allowed: %d seconds', |
| 259 | $time_diff, |
| 260 | $this->timestamp_tolerance |
| 261 | ); |
| 262 | } |
| 263 | |
| 264 | if (strlen($nonce) < 16) { |
| 265 | return 'Nonce must be at least 16 characters'; |
| 266 | } |
| 267 | |
| 268 | return null; |
| 269 | } |
| 270 | |
| 271 | private function collect_global_headers(): array { |
| 272 | $headers = []; |
| 273 | |
| 274 | if (function_exists('getallheaders')) { |
| 275 | $all_headers = getallheaders(); |
| 276 | if (is_array($all_headers)) { |
| 277 | $headers = $all_headers; |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | foreach ($_SERVER as $key => $value) { |
| 282 | if (strpos($key, 'HTTP_') !== 0 || !is_string($value)) { |
| 283 | continue; |
| 284 | } |
| 285 | |
| 286 | $headers[$key] = $value; |
| 287 | } |
| 288 | |
| 289 | return $headers; |
| 290 | } |
| 291 | |
| 292 | private function get_header(array $headers, string $name): ?string { |
| 293 | foreach ($headers as $key => $value) { |
| 294 | if (!is_string($value)) { |
| 295 | continue; |
| 296 | } |
| 297 | |
| 298 | if (strcasecmp($key, $name) === 0) { |
| 299 | return $value; |
| 300 | } |
| 301 | |
| 302 | if (strcasecmp($key, 'HTTP_' . strtoupper(str_replace('-', '_', $name))) === 0) { |
| 303 | return $value; |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | return null; |
| 308 | } |
| 309 | |
| 310 | private function compute_received_content_hash(?string $body, array $files): string { |
| 311 | if (empty($files)) { |
| 312 | return hash('sha256', $body ?? ''); |
| 313 | } |
| 314 | |
| 315 | $context = hash_init('sha256'); |
| 316 | $this->append_file_hashes($context, $files); |
| 317 | return hash_final($context); |
| 318 | } |
| 319 | |
| 320 | /** |
| 321 | * Walk a PHP $_FILES-style structure in a deterministic order. |
| 322 | */ |
| 323 | private function append_file_hashes($context, array $files): void { |
| 324 | ksort($files); |
| 325 | |
| 326 | foreach ($files as $file_info) { |
| 327 | if (!is_array($file_info)) { |
| 328 | continue; |
| 329 | } |
| 330 | |
| 331 | $tmp_name = $file_info['tmp_name'] ?? null; |
| 332 | $this->append_tmp_name_hash($context, $tmp_name); |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | private function append_tmp_name_hash($context, $tmp_name): void { |
| 337 | if (is_array($tmp_name)) { |
| 338 | ksort($tmp_name); |
| 339 | foreach ($tmp_name as $nested_tmp_name) { |
| 340 | $this->append_tmp_name_hash($context, $nested_tmp_name); |
| 341 | } |
| 342 | return; |
| 343 | } |
| 344 | |
| 345 | if (!is_string($tmp_name) || $tmp_name === '' || !is_readable($tmp_name)) { |
| 346 | return; |
| 347 | } |
| 348 | |
| 349 | if (!@hash_update_file($context, $tmp_name)) { |
| 350 | throw new RuntimeException('Cannot hash uploaded file.'); |
| 351 | } |
| 352 | } |
| 353 | } |
| 354 |