lowercase map]. * $directory = ['keys' => [JWK…]] or null. * Returns ['status' => valid|invalid|unsupported|nokey|none, 'agent' => url|null, 'reason' => string]. */ function realbots_wba_verify($req, $directory, $now = null) { $now = $now === null ? time() : (int) $now; $h = $req['headers']; $res = array('status' => 'none', 'agent' => null, 'reason' => ''); if (empty($h['signature-input']) || empty($h['signature'])) { return $res; } $inputs = realbots_sf_dict($h['signature-input']); $label = null; foreach ($inputs as $l => $member) { $pp = realbots_sf_params(substr($member, (int) strpos($member, ')') + 1)); if (($pp['tag'] ?? '') === 'web-bot-auth') { $label = $l; break; } } if ($label === null) { return $res; } $res['status'] = 'invalid'; $member = $inputs[$label]; $close = strpos($member, ')'); if ($member === '' || $member[0] !== '(' || $close === false) { $res['reason'] = 'bad Signature-Input'; return $res; } $params = realbots_sf_params(substr($member, $close + 1)); preg_match_all('/"((?:[^"\\\\]|\\\\.)*)"((?:;[a-z0-9_.*-]+(?:="(?:[^"\\\\]|\\\\.)*"|=[^\s;"]+)?)*)/i', substr($member, 1, $close - 1), $cm, PREG_SET_ORDER); $qi = strpos($req['path'], '?'); $path_only = $qi === false ? $req['path'] : substr($req['path'], 0, $qi); $lines = array(); $covers_authority = false; $agent_key = null; foreach ($cm as $c) { $name = $c[1]; $cp = realbots_sf_params($c[2]); switch ($name) { case '@authority': $v = strtolower($req['authority']); $covers_authority = true; break; case '@target-uri': $v = $req['scheme'] . '://' . strtolower($req['authority']) . $req['path']; $covers_authority = true; break; case '@method': $v = strtoupper($req['method']); break; case '@path': $v = $path_only === '' ? '/' : $path_only; break; case '@query': $v = '?' . ($qi === false ? '' : substr($req['path'], $qi + 1)); break; case '@scheme': $v = $req['scheme']; break; default: if ($name !== '' && $name[0] === '@') { $res['reason'] = "unsupported component $name"; return $res; } $raw = $h[strtolower($name)] ?? null; if ($raw === null) { $res['reason'] = "covered header $name missing"; return $res; } if (!empty($cp['key'])) { $d = realbots_sf_dict($raw); if (!isset($d[$cp['key']])) { $res['reason'] = "$name has no member " . $cp['key']; return $res; } $v = $d[$cp['key']]; if ($name === 'signature-agent') { $agent_key = $cp['key']; } } else { $v = trim(preg_replace('/\s*\n\s*/', ' ', $raw)); if ($name === 'signature-agent') { $agent_key = ''; } } } $lines[] = $c[0] . ': ' . $v; } $lines[] = '"@signature-params": ' . $member; $base = implode("\n", $lines); // Signature-Agent: dictionary member covered by the signature, or legacy string. $sa = trim((string) ($h['signature-agent'] ?? '')); if ($sa !== '' && $agent_key !== null) { if ($sa[0] === '"') { $res['agent'] = realbots_sf_unquote($sa); } elseif ($agent_key !== '') { $d = realbots_sf_dict($sa); $res['agent'] = isset($d[$agent_key]) ? realbots_sf_unquote($d[$agent_key]) : null; } } if (!$covers_authority) { $res['reason'] = 'does not cover @authority'; return $res; } // Validate the agent URL: plain https://host[:port][/path], host = DNS name only. if ($res['agent'] !== null && !preg_match('~^https://[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?(?::[0-9]{1,5})?(?:/[\x21-\x7E]{0,512})?$~', $res['agent'])) { $res['agent'] = null; } if (!$res['agent']) { $res['reason'] = 'Signature-Agent missing, uncovered or not https'; return $res; } $created = isset($params['created']) ? (int) $params['created'] : 0; $expires = isset($params['expires']) ? (int) $params['expires'] : 0; if (!$created || $created > $now + 60 || !$expires || $expires <= $now) { $res['reason'] = 'outside created/expires window'; return $res; } $alg = $params['alg'] ?? 'ed25519'; if ($alg !== 'ed25519') { $res['status'] = 'unsupported'; $res['reason'] = "algorithm $alg not supported"; return $res; } $sigs = realbots_sf_dict($h['signature']); if (!isset($sigs[$label]) || !preg_match('/^:([^:]*):/', $sigs[$label], $sm)) { $res['reason'] = "no Signature for label $label"; return $res; } $sig = base64_decode($sm[1], true); if (!is_array($directory)) { $res['status'] = 'nokey'; $res['reason'] = 'key directory unavailable'; return $res; } foreach ((array) ($directory['keys'] ?? array()) as $k) { if (($k['kty'] ?? '') !== 'OKP' || ($k['crv'] ?? '') !== 'Ed25519' || empty($k['x'])) { continue; } if (realbots_okp_thumbprint($k['x']) !== ($params['keyid'] ?? '')) { continue; } $pk = realbots_b64url_decode($k['x']); if ($sig !== false && $pk !== false && strlen($pk) === SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES && strlen($sig) === SODIUM_CRYPTO_SIGN_BYTES && sodium_crypto_sign_verify_detached($sig, $base, $pk)) { $res['status'] = 'valid'; $res['reason'] = ''; return $res; } $res['reason'] = 'signature does not verify'; return $res; } $res['status'] = 'nokey'; $res['reason'] = 'no directory key matches keyid'; return $res; } /** * Key directory for a Signature-Agent URL: cached 1 day (failures 1 hour), * fetched with wp_safe_remote_get (refuses private/internal hosts, SSRF-safe), * https only, 2 s timeout, at most 20 new agent lookups per hour. */ function realbots_wba_directory($agent) { $agent = apply_filters('realbots_wba_agent_url', $agent); $p = wp_parse_url($agent); if (empty($p['host']) || ($p['scheme'] ?? '') !== 'https') { return null; } $origin = 'https://' . strtolower($p['host']) . (isset($p['port']) ? ':' . (int) $p['port'] : ''); $ck = 'realbots_dir_' . md5($origin); $cached = get_transient($ck); if ($cached !== false) { return is_array($cached) ? $cached : null; } $test = apply_filters('realbots_wba_directory_override', null, $origin); if (is_array($test)) { return $test; } if (!realbots_agent_keys_allowed()) { return null; } $n = (int) get_transient('realbots_dir_lookups'); if ($n >= 20) { return null; } set_transient('realbots_dir_lookups', $n + 1, HOUR_IN_SECONDS); $r = wp_safe_remote_get($origin . '/.well-known/http-message-signatures-directory', array( 'timeout' => 2, 'redirection' => 0, 'limit_response_size' => 65536, // Plugin name only: unlike WordPress's default user-agent, no site address or WordPress version. 'user-agent' => realbots_http_user_agent(), 'headers' => array('Accept' => 'application/http-message-signatures-directory+json'), )); $dir = null; if (!is_wp_error($r) && wp_remote_retrieve_response_code($r) === 200) { $j = json_decode(wp_remote_retrieve_body($r), true); if (is_array($j) && isset($j['keys']) && is_array($j['keys'])) { $dir = array('keys' => array_slice($j['keys'], 0, 20)); } } set_transient($ck, $dir === null ? 'none' : $dir, $dir === null ? HOUR_IN_SECONDS : DAY_IN_SECONDS); return $dir; } /** * Sanitize + validate one request header value for signature checking. * Signature checks need the exact bytes the agent signed, and * sanitize_text_field() would strip %xx octets and break valid signatures, so * instead we accept a value only if it is plain visible ASCII (RFC 9110 field * syntax: 0x20-0x7E, at most 8 KB); anything else is rejected (null). * Values are only compared/verified here, never output; what gets stored * (agent host) is validated separately. */ function realbots_wba_sanitize_header($v) { if (!is_string($v)) { return null; } $v = trim($v); if (strlen($v) > 8192 || !preg_match('/^[\x20-\x7E]*$/', $v)) { return null; } return $v; } /** Verify the current request; null when it carries no Web Bot Auth signature. */ function realbots_wba_current() { $get = function ($k) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized + validated by realbots_wba_sanitize_header() (see its docblock) return isset($_SERVER[$k]) ? realbots_wba_sanitize_header(wp_unslash($_SERVER[$k])) : null; }; $sig_input = $get('HTTP_SIGNATURE_INPUT'); if ($sig_input === null || stripos($sig_input, 'web-bot-auth') === false) { return null; } $headers = array( 'signature-input' => $sig_input, 'signature' => $get('HTTP_SIGNATURE'), 'signature-agent' => $get('HTTP_SIGNATURE_AGENT'), ); // Other covered header fields, if any (e.g. agents covering user-agent). foreach (array_keys($_SERVER) as $k) { if (is_string($k) && preg_match('/^HTTP_[A-Z0-9_]{1,64}$/', $k)) { $name = strtolower(str_replace('_', '-', substr($k, 5))); if (!array_key_exists($name, $headers)) { $v = $get($k); if ($v !== null) { $headers[$name] = $v; } } } } $uri = $get('REQUEST_URI'); $method = strtoupper((string) $get('REQUEST_METHOD')); $host = strtolower((string) $get('HTTP_HOST')); $req = array( 'method' => preg_match('/^[A-Z]{1,16}$/', $method) ? $method : 'GET', 'authority' => preg_match('/^[a-z0-9.\-\[\]:]{1,261}$/', $host) ? $host : '', 'path' => $uri === null ? '/' : $uri, 'scheme' => is_ssl() ? 'https' : 'http', 'headers' => $headers, ); $first = realbots_wba_verify($req, null); if ($first['status'] !== 'nokey' || !$first['agent']) { return $first; } return realbots_wba_verify($req, realbots_wba_directory($first['agent'])); }