hash_hkdf( 'sha256', $ikm, 32, self::INFO, $salt ), 'key_id' => substr( hash( 'sha256', $ikm . $salt . self::INFO, true ), 0, 16 ) ); } /** * Pack a positive integer as an unsigned 64-bit big-endian value. * * @param int $number Number to pack. * @return string * @throws InvalidArgumentException When the number is invalid. */ private static function uint64be( $number ) { if ( ! is_int( $number ) || $number < 1 ) { throw new InvalidArgumentException( 'invalid_site_scope' ); } return pack( 'NN', intdiv( $number, 4294967296 ), $number % 4294967296 ); } /** * Validate the site identity fields. * * @param array $identity Site identity. * @return void * @throws InvalidArgumentException When the identity is invalid. */ private static function assert_identity( array $identity ) { if ( array_keys( $identity ) !== array( 'network_id', 'blog_id', 'origin', 'installation_uuid' ) || ! is_string( $identity['origin'] ) || ! is_string( $identity['installation_uuid'] ) || $identity['origin'] === '' || $identity['installation_uuid'] === '' ) { throw new InvalidArgumentException( 'invalid_site_scope' ); } self::uint64be( $identity['network_id'] ); self::uint64be( $identity['blog_id'] ); } /** * Generate signing and encryption key pairs. * * @return array * @throws RuntimeException When the required cryptography is unavailable. */ public static function generate_keys() { if ( ! function_exists( 'sodium_crypto_box_keypair' ) || ! function_exists( 'sodium_crypto_aead_xchacha20poly1305_ietf_encrypt' ) ) { throw new RuntimeException( 'connect_crypto_unavailable' ); } $signing = openssl_pkey_new( array( 'private_key_type' => OPENSSL_KEYTYPE_EC, 'curve_name' => 'prime256v1' ) ); if ( false === $signing || ! openssl_pkey_export( $signing, $private ) ) { throw new RuntimeException( 'connect_crypto_unavailable' ); } $details = openssl_pkey_get_details( $signing ); if ( ! isset( $details['ec']['x'], $details['ec']['y'] ) ) { throw new RuntimeException( 'connect_crypto_unavailable' ); } $x = self::pad_p256_coordinate( $details['ec']['x'] ); $y = self::pad_p256_coordinate( $details['ec']['y'] ); $encryption = sodium_crypto_box_keypair(); return array( 'signing_public' => array( 'kty' => 'EC', 'crv' => 'P-256', 'x' => self::base64url( $x ), 'y' => self::base64url( $y ) ), 'signing_private' => $private, 'encryption_public' => array( 'kty' => 'OKP', 'crv' => 'X25519', 'x' => self::base64url( sodium_crypto_box_publickey( $encryption ) ) ), 'encryption_private' => self::base64url( sodium_crypto_box_secretkey( $encryption ) ), ); } /** * Normalize an OpenSSL P-256 coordinate to the JWK-required width. * * @param mixed $coordinate Raw unsigned big-endian coordinate. * @return string * @throws RuntimeException When the coordinate is invalid or oversized. */ public static function pad_p256_coordinate( $coordinate ) { if ( ! is_string( $coordinate ) || '' === $coordinate || strlen( $coordinate ) > 32 ) { throw new RuntimeException( 'connect_crypto_unavailable' ); } return str_pad( $coordinate, 32, "\0", STR_PAD_LEFT ); } /** * Encrypt a value with authenticated encryption. * * @param string $plaintext Plaintext value. * @param string $key Encryption key. * @param string $aad Additional authenticated data. * @return array */ private static function encrypt( $plaintext, $key, $aad ) { $nonce = random_bytes( SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES ); $combined = sodium_crypto_aead_xchacha20poly1305_ietf_encrypt( $plaintext, $aad, $nonce, $key ); return array( 'nonce' => self::base64url( $nonce ), 'ciphertext' => self::base64url( substr( $combined, 0, -16 ) ), 'tag' => self::base64url( substr( $combined, -16 ) ) ); } /** * Decrypt an authenticated value. * * @param array $sealed Sealed value. * @param string $key Encryption key. * @param string $aad Additional authenticated data. * @return string * @throws InvalidArgumentException When the envelope is invalid. */ private static function decrypt( $sealed, $key, $aad ) { $keys = is_array( $sealed ) ? array_keys( $sealed ) : array(); sort( $keys, SORT_STRING ); if ( array( 'ciphertext', 'nonce', 'tag' ) !== $keys ) { throw new InvalidArgumentException( 'invalid_connect_envelope' ); } $nonce = self::decode( $sealed['nonce'], 24 ); $tag = self::decode( $sealed['tag'], 16 ); $ciphertext = self::decode( $sealed['ciphertext'] ); $value = sodium_crypto_aead_xchacha20poly1305_ietf_decrypt( $ciphertext . $tag, $aad, $nonce, $key ); if ( false === $value ) { throw new InvalidArgumentException( 'invalid_connect_envelope' ); } return $value; } /** * Seal private material for the site identity. * * @param array $private Private material. * @param array $derived Derived key material. * @param array $identity Site identity. * @return array * @throws InvalidArgumentException When the identity or key is invalid. */ public static function seal( array $private, array $derived, array $identity ) { self::assert_identity( $identity ); if ( ! isset( $derived['kek'], $derived['key_id'] ) || strlen( $derived['kek'] ) !== 32 || strlen( $derived['key_id'] ) !== 16 ) { throw new InvalidArgumentException( 'invalid_connect_key' ); } $dek = random_bytes( 32 ); $aad = 'aha-connect-local-state-v1:' . self::canonical_json( $identity ); return array( 'schema' => 1, 'algorithm' => 'XChaCha20-Poly1305', 'key_id' => self::base64url( $derived['key_id'] ), 'identity' => $identity, 'wrapped_dek' => self::encrypt( $dek, $derived['kek'], $aad . ':wrap' ), 'private' => self::encrypt( self::canonical_json( $private ), $dek, $aad . ':private' ) ); } /** * Open private material for the site identity. * * @param array $sealed Sealed material. * @param array $derived Derived key material. * @param array $identity Site identity. * @return array * @throws InvalidArgumentException When the envelope is invalid. */ public static function open( array $sealed, array $derived, array $identity ) { self::assert_identity( $identity ); if ( ! isset( $sealed['schema'], $sealed['algorithm'], $sealed['key_id'], $sealed['identity'], $sealed['wrapped_dek'], $sealed['private'] ) || count( $sealed ) !== 6 || $sealed['schema'] !== 1 || $sealed['algorithm'] !== 'XChaCha20-Poly1305' || ! hash_equals( self::base64url( $derived['key_id'] ), $sealed['key_id'] ) || ! is_array( $sealed['identity'] ) || self::canonical_json( $sealed['identity'] ) !== self::canonical_json( $identity ) ) { throw new InvalidArgumentException( 'invalid_connect_envelope' ); } $aad = 'aha-connect-local-state-v1:' . self::canonical_json( $identity ); $dek = self::decrypt( $sealed['wrapped_dek'], $derived['kek'], $aad . ':wrap' ); $private = json_decode( self::decrypt( $sealed['private'], $dek, $aad . ':private' ), true ); if ( ! is_array( $private ) ) { throw new InvalidArgumentException( 'invalid_connect_envelope' ); } return $private; } /** * Open an authority-to-installation Connect envelope. * * Every validation or authentication failure is deliberately collapsed to * one neutral error so callers cannot distinguish malformed key material * from an invalid authentication tag. * * @param array $envelope Connect envelope. * @param string $purpose handoff or credentials. * @param string $bootstrap_id Bootstrap identifier. * @param int $encryption_key_generation Installation key generation. * @param mixed $encryption_private Encoded X25519 private key. * @return string Decrypted UTF-8 bytes. * @throws InvalidArgumentException When the envelope cannot be authenticated. */ public static function open_envelope( array $envelope, string $purpose, string $bootstrap_id, int $encryption_key_generation, $encryption_private ) { try { $keys = array_keys( $envelope ); sort( $keys, SORT_STRING ); if ( array( 'alg', 'ciphertext', 'epk', 'nonce' ) !== $keys || self::CONNECT_ENVELOPE_ALGORITHM !== $envelope['alg'] || ! in_array( $purpose, array( 'handoff', 'credentials' ), true ) || ! self::is_b64url32( $bootstrap_id ) || $encryption_key_generation < 1 ) { throw new InvalidArgumentException( 'invalid_connect_envelope' ); } $private = self::decode( $encryption_private, 32 ); $ephemeral = self::decode( $envelope['epk'], 32 ); $nonce = self::decode( $envelope['nonce'], 12 ); $ciphertext = self::decode( $envelope['ciphertext'] ); if ( strlen( $ciphertext ) < 17 ) { throw new InvalidArgumentException( 'invalid_connect_envelope' ); } $public = sodium_crypto_scalarmult_base( $private ); $shared = sodium_crypto_scalarmult( $private, $ephemeral ); if ( false === $shared || hash_equals( str_repeat( "\0", 32 ), $shared ) ) { throw new InvalidArgumentException( 'invalid_connect_envelope' ); } $key = hash_hkdf( 'sha256', $shared, 32, 'aha-connect-v1:' . $purpose . ':' . $bootstrap_id, $ephemeral . $public ); $aad = self::canonical_json( array( 'bootstrap_id' => $bootstrap_id, 'encryption_key_generation' => $encryption_key_generation, 'purpose' => $purpose, ) ); $plaintext = sodium_crypto_aead_chacha20poly1305_ietf_decrypt( $ciphertext, $aad, $nonce, $key ); if ( false === $plaintext ) { throw new InvalidArgumentException( 'invalid_connect_envelope' ); } return $plaintext; } catch ( Throwable $error ) { throw new InvalidArgumentException( 'invalid_connect_envelope' ); } } /** * Encode a value as canonical JSON. * * @param mixed $value Value to encode. * @return string */ public static function canonical_json( $value ) { if ( is_array( $value ) ) { if ( array_keys( $value ) !== range( 0, count( $value ) - 1 ) ) { ksort( $value, SORT_STRING ); } foreach ( $value as $key => $item ) { $value[ $key ] = self::canonicalize( $item ); } } return json_encode( $value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR ); } /** * Canonicalize nested array values. * * @param mixed $value Value to canonicalize. * @return mixed */ private static function canonicalize( $value ) { if ( is_array( $value ) ) { if ( $value && array_keys( $value ) !== range( 0, count( $value ) - 1 ) ) { ksort( $value, SORT_STRING ); } foreach ( $value as $key => $item ) { $value[ $key ] = self::canonicalize( $item ); } } return $value; } /** * Sign a payload. * * @param array $payload Payload to sign. * @param string $private Private signing key. * @return string * @throws RuntimeException When signing fails. */ public static function sign( array $payload, $private ) { if ( ! openssl_sign( self::canonical_json( $payload ), $signature, $private, OPENSSL_ALGO_SHA256 ) ) { throw new RuntimeException( 'connect_sign_failed' ); } return self::base64url( $signature ); } /** * Verify a payload signature with a public JWK. * * @param array $payload Payload to verify. * @param string $signature Encoded signature. * @param array $jwk Public signing JWK. * @return bool */ public static function verify( array $payload, $signature, array $jwk ) { if ( array_keys( $jwk ) !== array( 'kty', 'crv', 'x', 'y' ) || $jwk['kty'] !== 'EC' || $jwk['crv'] !== 'P-256' ) { return false; } try { $point = "\x04" . self::decode( $jwk['x'], 32 ) . self::decode( $jwk['y'], 32 ); $der = hex2bin( '3059301306072a8648ce3d020106082a8648ce3d030107034200' ) . $point; $pem = "-----BEGIN PUBLIC KEY-----\n" . chunk_split( base64_encode( $der ), 64, "\n" ) . "-----END PUBLIC KEY-----\n"; return 1 === openssl_verify( self::canonical_json( $payload ), self::decode( $signature ), $pem, OPENSSL_ALGO_SHA256 ); } catch ( InvalidArgumentException $e ) { return false; } } /** * Encode bytes as unpadded base64url. * * @param string $bytes Bytes to encode. * @return string */ public static function base64url( $bytes ) { return rtrim( strtr( base64_encode( $bytes ), '+/', '-_' ), '=' ); } /** * Check for an unpadded 32-byte base64url value. * * @param mixed $value Value to check. * @return bool */ public static function is_b64url32( $value ): bool { if ( ! is_string( $value ) || preg_match( '/^[A-Za-z0-9_-]{43}$/D', $value ) !== 1 ) { return false; } $bytes = base64_decode( strtr( $value, '-_', '+/' ) . '=', true ); return false !== $bytes && strlen( $bytes ) === 32 && hash_equals( self::base64url( $bytes ), $value ); } /** * Decode an unpadded base64url value. * * @param string $value Value to decode. * @param int|null $length Required byte length. * @return string * @throws InvalidArgumentException When the encoding or length is invalid. */ private static function decode( $value, $length = null ) { if ( ! is_string( $value ) || ! preg_match( '/^[A-Za-z0-9_-]+$/D', $value ) ) { throw new InvalidArgumentException( 'invalid_connect_encoding' ); } $bytes = base64_decode( strtr( $value, '-_', '+/' ), true ); if ( false === $bytes || self::base64url( $bytes ) !== $value || ( null !== $length && strlen( $bytes ) !== $length ) ) { throw new InvalidArgumentException( 'invalid_connect_encoding' ); } return $bytes; } }