authentik.providers.oauth2.tests.test_token_jwt_alg_confusion

Security regression tests for JWT algorithm-confusion against the client_credentials JWT-bearer grant (RFC 9700 §4.5, CVE-2015-9235): alg:none, HS/RS key confusion (RSA public key used as an HMAC secret), and kid swapping. Assert the forgeries are rejected, including when the source JWK omits alg and verification falls back to the attacker-controlled header algorithm.

  1"""Security regression tests for JWT algorithm-confusion against the
  2client_credentials JWT-bearer grant (RFC 9700 §4.5, CVE-2015-9235): alg:none,
  3HS/RS key confusion (RSA public key used as an HMAC secret), and kid swapping.
  4Assert the forgeries are rejected, including when the source JWK omits ``alg``
  5and verification falls back to the attacker-controlled header algorithm.
  6"""
  7
  8import hashlib
  9import hmac
 10from base64 import urlsafe_b64encode
 11from copy import deepcopy
 12from datetime import datetime, timedelta
 13from json import dumps, loads
 14
 15from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
 16from django.test import RequestFactory
 17from django.urls import reverse
 18from jwt import encode
 19
 20from authentik.blueprints.tests import apply_blueprint
 21from authentik.common.oauth.constants import (
 22    CLIENT_ASSERTION_TYPE_JWT,
 23    GRANT_TYPE_CLIENT_CREDENTIALS,
 24    SCOPE_OPENID,
 25    SCOPE_OPENID_EMAIL,
 26    SCOPE_OPENID_PROFILE,
 27)
 28from authentik.core.models import Application, User
 29from authentik.core.tests.utils import create_test_cert, create_test_flow
 30from authentik.lib.generators import generate_id
 31from authentik.providers.oauth2.models import (
 32    GrantType,
 33    OAuth2Provider,
 34    RedirectURI,
 35    RedirectURIMatchingMode,
 36    ScopeMapping,
 37)
 38from authentik.providers.oauth2.tests.utils import OAuthTestCase
 39from authentik.providers.oauth2.views.jwks import JWKSView
 40from authentik.sources.oauth.models import OAuthSource
 41
 42
 43class TestTokenJWTAlgConfusion(OAuthTestCase):
 44    """Algorithm-confusion negative-path tests for the JWT-bearer grant."""
 45
 46    @apply_blueprint("system/providers-oauth2.yaml")
 47    def setUp(self) -> None:
 48        super().setUp()
 49        self.factory = RequestFactory()
 50        # Cert whose public key backs the trusted source JWK -- an attacker can
 51        # read this public key from the source's JWKS endpoint.
 52        self.source_cert = create_test_cert()
 53        self.provider_cert = create_test_cert()
 54
 55        jwk = JWKSView().get_jwk_for_key(self.source_cert, "sig")
 56        self.source: OAuthSource = OAuthSource.objects.create(
 57            name=generate_id(),
 58            slug=generate_id(),
 59            provider_type="openidconnect",
 60            consumer_key=generate_id(),
 61            consumer_secret=generate_id(),
 62            authorization_url="http://foo",
 63            access_token_url=f"http://{generate_id()}",
 64            profile_url="http://foo",
 65            oidc_well_known_url="",
 66            oidc_jwks_url="",
 67            oidc_jwks={"keys": [jwk]},
 68        )
 69
 70        self.provider: OAuth2Provider = OAuth2Provider.objects.create(
 71            name=generate_id(),
 72            authorization_flow=create_test_flow(),
 73            redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://testserver")],
 74            signing_key=self.provider_cert,
 75            grant_types=[GrantType.CLIENT_CREDENTIALS],
 76        )
 77        self.provider.jwt_federation_sources.add(self.source)
 78        self.provider.property_mappings.set(ScopeMapping.objects.all())
 79        self.app = Application.objects.create(
 80            name=generate_id(), slug=generate_id(), provider=self.provider
 81        )
 82
 83    def _public_key_secret_candidates(self) -> dict[str, bytes]:
 84        """The public-key byte representations a real attacker would scrape from
 85        the published JWKS/cert and try as the forged HMAC secret. These are the
 86        two representations actual tooling (e.g. jwt_tool) uses for HS/RS
 87        confusion: the bare public key PEM and the x5c certificate PEM."""
 88        public_key = self.source_cert.public_key
 89        return {
 90            "spki_pem": public_key.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo),
 91            "cert_pem": self.source_cert.certificate.public_bytes(Encoding.PEM),
 92        }
 93
 94    @staticmethod
 95    def _forge_hs256(payload: dict, secret: bytes, kid: str) -> str:
 96        """Hand-craft an HS256-signed JWT. PyJWT's ``encode`` refuses to use an
 97        asymmetric key as an HMAC secret, so -- like jwt_tool and other offensive
 98        tooling -- we build the token manually to faithfully simulate the attack."""
 99
100        def segment(data: bytes) -> bytes:
101            return urlsafe_b64encode(data).rstrip(b"=")
102
103        header = segment(dumps({"alg": "HS256", "typ": "JWT", "kid": kid}).encode())
104        body = segment(dumps(payload).encode())
105        signing_input = header + b"." + body
106        signature = segment(hmac.new(secret, signing_input, hashlib.sha256).digest())
107        return (signing_input + b"." + signature).decode()
108
109    @staticmethod
110    def _exp() -> int:
111        return int((datetime.now() + timedelta(hours=2)).timestamp())
112
113    def _post_assertion(self, assertion: str):
114        return self.client.post(
115            reverse("authentik_providers_oauth2:token"),
116            {
117                "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS,
118                "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}",
119                "client_id": self.provider.client_id,
120                "client_assertion_type": CLIENT_ASSERTION_TYPE_JWT,
121                "client_assertion": assertion,
122            },
123        )
124
125    def _assert_rejected(self, response):
126        self.assertEqual(response.status_code, 400)
127        self.assertEqual(loads(response.content.decode())["error"], "invalid_grant")
128        # A rejected assertion must not auto-provision a user as a side effect
129        self.assertIsNone(User.objects.filter(username=f"{self.provider.name}-foo").first())
130
131    def test_alg_none(self):
132        """An unsigned (alg:none) assertion with a valid kid must be rejected."""
133        forged = encode(
134            {"sub": "foo", "exp": self._exp()},
135            key="",
136            algorithm="none",
137            headers={"kid": self.source_cert.kid},
138        )
139        self._assert_rejected(self._post_assertion(forged))
140
141    def test_hs256_confusion_with_alg_in_jwk(self):
142        """HS256 forgery signed with the source's RSA public key, against a JWK
143        that pins alg=RS256. The header-declared HS256 must not be honored, for
144        any public-key byte representation the attacker might use as the secret."""
145        for label, secret in self._public_key_secret_candidates().items():
146            with self.subTest(secret=label):
147                forged = self._forge_hs256(
148                    {"sub": "foo", "exp": self._exp()},
149                    secret=secret,
150                    kid=self.source_cert.kid,
151                )
152                self._assert_rejected(self._post_assertion(forged))
153
154    def test_hs256_confusion_without_alg_in_jwk(self):
155        """The dangerous case: when the source JWK omits ``alg``, verification
156        falls back to the attacker-controlled header algorithm. An HS256 forgery
157        signed with the RSA public key must still be rejected (PyJWT refuses to
158        use an asymmetric key as an HMAC secret) -- for every public-key byte
159        representation the attacker might try as the secret."""
160        # Rebuild the source's JWK set without the alg member to force the fallback
161        jwks = deepcopy(self.source.oidc_jwks)
162        for key in jwks["keys"]:
163            key.pop("alg", None)
164        self.source.oidc_jwks = jwks
165        self.source.save()
166
167        for label, secret in self._public_key_secret_candidates().items():
168            with self.subTest(secret=label):
169                forged = self._forge_hs256(
170                    {"sub": "foo", "exp": self._exp()},
171                    secret=secret,
172                    kid=self.source_cert.kid,
173                )
174                self._assert_rejected(self._post_assertion(forged))
175
176    def test_kid_swapped_to_unrelated_key(self):
177        """A token signed with an unrelated key but carrying a kid that matches a
178        trusted source JWK must not verify."""
179        forged = encode(
180            {"sub": "foo", "exp": self._exp()},
181            key=self.provider_cert.private_key,  # not the source's key
182            algorithm="RS256",
183            headers={"kid": self.source_cert.kid},
184        )
185        self._assert_rejected(self._post_assertion(forged))
class TestTokenJWTAlgConfusion(authentik.providers.oauth2.tests.utils.OAuthTestCase):
 44class TestTokenJWTAlgConfusion(OAuthTestCase):
 45    """Algorithm-confusion negative-path tests for the JWT-bearer grant."""
 46
 47    @apply_blueprint("system/providers-oauth2.yaml")
 48    def setUp(self) -> None:
 49        super().setUp()
 50        self.factory = RequestFactory()
 51        # Cert whose public key backs the trusted source JWK -- an attacker can
 52        # read this public key from the source's JWKS endpoint.
 53        self.source_cert = create_test_cert()
 54        self.provider_cert = create_test_cert()
 55
 56        jwk = JWKSView().get_jwk_for_key(self.source_cert, "sig")
 57        self.source: OAuthSource = OAuthSource.objects.create(
 58            name=generate_id(),
 59            slug=generate_id(),
 60            provider_type="openidconnect",
 61            consumer_key=generate_id(),
 62            consumer_secret=generate_id(),
 63            authorization_url="http://foo",
 64            access_token_url=f"http://{generate_id()}",
 65            profile_url="http://foo",
 66            oidc_well_known_url="",
 67            oidc_jwks_url="",
 68            oidc_jwks={"keys": [jwk]},
 69        )
 70
 71        self.provider: OAuth2Provider = OAuth2Provider.objects.create(
 72            name=generate_id(),
 73            authorization_flow=create_test_flow(),
 74            redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://testserver")],
 75            signing_key=self.provider_cert,
 76            grant_types=[GrantType.CLIENT_CREDENTIALS],
 77        )
 78        self.provider.jwt_federation_sources.add(self.source)
 79        self.provider.property_mappings.set(ScopeMapping.objects.all())
 80        self.app = Application.objects.create(
 81            name=generate_id(), slug=generate_id(), provider=self.provider
 82        )
 83
 84    def _public_key_secret_candidates(self) -> dict[str, bytes]:
 85        """The public-key byte representations a real attacker would scrape from
 86        the published JWKS/cert and try as the forged HMAC secret. These are the
 87        two representations actual tooling (e.g. jwt_tool) uses for HS/RS
 88        confusion: the bare public key PEM and the x5c certificate PEM."""
 89        public_key = self.source_cert.public_key
 90        return {
 91            "spki_pem": public_key.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo),
 92            "cert_pem": self.source_cert.certificate.public_bytes(Encoding.PEM),
 93        }
 94
 95    @staticmethod
 96    def _forge_hs256(payload: dict, secret: bytes, kid: str) -> str:
 97        """Hand-craft an HS256-signed JWT. PyJWT's ``encode`` refuses to use an
 98        asymmetric key as an HMAC secret, so -- like jwt_tool and other offensive
 99        tooling -- we build the token manually to faithfully simulate the attack."""
100
101        def segment(data: bytes) -> bytes:
102            return urlsafe_b64encode(data).rstrip(b"=")
103
104        header = segment(dumps({"alg": "HS256", "typ": "JWT", "kid": kid}).encode())
105        body = segment(dumps(payload).encode())
106        signing_input = header + b"." + body
107        signature = segment(hmac.new(secret, signing_input, hashlib.sha256).digest())
108        return (signing_input + b"." + signature).decode()
109
110    @staticmethod
111    def _exp() -> int:
112        return int((datetime.now() + timedelta(hours=2)).timestamp())
113
114    def _post_assertion(self, assertion: str):
115        return self.client.post(
116            reverse("authentik_providers_oauth2:token"),
117            {
118                "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS,
119                "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}",
120                "client_id": self.provider.client_id,
121                "client_assertion_type": CLIENT_ASSERTION_TYPE_JWT,
122                "client_assertion": assertion,
123            },
124        )
125
126    def _assert_rejected(self, response):
127        self.assertEqual(response.status_code, 400)
128        self.assertEqual(loads(response.content.decode())["error"], "invalid_grant")
129        # A rejected assertion must not auto-provision a user as a side effect
130        self.assertIsNone(User.objects.filter(username=f"{self.provider.name}-foo").first())
131
132    def test_alg_none(self):
133        """An unsigned (alg:none) assertion with a valid kid must be rejected."""
134        forged = encode(
135            {"sub": "foo", "exp": self._exp()},
136            key="",
137            algorithm="none",
138            headers={"kid": self.source_cert.kid},
139        )
140        self._assert_rejected(self._post_assertion(forged))
141
142    def test_hs256_confusion_with_alg_in_jwk(self):
143        """HS256 forgery signed with the source's RSA public key, against a JWK
144        that pins alg=RS256. The header-declared HS256 must not be honored, for
145        any public-key byte representation the attacker might use as the secret."""
146        for label, secret in self._public_key_secret_candidates().items():
147            with self.subTest(secret=label):
148                forged = self._forge_hs256(
149                    {"sub": "foo", "exp": self._exp()},
150                    secret=secret,
151                    kid=self.source_cert.kid,
152                )
153                self._assert_rejected(self._post_assertion(forged))
154
155    def test_hs256_confusion_without_alg_in_jwk(self):
156        """The dangerous case: when the source JWK omits ``alg``, verification
157        falls back to the attacker-controlled header algorithm. An HS256 forgery
158        signed with the RSA public key must still be rejected (PyJWT refuses to
159        use an asymmetric key as an HMAC secret) -- for every public-key byte
160        representation the attacker might try as the secret."""
161        # Rebuild the source's JWK set without the alg member to force the fallback
162        jwks = deepcopy(self.source.oidc_jwks)
163        for key in jwks["keys"]:
164            key.pop("alg", None)
165        self.source.oidc_jwks = jwks
166        self.source.save()
167
168        for label, secret in self._public_key_secret_candidates().items():
169            with self.subTest(secret=label):
170                forged = self._forge_hs256(
171                    {"sub": "foo", "exp": self._exp()},
172                    secret=secret,
173                    kid=self.source_cert.kid,
174                )
175                self._assert_rejected(self._post_assertion(forged))
176
177    def test_kid_swapped_to_unrelated_key(self):
178        """A token signed with an unrelated key but carrying a kid that matches a
179        trusted source JWK must not verify."""
180        forged = encode(
181            {"sub": "foo", "exp": self._exp()},
182            key=self.provider_cert.private_key,  # not the source's key
183            algorithm="RS256",
184            headers={"kid": self.source_cert.kid},
185        )
186        self._assert_rejected(self._post_assertion(forged))

Algorithm-confusion negative-path tests for the JWT-bearer grant.

@apply_blueprint('system/providers-oauth2.yaml')
def setUp(self) -> None:
47    @apply_blueprint("system/providers-oauth2.yaml")
48    def setUp(self) -> None:
49        super().setUp()
50        self.factory = RequestFactory()
51        # Cert whose public key backs the trusted source JWK -- an attacker can
52        # read this public key from the source's JWKS endpoint.
53        self.source_cert = create_test_cert()
54        self.provider_cert = create_test_cert()
55
56        jwk = JWKSView().get_jwk_for_key(self.source_cert, "sig")
57        self.source: OAuthSource = OAuthSource.objects.create(
58            name=generate_id(),
59            slug=generate_id(),
60            provider_type="openidconnect",
61            consumer_key=generate_id(),
62            consumer_secret=generate_id(),
63            authorization_url="http://foo",
64            access_token_url=f"http://{generate_id()}",
65            profile_url="http://foo",
66            oidc_well_known_url="",
67            oidc_jwks_url="",
68            oidc_jwks={"keys": [jwk]},
69        )
70
71        self.provider: OAuth2Provider = OAuth2Provider.objects.create(
72            name=generate_id(),
73            authorization_flow=create_test_flow(),
74            redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://testserver")],
75            signing_key=self.provider_cert,
76            grant_types=[GrantType.CLIENT_CREDENTIALS],
77        )
78        self.provider.jwt_federation_sources.add(self.source)
79        self.provider.property_mappings.set(ScopeMapping.objects.all())
80        self.app = Application.objects.create(
81            name=generate_id(), slug=generate_id(), provider=self.provider
82        )

Hook method for setting up the test fixture before exercising it.

def test_alg_none(self):
132    def test_alg_none(self):
133        """An unsigned (alg:none) assertion with a valid kid must be rejected."""
134        forged = encode(
135            {"sub": "foo", "exp": self._exp()},
136            key="",
137            algorithm="none",
138            headers={"kid": self.source_cert.kid},
139        )
140        self._assert_rejected(self._post_assertion(forged))

An unsigned (alg:none) assertion with a valid kid must be rejected.

def test_hs256_confusion_with_alg_in_jwk(self):
142    def test_hs256_confusion_with_alg_in_jwk(self):
143        """HS256 forgery signed with the source's RSA public key, against a JWK
144        that pins alg=RS256. The header-declared HS256 must not be honored, for
145        any public-key byte representation the attacker might use as the secret."""
146        for label, secret in self._public_key_secret_candidates().items():
147            with self.subTest(secret=label):
148                forged = self._forge_hs256(
149                    {"sub": "foo", "exp": self._exp()},
150                    secret=secret,
151                    kid=self.source_cert.kid,
152                )
153                self._assert_rejected(self._post_assertion(forged))

HS256 forgery signed with the source's RSA public key, against a JWK that pins alg=RS256. The header-declared HS256 must not be honored, for any public-key byte representation the attacker might use as the secret.

def test_hs256_confusion_without_alg_in_jwk(self):
155    def test_hs256_confusion_without_alg_in_jwk(self):
156        """The dangerous case: when the source JWK omits ``alg``, verification
157        falls back to the attacker-controlled header algorithm. An HS256 forgery
158        signed with the RSA public key must still be rejected (PyJWT refuses to
159        use an asymmetric key as an HMAC secret) -- for every public-key byte
160        representation the attacker might try as the secret."""
161        # Rebuild the source's JWK set without the alg member to force the fallback
162        jwks = deepcopy(self.source.oidc_jwks)
163        for key in jwks["keys"]:
164            key.pop("alg", None)
165        self.source.oidc_jwks = jwks
166        self.source.save()
167
168        for label, secret in self._public_key_secret_candidates().items():
169            with self.subTest(secret=label):
170                forged = self._forge_hs256(
171                    {"sub": "foo", "exp": self._exp()},
172                    secret=secret,
173                    kid=self.source_cert.kid,
174                )
175                self._assert_rejected(self._post_assertion(forged))

The dangerous case: when the source JWK omits alg, verification falls back to the attacker-controlled header algorithm. An HS256 forgery signed with the RSA public key must still be rejected (PyJWT refuses to use an asymmetric key as an HMAC secret) -- for every public-key byte representation the attacker might try as the secret.

def test_kid_swapped_to_unrelated_key(self):
177    def test_kid_swapped_to_unrelated_key(self):
178        """A token signed with an unrelated key but carrying a kid that matches a
179        trusted source JWK must not verify."""
180        forged = encode(
181            {"sub": "foo", "exp": self._exp()},
182            key=self.provider_cert.private_key,  # not the source's key
183            algorithm="RS256",
184            headers={"kid": self.source_cert.kid},
185        )
186        self._assert_rejected(self._post_assertion(forged))

A token signed with an unrelated key but carrying a kid that matches a trusted source JWK must not verify.