array( 'type' => OPENSSL_KEYTYPE_RSA, 'algo' => OPENSSL_ALGO_SHA256, ), 'rsa-v1_5-sha384' => array( 'type' => OPENSSL_KEYTYPE_RSA, 'algo' => OPENSSL_ALGO_SHA384, ), 'rsa-v1_5-sha512' => array( 'type' => OPENSSL_KEYTYPE_RSA, 'algo' => OPENSSL_ALGO_SHA512, ), // RSA PSS (note: not supported in openssl_verify() until PHP 8.1). 'rsa-pss-sha256' => array( 'type' => OPENSSL_KEYTYPE_RSA, 'algo' => OPENSSL_ALGO_SHA256, ), 'rsa-pss-sha384' => array( 'type' => OPENSSL_KEYTYPE_RSA, 'algo' => OPENSSL_ALGO_SHA384, ), 'rsa-pss-sha512' => array( 'type' => OPENSSL_KEYTYPE_RSA, 'algo' => OPENSSL_ALGO_SHA512, ), // ECDSA. 'ecdsa-p256-sha256' => array( 'type' => OPENSSL_KEYTYPE_EC, 'algo' => OPENSSL_ALGO_SHA256, ), 'ecdsa-p384-sha384' => array( 'type' => OPENSSL_KEYTYPE_EC, 'algo' => OPENSSL_ALGO_SHA384, ), 'ecdsa-p521-sha512' => array( 'type' => OPENSSL_KEYTYPE_EC, 'algo' => OPENSSL_ALGO_SHA512, ), ); /** * Digest algorithms. * * @var string[] */ private $digest_algorithms = array( 'sha-256' => 'sha256', 'sha-512' => 'sha512', ); /** * The most signature labels a request is checked with. Each label can fetch a key. * * @var int */ private const MAX_LABELS = 3; /** * The name of a label or a parameter: a Structured Field key (RFC 8941). RFC 8941 keys are * lowercase; uppercase is accepted, as before, and parameter names are lowercased. * * @var string */ private const SF_KEY = '[A-Za-z*][A-Za-z0-9_.*-]*+'; /** * A Structured Field bare item: a quoted string, or a token, integer, decimal, boolean or byte sequence. * * @var string */ private const SF_VALUE = '(?:"(?:[^"\\\\]++|\\\\.)*+"|[^\s;,()"]++)'; /** * Structured Field parameters. * * @var string */ private const SF_PARAMS = '(?:;\s*' . self::SF_KEY . '(?:=' . self::SF_VALUE . ')?)*+'; /** * Generate RFC-9421 compliant Signature-Input and Signature headers for an outgoing HTTP request. * * @param array $args The request arguments. * @param string $url The request URL. * * @return array Request arguments with signature headers. */ public function sign( $args, $url ) { // Standard components to sign. $components = array( '"@method"' => \strtoupper( $args['method'] ), '"@target-uri"' => $url, '"@authority"' => get_authority( $url ), ); if ( isset( $args['headers']['Collection-Synchronization'] ) ) { $components['"collection-synchronization"'] = $args['headers']['Collection-Synchronization']; } $identifiers = \array_keys( $components ); // Add digest if provided. if ( isset( $args['body'] ) ) { $components['"content-digest"'] = $this->generate_digest( $args['body'] ); $identifiers = \array_keys( $components ); $args['headers']['Content-Digest'] = $components['"content-digest"']; } $params = array( 'created' => \strtotime( $args['headers']['Date'] ), 'keyid' => $args['key_id'], 'alg' => 'rsa-v1_5-sha256', ); // Build the signature base string as per RFC-9421. $signature_base = $this->get_signature_base_string( $components, $params ); $signature = null; \openssl_sign( $signature_base, $signature, $args['private_key'], \OPENSSL_ALGO_SHA256 ); $signature = \base64_encode( $signature ); $args['headers']['Signature-Input'] = 'wp=(' . \implode( ' ', $identifiers ) . ')' . $this->get_params_string( $params ); $args['headers']['Signature'] = 'wp=:' . $signature . ':'; return $args; } /** * Verify the HTTP Signature against a request. * * @since 9.0.0 Returns the verified keyId on success instead of `true`. * @since 9.4.0 Returns the id of the actor that owns the verified key instead of the keyId. * * @param array $headers The HTTP headers. * @param string|null $body The request body, if applicable. * @return string|\WP_Error The id of the actor that owns the verified key on success, WP_Error on failure. */ public function verify( array $headers, $body = null ) { $parsed = $this->parse_signatures( $headers['signature_input'][0] ?? '', $headers['signature'][0] ?? null ); if ( empty( $parsed ) ) { return new \WP_Error( 'no_valid_labels', 'No valid signature labels found.' ); } $errors = new \WP_Error(); foreach ( $parsed as $data ) { $result = $this->verify_signature_label( $data, $headers, $body ); if ( ! \is_wp_error( $result ) ) { /* * Return the key owner of the label that actually verified, so the caller binds * against the real signer instead of guessing among several labels. */ return $result; } $errors->add( $result->get_error_code(), $result->get_error_message() ); } // No valid signature found. $errors->add_data( array( 'status' => 401 ) ); return $errors; } /** * Generate a digest for the request body. * * @param string $body The request body. * * @return string The digest. */ public function generate_digest( $body ) { return 'sha-256=:' . \base64_encode( \hash( 'sha256', $body, true ) ) . ':'; } /** * The keyIds of the labels this verifier checks. * * @since 9.4.4 * * @param array $headers The HTTP headers. * * @return string[] The distinct keyIds, empty when none is present. */ public function get_key_ids( array $headers ) { $key_ids = array(); foreach ( $this->parse_signatures( $headers['signature_input'][0] ?? '', $headers['signature'][0] ?? null ) as $input ) { if ( ! empty( $input['params']['keyid'] ) && \is_string( $input['params']['keyid'] ) ) { $key_ids[] = $input['params']['keyid']; } } return \array_values( \array_unique( $key_ids ) ); } /** * Parse the Signature-Input and Signature headers into the labels that carry a signature. * * Both headers are Structured Field dictionaries (RFC 8941), read member by member with one * grammar for labels and parameters. Reading stops at the first member that does not follow it, * so a label is never checked with some of its parameters left out. A label defined twice keeps * its first position and its last definition. Only the first labels up to MAX_LABELS count, in * header order. * * @param string $signature_input The Signature-Input header. * @param string|null $signature The Signature header. * @return array[] The components, params and signature of each label, keyed by label. */ private function parse_signatures( $signature_input, $signature ) { \preg_match_all( '/\G\s*(' . self::SF_KEY . ')=:([A-Za-z0-9+\/]*+=*+):' . self::SF_PARAMS . '\s*(?:,|\z)/', (string) $signature, $members, PREG_SET_ORDER ); $signatures = \array_column( $members, 2, 1 ); \preg_match_all( '/\G\s*(' . self::SF_KEY . ')=\(((?:\s*' . self::SF_VALUE . self::SF_PARAMS . ')*+)\s*\)(' . self::SF_PARAMS . ')\s*(?:,|\z)/', (string) $signature_input, $members, PREG_SET_ORDER ); $labels = array(); foreach ( $members as $member ) { list( , $label, $inner_list, $params_string ) = $member; if ( ! isset( $signatures[ $label ] ) ) { continue; } \preg_match_all( '/\G\s*(' . self::SF_VALUE . self::SF_PARAMS . ')/', $inner_list, $components ); \preg_match_all( '/\G;\s*(' . self::SF_KEY . ')(?:=(' . self::SF_VALUE . '))?/', $params_string, $pairs, PREG_SET_ORDER ); // Parameter names count in lowercase. A parameter without a value is true; a quoted value loses its quotes and escapes. $params = array(); foreach ( $pairs as $pair ) { $param = $pair[2] ?? true; if ( \is_string( $param ) && '"' === $param[0] ) { $param = \preg_replace( '/\\\\(.)/', '$1', \substr( $param, 1, -1 ) ); } $params[ \strtolower( $pair[1] ) ] = $param; } $labels[ $label ] = array( 'components' => $components[1], 'params' => $params, 'signature' => \base64_decode( $signatures[ $label ] ), ); } return \array_slice( $labels, 0, self::MAX_LABELS, true ); } /** * Verify a single signature label. * * @param array $data Parsed signature data. * @param array $headers HTTP headers. * @param string|null $body Request body, if applicable. * @return string|\WP_Error The id of the actor that owns the label's key, if the signature is valid, WP_Error on failure. */ private function verify_signature_label( $data, $headers, $body ) { $params = $data['params']; /* * Timestamp verification. * * Keep the pre-existing one-minute forward bound (tighter than the * Cavage path's five minutes, appropriate for RFC 9421 where fresh * peers tend to ship with synced clocks) and add one hour of * backward drift. Without the past-side bound, peers that omit * `expires` could present arbitrarily old signatures for replay. */ $now = \time(); if ( isset( $params['created'] ) ) { $created = (int) $params['created']; if ( $created > $now + MINUTE_IN_SECONDS ) { return new \WP_Error( 'invalid_created', 'The signature creation time is in the future.' ); } if ( $created < $now - HOUR_IN_SECONDS ) { return new \WP_Error( 'expired_created', 'The signature creation time is too far in the past.' ); } } if ( isset( $params['expires'] ) ) { $expires = (int) $params['expires']; if ( $expires < $now ) { return new \WP_Error( 'expired_signature', 'The signature has expired.' ); } if ( $expires > $now + DAY_IN_SECONDS ) { return new \WP_Error( 'invalid_expires', 'The signature expiry time is too far in the future.' ); } } /* * Require a time anchor. Both `created` and `expires` are optional * in RFC-9421; a signature without either has no freshness bound * and could be replayed indefinitely. */ if ( ! isset( $params['created'] ) && ! isset( $params['expires'] ) ) { return new \WP_Error( 'missing_time_anchor', 'The signature is missing a time anchor (created or expires).' ); } /* * Require the components that tie a signature to this request: one naming this site, which * get_component_values() checks is ours, and the digest of a body. A signature over less * verifies on its own terms, but could be presented to any site, with any body. */ $covered = \array_map( static function ( $component ) { return \strtolower( \trim( \strtok( $component, ';' ), '"' ) ); }, $data['components'] ); if ( ! \array_intersect( array( '@target-uri', '@authority', 'host' ), $covered ) ) { return new \WP_Error( 'activitypub_signature_components', 'The signature does not cover the request target.' ); } if ( '' !== (string) $body && ! \in_array( 'content-digest', $covered, true ) ) { return new \WP_Error( 'activitypub_signature_components', 'The signature does not cover the request body.' ); } // Read before the key is fetched, so a request made out to another host fails without a lookup. $components = $this->get_component_values( $data['components'], $headers ); if ( \is_wp_error( $components ) ) { return $components; } // KeyId verification. if ( empty( $params['keyid'] ) || ! \is_string( $params['keyid'] ) ) { return new \WP_Error( 'missing_keyid', 'Missing keyId in signature parameters.' ); } $owner = null; $public_key = Remote_Actors::get_public_key( $params['keyid'], $owner ); if ( \is_wp_error( $public_key ) ) { return $public_key; } // The owner is what callers bind to the actor, so a key without one does not verify anything. if ( ! \is_string( $owner ) || '' === $owner ) { return new \WP_Error( 'activitypub_no_key_owner', 'The signing key has no owner.' ); } // Algorithm verification. $algorithm = $this->verify_algorithm( $params['alg'] ?? '', $public_key ); if ( \is_wp_error( $algorithm ) ) { return $algorithm; } // Digest verification. $result = $this->verify_content_digest( $headers, $body ); if ( \is_wp_error( $result ) ) { return $result; } $signature_base = $this->get_signature_base_string( $components, $params ); $verified = \openssl_verify( $signature_base, $data['signature'], $public_key, $algorithm ) > 0; if ( ! $verified ) { return new \WP_Error( 'activitypub_signature', 'Invalid signature' ); } return $owner; } /** * Verify the Content-Digest header against the request body. * * @param array $headers The HTTP headers. * @param string|null $body The request body, if applicable. * @return bool|\WP_Error True, if the signature is valid, WP_Error on failure. */ private function verify_content_digest( $headers, $body ) { // A covered but absent header enters the signature base empty and would vouch for any body. if ( ! isset( $headers['content_digest'][0] ) ) { return '' === (string) $body ? true : new \WP_Error( 'missing_digest', 'The Content-Digest header is missing.' ); } if ( null === $body ) { return true; } $digests = \array_map( 'trim', \explode( ',', $headers['content_digest'][0] ) ); foreach ( $digests as $digest ) { if ( \preg_match( '/^([a-z0-9-]+)=:(.+):$/i', $digest, $matches ) ) { list( , $alg, $encoded ) = $matches; if ( ! isset( $this->digest_algorithms[ $alg ] ) ) { return new \WP_Error( 'unsupported_digest', 'WordPress supports sha-256 and sha-512 in Digest header. Offered algorithm: ' . $alg ); } if ( \hash_equals( $encoded, \base64_encode( \hash( $this->digest_algorithms[ $alg ], $body, true ) ) ) ) { return true; } } } return new \WP_Error( 'digest_mismatch', 'Content-Digest header value does not match body.' ); } /** * Resolve and validate the HTTP Signature algorithm from `alg=` parameter and key. * * @param string $alg_string The alg= parameter value (e.g., 'rsa-pss-sha512'). * @param resource $public_key An OpenSSL public key resource. * * @return int|\WP_Error OpenSSL algorithm constant or WP_Error. */ private function verify_algorithm( $alg_string, $public_key ) { $details = \openssl_pkey_get_details( $public_key ); if ( ! isset( $details['type'] ) ) { return new \WP_Error( 'invalid_key_details', 'Unable to read public key details.' ); } // If alg_string is empty, determine algorithm based on public key. if ( empty( $alg_string ) ) { switch ( $details['type'] ) { case \OPENSSL_KEYTYPE_RSA: $bits = $details['bits'] ?? 2048; if ( $bits >= 4 * KB_IN_BYTES ) { return \OPENSSL_ALGO_SHA512; } elseif ( $bits >= 3 * KB_IN_BYTES ) { return \OPENSSL_ALGO_SHA384; } else { return \OPENSSL_ALGO_SHA256; } case \OPENSSL_KEYTYPE_EC: switch ( $details['ec']['curve_name'] ?? '' ) { case 'prime256v1': case 'secp256r1': return \OPENSSL_ALGO_SHA256; case 'secp384r1': return \OPENSSL_ALGO_SHA384; case 'secp521r1': return \OPENSSL_ALGO_SHA512; } } } $alg_string = \strtolower( $alg_string ); if ( \strpos( $alg_string, 'rsa-pss-' ) === 0 && \version_compare( PHP_VERSION, '8.1.0', '<' ) ) { return new \WP_Error( 'unsupported_pss', 'RSA-PSS algorithms are not supported.' ); } if ( ! isset( $this->algorithms[ $alg_string ] ) ) { return new \WP_Error( 'unsupported_alg', 'Unsupported or unknown alg parameter: ' . $alg_string ); } if ( $this->algorithms[ $alg_string ]['type'] !== $details['type'] ) { return new \WP_Error( 'alg_key_mismatch', 'Algorithm does not match public key type.' ); } return $this->algorithms[ $alg_string ]['algo']; } /** * Returns the base strings to compare the incoming signature with. * * @param array $components Signature components. * @param array $params Signature params. * * @return string Base string to compare signature with. */ private function get_signature_base_string( $components, $params ) { $signature_base = ''; foreach ( $components as $component => $value ) { $signature_base .= $component . ': ' . $value . "\n"; } $signature_base .= '"@signature-params": (' . \implode( ' ', \array_keys( $components ) ) . ')'; $signature_base .= $this->get_params_string( $params ); return $signature_base; } /** * Returns the signature params in a string format. * * @param array $params Signature params. * * @return string Signature params. */ private function get_params_string( $params ) { $signature_params = ''; foreach ( $params as $key => $value ) { if ( \is_numeric( $value ) ) { $signature_params .= ';' . $key . '=' . $value; // No quotes. } else { // Escape backslashes and double quotes per RFC-9421. $value = \str_replace( array( '\\', '"' ), array( '\\\\', '\\"' ), $value ); $signature_params .= ';' . $key . '="' . $value . '"'; // Double quotes. } } return $signature_params; } /** * Generate signature components. * * @param array $components Signature component names. * @param array $headers HTTP headers. * * @return array|\WP_Error Signature components, or an error if the request is made out to another host. */ private function get_component_values( $components, $headers ) { $signature_components = array(); foreach ( $components as $component ) { $key = \strtok( $component, ';' ); // See https://www.rfc-editor.org/rfc/rfc9421.html#name-query-parameters. $key = \strtolower( \trim( $key, '"' ) ); /* * These name this server through the client-supplied `Host`, so check the value that enters the base. * A proxy that rewrites `Host` leaves the value the peer signed only in `X-Original-Host`, so it is read first. */ $host = ''; if ( \in_array( $key, array( '@target-uri', '@authority', 'host' ), true ) ) { $host = 'host' === $key ? ( $headers['host'][0] ?? '' ) : ( $_SERVER['HTTP_HOST'] ?? '' ); if ( is_signature_host( $headers['x_original_host'][0] ?? '' ) ) { $host = $headers['x_original_host'][0]; } elseif ( ! is_signature_host( $host ) ) { return new \WP_Error( 'activitypub_signature_host', 'The signature is not made out to this site.' ); } } switch ( $key ) { case '@method': $value = $_SERVER['REQUEST_METHOD'] ?? 'GET'; break; case '@target-uri': $value = \set_url_scheme( \sprintf( '//%s%s', $host, $_SERVER['REQUEST_URI'] ?? '/' ) ); break; case '@authority': $value = $host; break; case 'host': $value = \preg_replace( '/\s+/', ' ', \trim( $host ) ); break; case '@scheme': $value = \is_ssl() ? 'https' : 'http'; break; case '@request-target': $value = $_SERVER['REQUEST_URI'] ?? '/'; break; case '@path': $value = \wp_parse_url( $_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH ); break; case '@query': $value = \wp_parse_url( $_SERVER['REQUEST_URI'] ?? '', PHP_URL_QUERY ); $value = $value ? '?' . $value : ''; break; case '@query-param': $value = ''; if ( \preg_match( '/"@query-param";name="(?P[^"]+)"/', $component, $matches ) ) { $query = \wp_parse_args( \wp_parse_url( $_SERVER['REQUEST_URI'] ?? '', PHP_URL_QUERY ) ); $value = $query[ $matches['name'] ] ?? ''; } break; default: /** Canonicalize header names. {@see WP_REST_Request::canonicalize_header_name()} */ $key = \str_replace( '-', '_', $key ); $value = \preg_replace( '/\s+/', ' ', \trim( $headers[ $key ][0] ?? '' ) ); } $signature_components[ $component ] = $value; } return $signature_components; } }