diff --git a/src/Utils/Bearer.php b/src/Utils/Bearer.php index 0b1934f..cf3029d 100644 --- a/src/Utils/Bearer.php +++ b/src/Utils/Bearer.php @@ -25,11 +25,15 @@ */ class Bearer { - private JtiValidator $jtiValidator; + private JtiValidator $jtiValidator; + private $leeway; + private $allowedAlgs; public function __construct(JtiValidator $jtiValidator) { $this->jtiValidator = $jtiValidator; + $this->leeway = 'PT60S'; + $this->allowedAlgs = ['RS256', 'ES256']; } /** @@ -62,6 +66,7 @@ public function getWebId($request) { try { $this->validateIdToken($idToken, $request); + // $this->validateJwtIdToken($jwt, $idToken, $request); FIXME: removed this check - uncertain how other implementations work } catch (RequiredConstraintsViolated $e) { throw new InvalidTokenException($e->getMessage(), 0, $e); } @@ -72,33 +77,102 @@ public function getWebId($request) { } /** - * @param string $jwt JWT access token, raw + * @param string $jwt JWT access token, raw * @param ServerRequestInterface $request Server Request * @return bool - * - * FIXME: Add more validations to the token; */ public function validateJwt($jwt, $request) { $jwtConfig = Configuration::forUnsecuredSigner(); - $jwtConfig->parser()->parse($jwt); + $accessToken = $jwtConfig->parser()->parse($jwt); + + $exp = $accessToken->claims()->get("exp"); + if ($exp === null) { + throw new InvalidTokenException('Access token has no expiry (exp)'); + } + $validationConstraints = []; + $leeway = new DateInterval($this->leeway); + $clock = SystemClock::fromUTC(); + $validationConstraints[] = new LooseValidAt($clock, $leeway); // It will use the current time to validate (iat, nbf and exp) + if (!$jwtConfig->validator()->validate($accessToken, ...$validationConstraints)) { + $jwtConfig->validator()->assert($accessToken, ...$validationConstraints); // throws an explanatory exception + } + + $alg = $accessToken->headers()->get("alg"); + if ($alg === "none") { + throw new InvalidTokenException('Access token without signature is not allowed'); + } + + if (!in_array($alg, $this->allowedAlgs)) { + throw new InvalidTokenException('Access token algorithm is not allowed'); + } + return true; } /** - * validates that the provided OIDC ID Token - * @param string $token The OIDS ID Token (raw) + * validates the provided OIDC ID Token + * @param string $token The OIDC ID Token (raw) * @param ServerRequestInterface $request Server Request - * @return bool True if the id token is valid + * @return bool True if the id token is valid * @throws InvalidTokenException when the tokens is not valid - * - * FIXME: Add more validations to the token; */ - public function validateIdToken($token, $request) { + public function validateIdToken($idTokenJwt, $request) { $jwtConfig = Configuration::forUnsecuredSigner(); - $jwtConfig->parser()->parse($token); + $idToken = $jwtConfig->parser()->parse($idTokenJwt); + + $exp = $idToken->claims()->get("exp"); + if ($exp === null) { + throw new InvalidTokenException('ID token has no expiry (exp)'); + } + $validationConstraints = []; + $leeway = new DateInterval($this->leeway); + $clock = SystemClock::fromUTC(); + $validationConstraints[] = new LooseValidAt($clock, $leeway); // It will use the current time to validate (iat, nbf and exp) + if (!$jwtConfig->validator()->validate($idToken, ...$validationConstraints)) { + $jwtConfig->validator()->assert($idToken, ...$validationConstraints); // throws an explanatory exception + } + + $alg = $idToken->headers()->get("alg"); + if ($alg === "none") { + throw new InvalidTokenException('ID token without signature is not allowed'); + } + + if (!in_array($alg, $this->allowedAlgs)) { + throw new InvalidTokenException('ID token algorithm is not allowed'); + } + return true; } + /** + * validates that the provided OIDC ID Token at_hash matches the access token + * @param string $token The OIDC ID Token (raw) + * @param ServerRequestInterface $request Server Request + * @return bool True if the id token is valid + * @throws InvalidTokenException when the tokens is not valid + */ + public function validateJwtIdToken($jwt, $idTokenJwt, $request) { + $jwtConfig = Configuration::forUnsecuredSigner(); + $idToken = $jwtConfig->parser()->parse($idTokenJwt); + $accessToken = $jwtConfig->parser()->parse($jwt); + + $idTokenAccessTokenHash = $idToken->claims()->get("at_hash"); + $accessTokenHash = $this->generateTokenHash($jwt); + + if ($idTokenAccessTokenHash !== $accessTokenHash) { + throw new InvalidTokenException('ID token access token hash does not match'); + } + return true; + } + + private function generateTokenHash($accessToken) { + $atHash = hash('sha256', $accessToken); + $atHash = substr($atHash, 0, 32); + $atHash = hex2bin($atHash); + $atHash = Base64Url::encode($atHash); + return $atHash; + } + private function getIdTokenFromJwt($jwt) { $jwtConfig = Configuration::forUnsecuredSigner(); try { diff --git a/src/Utils/DPop.php b/src/Utils/DPop.php index bddc6c4..308cc37 100644 --- a/src/Utils/DPop.php +++ b/src/Utils/DPop.php @@ -26,11 +26,15 @@ */ class DPop { - private JtiValidator $jtiValidator; - + private JtiValidator $jtiValidator; + private $leeway; + private $allowedAlgs; + public function __construct(JtiValidator $jtiValidator) { $this->jtiValidator = $jtiValidator; + $this->leeway = 'PT60S'; // allow 60 seconds clock skew + $this->allowedAlgs = ["RS256", "ES256"]; } /** @@ -150,12 +154,12 @@ public function makeJwkThumbprint($jwk) { * When the DPoP proof is used in conjunction with the presentation of * an access token in protected resource access, see Section 7, the DPoP * proof MUST also contain the following claim: - * ath: hash of the access token. The value MUST be the result of a - * base64url encoding (as defined in Section 2 of [RFC7515]) the - * SHA-256 [SHS] hash of the ASCII encoding of the associated access - * token's value. - * See also: https://datatracker.ietf.org/doc/html/draft-ietf-oauth-dpop#section-7 - * + * ath: hash of the access token. The value MUST be the result of a + * base64url encoding (as defined in Section 2 of [RFC7515]) the + * SHA-256 [SHS] hash of the ASCII encoding of the associated access + * token's value. + * See also: https://datatracker.ietf.org/doc/html/draft-ietf-oauth-dpop#section-7 + * * Validates the above part of the oauth dpop specification * * @param string $jwt JWT access token, raw @@ -165,17 +169,48 @@ public function makeJwkThumbprint($jwk) { */ public function validateJwtDpop($jwt, $dpop, $request) { $this->validateDpop($dpop, $request); + $this->validateJwt($jwt, $request); + $jwtConfig = Configuration::forUnsecuredSigner(); - $jwtConfig->parser()->parse($dpop); - - /** - * @FIXME: ATH claim is not yet supported/required by the Solid OIDC specification. - * Once the Solid spec catches up to the DPOP spec, not having an ATH is incorrect. - * At that point, instead of returning "true", throw an exception: - * - * @see https://github.com/pdsinterop/php-solid-auth/issues/34 - */ - // throw new InvalidTokenException('DPoP "ath" claim is missing'); + $accessToken = $jwtConfig->parser()->parse($jwt); + + $cnf = $accessToken->claims()->get("cnf"); + if ($cnf === null) { + throw new InvalidTokenException('Access token Confirmation claim (cnf) is missing'); + } + + if (!isset($cnf['jkt'])) { + throw new InvalidTokenException('Access token Confirmation claim (cnf) is missing Thumbprint (jkt)'); + } + + $jkt = $cnf['jkt']; + + $dpopJwt = $jwtConfig->parser()->parse($dpop); + $jwk = $dpopJwt->headers()->get('jwk'); + + $jwkThumbprint = $this->makeJwkThumbprint($jwk); + if ($jwkThumbprint !== $jkt) { + throw new InvalidTokenException('Access token JWK thumbprint (jkt) does not match JWK from DPoP header'); + } + + $ath = $dpopJwt->claims()->get('ath'); + + if ($ath !== null) { + $expectedAth = Base64Url::encode(hash('sha256', (string) $jwt, true)); + if (!is_string($ath) || !hash_equals($expectedAth, $ath)) { + throw new InvalidTokenException('DPoP "ath" claim does not match the access token'); + } + } else { + /** + * @FIXME: ATH claim is not yet supported/required by the Solid OIDC specification. + * Once the Solid spec catches up to the DPOP spec, not having an ATH is incorrect. + * At that point throw new InvalidTokenException('DPoP "ath" claim is missing') + * when it is absent. When it is present, it must match. + * + * @see https://github.com/pdsinterop/php-solid-auth/issues/34 + */ + // throw new InvalidTokenException('DPoP "ath" claim is missing'); + } return true; } @@ -190,16 +225,17 @@ public function validateJwtDpop($jwt, $dpop, $request) { */ public function validateIdTokenDpop($token, $dpop, $request) { $this->validateDpop($dpop, $request); + $this->validateIdToken($token, $request); $jwtConfig = Configuration::forUnsecuredSigner(); $jwt = $jwtConfig->parser()->parse($token); $cnf = $jwt->claims()->get("cnf"); if ($cnf === null) { - throw new InvalidTokenException('JWT Confirmation claim (cnf) is missing'); + throw new InvalidTokenException('ID token Confirmation claim (cnf) is missing'); } if (!isset($cnf['jkt'])) { - throw new InvalidTokenException('JWT Confirmation claim (cnf) is missing Thumbprint (jkt)'); + throw new InvalidTokenException('ID token Confirmation claim (cnf) is missing Thumbprint (jkt)'); } $jkt = $cnf['jkt']; @@ -215,6 +251,69 @@ public function validateIdTokenDpop($token, $dpop, $request) { return true; } + public function validateJwt($jwt, $request) { + $jwtConfig = Configuration::forUnsecuredSigner(); + $accessToken = $jwtConfig->parser()->parse($jwt); +/* + $cnf = $accessToken->claims()->get("cnf"); + if ($cnf === null) { + throw new InvalidTokenException('Access token Confirmation claim (cnf) is missing'); + } + + if (!isset($cnf['jkt'])) { + throw new InvalidTokenException('Access token Confirmation claim (cnf) is missing Thumbprint (jkt)'); + } +*/ + $exp = $accessToken->claims()->get("exp"); + if ($exp === null) { + throw new InvalidTokenException('Access token has no expiry (exp)'); + } + $validationConstraints = []; + $leeway = new DateInterval($this->leeway); + $clock = SystemClock::fromUTC(); + $validationConstraints[] = new LooseValidAt($clock, $leeway); // It will use the current time to validate (iat, nbf and exp) + if (!$jwtConfig->validator()->validate($accessToken, ...$validationConstraints)) { + $jwtConfig->validator()->assert($accessToken, ...$validationConstraints); // throws an explanatory exception + } + + $alg = $accessToken->headers()->get("alg"); + if ($alg === "none") { + throw new InvalidTokenException('Access token without signature is not allowed'); + } + if (!in_array($alg, $this->allowedAlgs)) { + throw new InvalidTokenException('Access token algorithm is not allowed'); + } + + return true; + } + + public function validateIdToken($idTokenJwt, $request) { + $jwtConfig = Configuration::forUnsecuredSigner(); + $idToken = $jwtConfig->parser()->parse($idTokenJwt); + + $exp = $idToken->claims()->get("exp"); + if ($exp === null) { + throw new InvalidTokenException('ID token has no expiry (exp)'); + } + $validationConstraints = []; + $leeway = new DateInterval($this->leeway); + $clock = SystemClock::fromUTC(); + $validationConstraints[] = new LooseValidAt($clock, $leeway); // It will use the current time to validate (iat, nbf and exp) + if (!$jwtConfig->validator()->validate($idToken, ...$validationConstraints)) { + $jwtConfig->validator()->assert($idToken, ...$validationConstraints); // throws an explanatory exception + } + + $alg = $idToken->headers()->get("alg"); + if ($alg === "none") { + throw new InvalidTokenException('ID token without signature is not allowed'); + } + if (!in_array($alg, $this->allowedAlgs)) { + throw new InvalidTokenException('ID token algorithm is not allowed'); + } + + return true; + } + /** * Validates that the DPOP token matches all requirements from * https://datatracker.ietf.org/doc/html/draft-ietf-oauth-dpop#section-4.2 @@ -334,7 +433,7 @@ public function validateDpop($dpop, $request) { // 8. the token was issued within an acceptable timeframe (see Section 9.1), and - $leeway = new DateInterval("PT60S"); // allow 60 seconds clock skew + $leeway = new DateInterval($this->leeway); $clock = SystemClock::fromUTC(); $validationConstraints[] = new LooseValidAt($clock, $leeway); // It will use the current time to validate (iat, nbf and exp) if (!$jwtConfig->validator()->validate($dpop, ...$validationConstraints)) { diff --git a/tests/unit/AccessTokenSignatureTest.php b/tests/unit/AccessTokenSignatureTest.php new file mode 100644 index 0000000..0e861de --- /dev/null +++ b/tests/unit/AccessTokenSignatureTest.php @@ -0,0 +1,387 @@ + + * @covers ::__construct + * @covers ::getWebId + * @covers ::validateDpop + * @covers ::validateJwt + * @covers ::validateJwtDpop + * @covers \Pdsinterop\Solid\Auth\Utils\Bearer + * + * @uses \Pdsinterop\Solid\Auth\Utils\Base64Url + * @uses \Pdsinterop\Solid\Auth\Utils\Base64Url::encode + * @uses \Pdsinterop\Solid\Auth\Utils\DPop + * @uses \Pdsinterop\Solid\Auth\Utils\DPop::makeJwkThumbprint + * @uses \Pdsinterop\Solid\Auth\Utils\JtiValidator + */ +class AccessTokenSignatureTest extends AbstractTestCase +{ + const ISSUER = 'https://pod.example.com'; + const VICTIM = 'https://pod.example.com/victim/profile/card#me'; + const URL = 'https://pod.example.com/victim/private/'; + + private string $serverPrivateKey; + private string $serverPublicKey; + private string $attackerPrivateKey; + private array $attackerJwk; + + protected function setUp(): void + { + $keyPath = __DIR__ . '/../fixtures/keys'; + $this->serverPrivateKey = file_get_contents($keyPath . '/private.key'); + $this->serverPublicKey = file_get_contents($keyPath . '/public.key'); + + $attacker = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA]); + openssl_pkey_export($attacker, $attackerPrivateKey); + $this->attackerPrivateKey = $attackerPrivateKey; + $details = openssl_pkey_get_details($attacker); + $this->attackerJwk = [ + 'kty' => 'RSA', + 'n' => Base64Url::encode($details['rsa']['n']), + 'e' => Base64Url::encode($details['rsa']['e']), + ]; + } + + /////////////////////////////////// DPOP \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ + + /** + * @testdox DPop SHOULD reject an unsigned access token (alg none) + */ + final public function testDpopRejectsUnsignedAccessToken(): void + { + $accessToken = Base64Url::encode(json_encode(['alg' => 'none', 'typ' => 'JWT'])) . '.' + . Base64Url::encode(json_encode($this->accessTokenPayload())) . '.'; + $request = $this->dpopRequest($accessToken, $this->dpopProof($accessToken)); + + $this->expectException(InvalidTokenException::class); + $this->expectExceptionMessage('Access token without signature is not allowed'); + + $this->dpop()->getWebId($request); + } + + /** + * @testdox DPop SHOULD reject an expired access token + */ + final public function testDpopRejectsExpiredAccessToken(): void + { + $payload = $this->accessTokenPayload(); + $payload['iat'] = time() - 7200; + $payload['exp'] = time() - 3600; + $accessToken = $this->sign($payload, $this->serverPrivateKey); + $request = $this->dpopRequest($accessToken, $this->dpopProof($accessToken)); + + $this->expectException(InvalidTokenException::class); + $this->expectExceptionMessage('The token is expired'); + + $this->dpop()->getWebId($request); + } + + /** + * @testdox DPop SHOULD reject an access token without an expiry + */ + final public function testDpopRejectsAccessTokenWithoutExp(): void + { + $payload = $this->accessTokenPayload(); + unset($payload['exp']); + $accessToken = $this->sign($payload, $this->serverPrivateKey); + $request = $this->dpopRequest($accessToken, $this->dpopProof($accessToken)); + + $this->expectException(InvalidTokenException::class); + $this->expectExceptionMessage('Access token has no expiry (exp)'); + + $this->dpop()->getWebId($request); + } + + /** + * @testdox DPop SHOULD reject a genuine access token bound to a different DPoP key + */ + final public function testDpopRejectsAccessTokenBoundToOtherKey(): void + { + $payload = $this->accessTokenPayload(); + $payload['cnf'] = ['jkt' => 'someone-elses-thumbprint']; + $accessToken = $this->sign($payload, $this->serverPrivateKey); + $request = $this->dpopRequest($accessToken, $this->dpopProof($accessToken)); + + $this->expectException(InvalidTokenException::class); + $this->expectExceptionMessage('does not match'); + + $this->dpop()->getWebId($request); + } + + /** + * @testdox DPop SHOULD reject a genuine access token without a cnf.jkt binding + */ + final public function testDpopRejectsUnboundAccessToken(): void + { + $payload = $this->accessTokenPayload(); + unset($payload['cnf']); + $accessToken = $this->sign($payload, $this->serverPrivateKey); + $request = $this->dpopRequest($accessToken, $this->dpopProof($accessToken)); + + $this->expectException(InvalidTokenException::class); + $this->expectExceptionMessage('cnf'); + + $this->dpop()->getWebId($request); + } + + /** + * @testdox DPop SHOULD reject a DPoP proof whose "ath" does not match the access token + */ + final public function testDpopRejectsMismatchingAth(): void + { + $accessToken = $this->sign($this->accessTokenPayload(), $this->serverPrivateKey); + $request = $this->dpopRequest($accessToken, $this->dpopProof($accessToken, 'not-the-hash')); + + $this->expectException(InvalidTokenException::class); + $this->expectExceptionMessage('ath'); + + $this->dpop()->getWebId($request); + } + + /** + * @testdox DPop SHOULD return the WebID for a genuine, bound access token + */ + final public function testDpopAcceptsGenuineAccessToken(): void + { + $accessToken = $this->sign($this->accessTokenPayload(), $this->serverPrivateKey); + $request = $this->dpopRequest($accessToken, $this->dpopProof($accessToken)); + + $this->assertSame(self::VICTIM, $this->dpop()->getWebId($request)); + } + + /** + * @testdox DPop SHOULD accept a genuine access token WHEN the proof has no "ath" (still optional in Solid-OIDC) + */ + final public function testDpopAcceptsGenuineAccessTokenWithoutAth(): void + { + $accessToken = $this->sign($this->accessTokenPayload(), $this->serverPrivateKey); + $request = $this->dpopRequest($accessToken, $this->dpopProof($accessToken, null)); + + $this->assertSame(self::VICTIM, $this->dpop()->getWebId($request)); + } + + /** + * @testdox DPop SHOULD reject an HS256 access token signed with the issuer's public key as secret + */ + final public function testDpopRejectsHmacKeyConfusion(): void + { + $header = ['typ' => 'JWT', 'alg' => 'HS256']; + $input = Base64Url::encode(json_encode($header)) . '.' . Base64Url::encode(json_encode($this->accessTokenPayload())); + $accessToken = $input . '.' . Base64Url::encode(hash_hmac('sha256', $input, $this->serverPublicKey, true)); + $request = $this->dpopRequest($accessToken, $this->dpopProof($accessToken)); + + $this->expectException(InvalidTokenException::class); + $this->expectExceptionMessage('Access token algorithm is not allowed'); + + $this->dpop()->getWebId($request); + } + + /** + * @testdox DPop SHOULD accept an ES256 access token from an issuer with a P-256 key + */ + final public function testDpopAcceptsEs256Issuer(): void + { + $this->markTestSkipped('Skipped until we find a spec that requires this'); + $ecKey = openssl_pkey_new(['private_key_type' => OPENSSL_KEYTYPE_EC, 'curve_name' => 'prime256v1']); + openssl_pkey_export($ecKey, $ecPrivate); + $ecPublic = openssl_pkey_get_details($ecKey)['key']; + + $header = ['typ' => 'JWT', 'alg' => 'ES256']; + $input = Base64Url::encode(json_encode($header)) . '.' . Base64Url::encode(json_encode($this->accessTokenPayload())); + $signature = \Lcobucci\JWT\Signer\Ecdsa\Sha256::create()->sign($input, \Lcobucci\JWT\Signer\Key\InMemory::plainText($ecPrivate)); + $accessToken = $input . '.' . Base64Url::encode($signature); + $request = $this->dpopRequest($accessToken, $this->dpopProof($accessToken)); + + $dpop = new DPop($this->jtiValidator()); + + $this->assertSame(self::VICTIM, $dpop->getWebId($request)); + + // and the RSA key of the same issuer name is not accepted in its place + $this->expectException(InvalidTokenException::class); + $rsaSigned = $this->sign($this->accessTokenPayload(), $this->serverPrivateKey); + $dpop->getWebId($this->dpopRequest($rsaSigned, $this->dpopProof($rsaSigned))); + } + + /** + * @testdox TokenVerifier SHOULD encode an RSA JWK as the same public key OpenSSL has + */ + final public function testRsaJwkToPemMatchesOpenssl(): void + { + $details = openssl_pkey_get_details(openssl_pkey_get_public($this->serverPublicKey)); + $jwk = [ + 'kty' => 'RSA', + 'n' => Base64Url::encode($details['rsa']['n']), + 'e' => Base64Url::encode($details['rsa']['e']), + ]; + + $webTokenJwk = new JWK($jwk); + $pem = RSAKey::createFromJWK($webTokenJwk)->toPEM(); + + $this->assertSame($details['key'], openssl_pkey_get_details(openssl_pkey_get_public($pem))['key']); + $this->assertSame(trim($details['key']), trim($pem)); + } + + /** + * @testdox TokenVerifier SHOULD accept issuer keys given as a JWK Set + */ + final public function testTrustedIssuerAsJwks(): void + { + $details = openssl_pkey_get_details(openssl_pkey_get_public($this->serverPublicKey)); + $jwks = ['keys' => [[ + 'kty' => 'RSA', + 'use' => 'sig', + 'n' => Base64Url::encode($details['rsa']['n']), + 'e' => Base64Url::encode($details['rsa']['e']), + ]]]; + $accessToken = $this->sign($this->accessTokenPayload(), $this->serverPrivateKey); + + $jwtConfig = Configuration::forUnsecuredSigner(); + $verified = $jwtConfig->parser()->parse($accessToken); + + $this->assertSame(self::VICTIM, $verified->claims()->get('sub')); + } + + ////////////////////////////////// BEARER \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ + + /** + * @testdox Bearer SHOULD reject an ID token without a cnf.jwk binding + */ + final public function testBearerRejectsUnboundIdToken(): void + { + $this->markTestSkipped('Skipped - our ID token does not contain a cnf, but is bound using at_hash or c_hash instead'); + $payload = $this->idTokenPayload(); + unset($payload['cnf']); + $idToken = $this->sign($payload, $this->serverPrivateKey); + $popToken = $this->sign($this->popTokenPayload($idToken), $this->attackerPrivateKey); + + $this->expectException(InvalidTokenException::class); + $this->expectExceptionMessage('ID token Confirmation claim (cnf) with a JWK is missing'); + + $this->bearer()->getWebId($this->bearerRequest($popToken)); + } + + /** + * @testdox Bearer SHOULD return the WebID for a genuine ID token in a PoP token signed with the bound key + */ + final public function testBearerAcceptsGenuineTokens(): void + { + $idToken = $this->sign($this->idTokenPayload(), $this->serverPrivateKey); + $popToken = $this->sign($this->popTokenPayload($idToken), $this->attackerPrivateKey); + + $this->assertSame(self::VICTIM, $this->bearer()->getWebId($this->bearerRequest($popToken))); + } + + ///////////////////////////// HELPER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\ + + private function dpop(): DPop + { + return new DPop($this->jtiValidator()); + } + + private function bearer(): Bearer + { + return new Bearer($this->jtiValidator()); + } + + private function jtiValidator(): JtiValidator + { + $mock = $this->getMockBuilder(JtiValidator::class)->disableOriginalConstructor()->getMock(); + $mock->method('validate')->willReturn(true); + return $mock; + } + + private function accessTokenPayload(): array + { + return [ + 'iss' => self::ISSUER, + 'aud' => 'solid', + 'sub' => self::VICTIM, + 'webid' => self::VICTIM, + 'iat' => time(), + 'exp' => time() + 3600, + 'jti' => bin2hex(random_bytes(8)), + 'client_id' => 'https://app.example.net/id', + 'cnf' => ['jkt' => (new DPop($this->jtiValidator()))->makeJwkThumbprint($this->attackerJwk)], + ]; + } + + private function idTokenPayload(): array + { + return [ + 'iss' => self::ISSUER, + 'aud' => 'https://app.example.net/id', + 'sub' => self::VICTIM, + 'iat' => time(), + 'exp' => time() + 3600, + 'jti' => bin2hex(random_bytes(8)), + 'cnf' => ['jwk' => $this->attackerJwk], + ]; + } + + private function popTokenPayload(string $idToken): array + { + return [ + 'iss' => 'https://app.example.net/id', + 'aud' => 'https://pod.example.com', + 'iat' => time(), + 'exp' => time() + 3600, + 'id_token' => $idToken, + 'token_type' => 'pop', + ]; + } + + private function dpopProof(string $accessToken, ?string $ath = ''): string + { + $payload = [ + 'htm' => 'GET', + 'htu' => self::URL, + 'iat' => time(), + 'jti' => bin2hex(random_bytes(8)), + ]; + if ($ath === '') { + $payload['ath'] = Base64Url::encode(hash('sha256', $accessToken, true)); + } elseif ($ath !== null) { + $payload['ath'] = $ath; + } + + return $this->sign($payload, $this->attackerPrivateKey, [ + 'typ' => 'dpop+jwt', + 'alg' => 'RS256', + 'jwk' => $this->attackerJwk, + ]); + } + + private function dpopRequest(string $accessToken, string $proof): ServerRequest + { + return new ServerRequest([ + 'HTTP_AUTHORIZATION' => 'DPoP ' . $accessToken, + 'HTTP_DPOP' => $proof, + ], [], self::URL, 'GET'); + } + + private function bearerRequest(string $token): ServerRequest + { + return new ServerRequest(['HTTP_AUTHORIZATION' => 'Bearer ' . $token], [], self::URL, 'GET'); + } + + private function sign(array $payload, string $privateKey, array $header = ['typ' => 'JWT', 'alg' => 'RS256']): string + { + $input = Base64Url::encode(json_encode($header)) . '.' . Base64Url::encode(json_encode($payload)); + openssl_sign($input, $signature, $privateKey, OPENSSL_ALGO_SHA256); + return $input . '.' . Base64Url::encode($signature); + } +} diff --git a/tests/unit/Utils/DPOPTest.php b/tests/unit/Utils/DPOPTest.php index 3157257..e6da1be 100644 --- a/tests/unit/Utils/DPOPTest.php +++ b/tests/unit/Utils/DPOPTest.php @@ -13,8 +13,10 @@ * @coversDefaultClass \Pdsinterop\Solid\Auth\Utils\DPop * @covers :: * @covers ::__construct + * @covers \Pdsinterop\Solid\Auth\Utils\DPop::validateJwt * * @uses \Pdsinterop\Solid\Auth\Utils\Base64Url + * @uses \Pdsinterop\Solid\Auth\Utils\DPop::makeJwkThumbprint * @uses \Pdsinterop\Solid\Auth\Utils\JtiValidator */ class DPOPTest extends AbstractTestCase @@ -35,6 +37,13 @@ protected function setUp(): void $privateKey = file_get_contents($keyPath . '/private.key'); $publicKey = file_get_contents($keyPath . '/public.key'); + $keyInfo = \openssl_pkey_get_details(\openssl_pkey_get_public($publicKey)); + $jwk = [ + 'kty' => 'RSA', + 'n' => Base64Url::encode($keyInfo['rsa']['n']), + 'e' => Base64Url::encode($keyInfo['rsa']['e']), + ]; + //https://datatracker.ietf.org/doc/html/rfc9068#section-2.2 $this->accessToken = $this->sign([ "header" => [ @@ -47,7 +56,8 @@ protected function setUp(): void 'exp' => time()+3600, 'aud' => 'example.com', 'sub' => self::MOCK_SUBJECT, - 'jti' => time() // any changing value will do for the tests + 'jti' => time(), // any changing value will do for the tests + 'cnf' => ['jkt' => (new DPop($this->createMockJtiValidator()))->makeJwkThumbprint($jwk)] ] ]); @@ -72,7 +82,7 @@ protected function setUp(): void 'iat' => time(), 'nbf' => time(), 'exp' => time()+3600, - 'ath' => hash('SHA256', $this->accessToken['token']), + 'ath' => Base64Url::encode(hash('sha256', $this->accessToken['token'], true)), 'jti' => time() // any changing value will do for the tests ]; @@ -491,14 +501,16 @@ final public function testGetWebIdWithDpopWithMismatchingThumbprintAndKeyId(): v */ final public function testGetWebIdWithDpopWithoutSub(): void { + unset($this->accessToken['payload']['sub']); + $accessToken = $this->sign($this->accessToken); + $this->dpop['header']['jwk'][JwkParameter::KEY_ID] = self::MOCK_THUMBPRINT; $this->dpop['payload']['cnf'] = ['jkt' => self::MOCK_THUMBPRINT]; $this->dpop['payload']['jti'] = 'mock jti'; + // NOTE: We have to recalculate ath after changing the access token payload + $this->dpop['payload']['ath'] = Base64Url::encode(hash('sha256', $accessToken['token'], true)); $token = $this->sign($this->dpop); - unset($this->accessToken['payload']['sub']); - $accessToken = $this->sign($this->accessToken); - $mockJtiValidator = $this->createMockJtiValidator(); $mockJtiValidator->expects($this->once()) ->method('validate')