$keys kid => raw 32-byte Ed25519 public key * @return Result Result, payload: JsonObject}> */ public static function verify( string $token, string $expected_typ, array $keys ): Result { // Split to four, not to however many the caller asked for. A compact // serialization has three parts, so a fourth is already a rejection and // the limit changes no answer this function gives — but without it an // unverified token of n dots buys an n-element PHP array, which is the // same byte-into-array amplification `Json\Utf` was carrying, one layer // down and on a route that is reached before any signature is checked. $parts = explode( '.', $token, 4 ); if ( 3 !== count( $parts ) || '' === $parts[0] || '' === $parts[1] || '' === $parts[2] ) { return Result::err( 'jws_malformed', 'not a three-part compact serialization' ); } list( $header_part, $payload_part, $signature_part ) = $parts; $parsed_header = self::parseHeader( $header_part ); if ( ! $parsed_header->isOk() ) { return $parsed_header; } $alg = $parsed_header->value()['alg']; $kid = $parsed_header->value()['kid']; $typ = $parsed_header->value()['typ']; // A verifier that accepts one envelope where another is expected is a // confused deputy waiting for a caller (section 3.1). if ( ! hash_equals( $expected_typ, $typ ) ) { return Result::err( 'jws_typ_mismatch', "expected typ {$expected_typ}, got {$typ}" ); } // The same measurement `parseHeader` makes, on the one segment whose // decoded length is not merely bounded but fixed: Ed25519 signs in // SODIUM_CRYPTO_SIGN_BYTES and nothing else, so a longer segment was // always going to be refused below and this refuses it without decoding a // caller-sized blob first. // // All of it runs BEFORE the key lookup (section 6.6, wp-a96rb). After it, // a malformed segment answered one way for an installed kid and // `unknown_kid` for an absent one, which told an anonymous caller which // kids the site holds. A segment that does not decode is an invalid // signature and is refused under that code, whatever the kid. if ( strlen( $signature_part ) > (int) ceil( SODIUM_CRYPTO_SIGN_BYTES * 4 / 3 ) ) { return Result::err( 'sig_invalid', 'signature is not the length Ed25519 produces' ); } $signature = Base64Url::decode( $signature_part ); if ( ! $signature->isOk() ) { return Result::err( 'sig_invalid', 'signature segment: ' . $signature->error()->message() ); } if ( SODIUM_CRYPTO_SIGN_BYTES !== strlen( $signature->value() ) ) { return Result::err( 'sig_invalid', 'signature is not the length Ed25519 produces' ); } // ONE VERIFICATION ON EVERY PATH (section 6.6; review of wp-a96rb). An // absent kid used to return here at once while an installed one went on // to an Ed25519 verification, about three times slower, so averaging // response times told a stranger which kids the site holds even with the // wire codes collapsed. An absent or malformed key is verified against // `TIMING_STAND_IN` instead, whose secret nobody holds, and refused only // after the same work. // `is_string` before `strlen`, because under strict_types a non-string in // the key set is a TypeError, and this function's contract is that // anything malformed comes back as a refusal rather than a fatal. $installed = isset( $keys[ $kid ] ); $candidate = $installed ? $keys[ $kid ] : null; $usable = is_string( $candidate ) && Keys::PUBLIC_KEY_BYTES === strlen( $candidate ); $public_key = $usable ? $candidate : (string) hex2bin( self::TIMING_STAND_IN ); $signing_input = $header_part . '.' . $payload_part; $verified = false; try { // Constructed algorithm-first: the function IS the algorithm choice. $verified = sodium_crypto_sign_verify_detached( $signature->value(), $signing_input, $public_key ); } catch ( \Throwable $e ) { // SodiumException for most malformed input, but the same call raises // ValueError or TypeError on some builds and inputs. A verifier that // lets any of them escape has turned a rejection into a fatal. $verified = false; } if ( ! $installed ) { return Result::err( 'unknown_kid', "no active key named {$kid}" ); } if ( ! $usable ) { // A `kid` naming a key of another type is a rejection (section 6.4). return Result::err( 'key_type_mismatch', "kid {$kid} does not name an Ed25519 key" ); } if ( ! $verified ) { return Result::err( 'sig_invalid', 'signature does not verify under the selected key' ); } // Compared, never dispatched on — and only now that the signature held. if ( ! hash_equals( self::ALG, $alg ) ) { return Result::err( 'jws_alg_mismatch', "alg {$alg} is not " . self::ALG ); } $payload_bytes = Base64Url::decode( $payload_part ); if ( ! $payload_bytes->isOk() ) { return $payload_bytes; } $payload = Domain::check( $payload_bytes->value() ); if ( ! $payload->isOk() ) { return Result::err( 'payload_malformed', $payload->error()->message() ); } return Result::ok( array( 'header' => array( 'alg' => $alg, 'kid' => $kid, 'typ' => $typ, ), 'payload' => $payload->value(), ) ); } /** * The header rules, in one place, because `Chain` has to read a `kid` out of a * token before it can decide which key set that token verifies against — and a * second copy of these rules is a second chance to get one of them wrong. * * The header is parsed *before* the signature is verified — it has to be, * because it names the key that does the verifying. So everything this reaches * is work an unauthenticated caller can ask for, and it is bounded here rather * than at the argument limit. A conforming header is `{"alg","kid","typ"}` and * is under a hundred bytes; the argument domain's megabyte allowance is for * arguments, and applying it to a pre-auth parse let one request buy a * megabyte of JSON reading, NFC normalisation and canonicalisation. * * The exactness below is load-bearing beyond hygiene: it is what refuses an * `x5c`-style chain in the header by construction. ADR 0021 carries the * delegation in the payload precisely so this stays true. * * @return Result Result */ public static function parseHeader( string $header_part ): Result { // Measured on the ENCODED segment, before a byte of it is decoded, the way // `Chain::resolve` measures the payload segment and for the reason its // comment gives. The bound below says it exists to cap pre-auth work, and // until this line it did not: the decode it was placed after is itself the // work, and a megabyte of base64url was decoded and canonically // re-encoded before a 1024-byte limit got to refuse it. Base64url of n // bytes is ceil(n * 4 / 3) characters. if ( strlen( $header_part ) > (int) ceil( self::MAX_HEADER_BYTES * 4 / 3 ) ) { return Result::err( 'jws_header_malformed', 'the JWS header exceeds ' . self::MAX_HEADER_BYTES . ' bytes' ); } $header_bytes = Base64Url::decode( $header_part ); if ( ! $header_bytes->isOk() ) { return $header_bytes; } if ( strlen( $header_bytes->value() ) > self::MAX_HEADER_BYTES ) { return Result::err( 'jws_header_malformed', 'the JWS header exceeds ' . self::MAX_HEADER_BYTES . ' bytes' ); } $header_json = Domain::check( $header_bytes->value() ); if ( ! $header_json->isOk() ) { return Result::err( 'jws_header_malformed', $header_json->error()->message() ); } /** @var JsonObject $header */ $header = $header_json->value(); if ( $header->has( 'crit' ) ) { return Result::err( 'jws_header_crit', 'crit is never emitted and its presence is a rejection' ); } $names = $header->keys(); sort( $names ); if ( array( 'alg', 'kid', 'typ' ) !== $names ) { return Result::err( 'jws_header_malformed', 'the header carries exactly alg, kid and typ' ); } foreach ( $names as $name ) { if ( ! is_string( $header->get( $name ) ) ) { return Result::err( 'jws_header_malformed', 'every header member is a string' ); } } return Result::ok( array( 'alg' => $header->get( 'alg' ), 'kid' => $header->get( 'kid' ), 'typ' => $header->get( 'typ' ), ) ); } /** * Signing exists for one reason: the site key, which signs the pairing * request, the challenge echo, the exchange and every report. The plugin * never signs a grant or a control message. * * @param array $claims */ public static function sign( array $claims, string $kid, string $typ, string $secret_key ): Result { if ( Keys::SECRET_KEY_BYTES !== strlen( $secret_key ) ) { return Result::err( 'key_type_mismatch', 'cannot sign without an Ed25519 secret key' ); } $header = self::canonicalObject( array( 'alg' => self::ALG, 'kid' => $kid, 'typ' => $typ, ) ); $input = Base64Url::encode( $header ) . '.' . Base64Url::encode( self::canonicalObject( $claims ) ); try { $signature = sodium_crypto_sign_detached( $input, $secret_key ); } catch ( \Throwable $e ) { return Result::err( 'sign_failed', 'the signature could not be produced' ); } return Result::ok( $input . '.' . Base64Url::encode( $signature ) ); } /** * The gateway serialises JWS parts with the canonical encoder, so the plugin * has to as well or its own signatures would be over different bytes than a * gateway-side re-derivation of the same claims. * * @param array $claims */ private static function canonicalObject( array $claims ): string { $object = new JsonObject(); foreach ( $claims as $key => $value ) { $object->set( (string) $key, self::toJsonValue( $value ) ); } return \Pielyt\Json\Canonical::encode( $object ); } /** * @param mixed $value * @return mixed */ private static function toJsonValue( $value ) { if ( ! is_array( $value ) ) { return $value; } if ( array() === $value ) { return array(); } $is_list = array_keys( $value ) === range( 0, count( $value ) - 1 ); if ( $is_list ) { return array_map( array( self::class, 'toJsonValue' ), $value ); } $object = new JsonObject(); foreach ( $value as $key => $item ) { $object->set( (string) $key, self::toJsonValue( $item ) ); } return $object; } }