Debian Codegraph @

pkg/client/rp/key_binding.go

raw
1 package rp
2
3 import (
4 "crypto"
5 "crypto/ecdsa"
6 "crypto/ed25519"
7 "crypto/elliptic"
8 "crypto/rsa"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "io"
13 "net/http"
14 "net/url"
15 "reflect"
16 "slices"
17 "strings"
18 "time"
19
20 "github.com/go-jose/go-jose/v4"
21 "github.com/go-jose/go-jose/v4/cryptosigner"
22 "github.com/google/uuid"
23
24 "github.com/zitadel/oidc/v3/pkg/oidc"
25 )
26
27 var (
28 // ErrInvalidKeyBinding is returned when the key binding configuration is invalid.
29 //
30 // Experimental: OpenID Connect Key Binding 1.0 is a draft standard.
31 // This API may change or be removed without a major version bump.
32 ErrInvalidKeyBinding = errors.New("invalid key binding configuration")
33
34 // ErrKeyBindingIDToken is returned when a key-bound ID token is invalid.
35 //
36 // Experimental: OpenID Connect Key Binding 1.0 is a draft standard.
37 // This API may change or be removed without a major version bump.
38 ErrKeyBindingIDToken = errors.New("invalid key-bound ID token")
39
40 // ErrKeyBindingConfirmation is returned when the ID token confirmation
41 // does not match the binding key.
42 //
43 // Experimental: OpenID Connect Key Binding 1.0 is a draft standard.
44 // This API may change or be removed without a major version bump.
45 ErrKeyBindingConfirmation = errors.New("ID token confirmation does not match the binding key")
46
47 // ErrKeyBindingEndpoint is returned when a key-bound token request would be
48 // sent anywhere other than the expected token endpoint, e.g. a redirect.
49 //
50 // Experimental: OpenID Connect Key Binding 1.0 is a draft standard.
51 // This API may change or be removed without a major version bump.
52 ErrKeyBindingEndpoint = errors.New("key-bound request refused for a URL other than the token endpoint")
53 )
54
55 type keyBinding struct {
56 signer jose.Signer
57 thumbprint string
58 }
59
60 // KeyBindingRelyingParty is implemented by RPs configured with
61 // [WithKeyBinding].
62 //
63 // Experimental: OpenID Connect Key Binding 1.0 is a draft standard.
64 // This API may change or be removed without a major version bump.
65 type KeyBindingRelyingParty interface {
66 RelyingParty
67 KeyBindingThumbprint() string
68 SignDPoPProof(method, htu, code string) (string, error)
69 }
70
71 // WithKeyBinding enables OpenID Connect Key Binding for the authorization code,
72 // refresh and device authorization flows. The RP appends the `bound_key` scope,
73 // adds the `dpop_jkt` authorization request parameter, signs a DPoP proof for each
74 // token request, and verifies that the returned ID Token is actually bound to
75 // the provided signer.
76 //
77 // Signer may be any [crypto.Signer], including an HSM-backed signer. alg must
78 // be an asymmetric JWS algorithm supported by the signer's key.
79 //
80 // Experimental: OpenID Connect Key Binding 1.0 is a draft standard.
81 // This API may change or be removed without a major version bump.
82 func WithKeyBinding(signer crypto.Signer, alg jose.SignatureAlgorithm) Option {
83 return func(rp *relyingParty) error {
84 if rp.oauth2Only {
85 return fmt.Errorf("%w: key binding requires OpenID Connect", ErrInvalidOption)
86 }
87 if nilCryptoSigner(signer) {
88 return ErrInvalidKeyBinding
89 }
90 // Catch any signer alg mismatches early
91 if !keyBindingAlgMatchesKey(alg, signer.Public()) {
92 return fmt.Errorf("%w: algorithm %q does not match the signer's public key", ErrInvalidKeyBinding, alg)
93 }
94 // Reject a key the OP will reject anyway
95 if err := oidc.ValidateDPoPKeyStrength(signer.Public()); err != nil {
96 return fmt.Errorf("%w: %v", ErrInvalidKeyBinding, err)
97 }
98 publicJWK := &jose.JSONWebKey{Key: signer.Public(), Algorithm: string(alg)}
99 thumbprint, err := oidc.JWKThumbprint(publicJWK)
100 if err != nil {
101 return fmt.Errorf("%w: %v", ErrInvalidKeyBinding, err)
102 }
103 opaqueSigner := cryptosigner.Opaque(joseCryptoSigner{Signer: signer})
104 proofSigner, err := jose.NewSigner(
105 jose.SigningKey{Algorithm: alg, Key: keyBindingOpaqueSigner{OpaqueSigner: opaqueSigner, publicJWK: publicJWK}},
106 (&jose.SignerOptions{EmbedJWK: true}).WithType(oidc.DPoPProofType),
107 )
108 if err != nil {
109 return fmt.Errorf("%w: %v", ErrInvalidKeyBinding, err)
110 }
111 rp.keyBinding = &keyBinding{signer: proofSigner, thumbprint: thumbprint}
112 if !slices.Contains(rp.oauthConfig.Scopes, oidc.ScopeBoundKey) {
113 rp.oauthConfig.Scopes = append(slices.Clone(rp.oauthConfig.Scopes), oidc.ScopeBoundKey)
114 }
115 return nil
116 }
117 }
118
119 // joseCryptoSigner corrects rsa.PSSSaltLengthAuto used by cryptosigner.Opaque
120 // to the hash-length salt required by JWA for PS256, PS384, and PS512.
121 type joseCryptoSigner struct {
122 crypto.Signer
123 }
124
125 func (s joseCryptoSigner) Sign(random io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
126 if pss, ok := opts.(*rsa.PSSOptions); ok {
127 corrected := *pss
128 corrected.SaltLength = rsa.PSSSaltLengthEqualsHash
129 opts = &corrected
130 }
131 return s.Signer.Sign(random, digest, opts)
132 }
133
134 type keyBindingOpaqueSigner struct {
135 jose.OpaqueSigner
136 publicJWK *jose.JSONWebKey
137 }
138
139 func (s keyBindingOpaqueSigner) Public() *jose.JSONWebKey {
140 return s.publicJWK
141 }
142
143 func nilCryptoSigner(signer crypto.Signer) bool {
144 if signer == nil {
145 return true
146 }
147 value := reflect.ValueOf(signer)
148 switch value.Kind() {
149 case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
150 return value.IsNil()
151 default:
152 return false
153 }
154 }
155
156 // KeyBindingThumbprint returns the RFC 7638 SHA-256 JWK thumbprint of the
157 // binding key.
158 //
159 // Experimental: OpenID Connect Key Binding 1.0 is a draft standard.
160 // This API may change or be removed without a major version bump.
161 func (rp *relyingParty) KeyBindingThumbprint() string {
162 if rp.keyBinding == nil {
163 return ""
164 }
165 return rp.keyBinding.thumbprint
166 }
167
168 // SignDPoPProof creates and signs a DPoP proof JWT for the given HTTP method,
169 // URI, and optional authorization/device code.
170 //
171 // Experimental: OpenID Connect Key Binding 1.0 is a draft standard.
172 // This API may change or be removed without a major version bump.
173 func (rp *relyingParty) SignDPoPProof(method, htu, code string) (string, error) {
174 if rp.keyBinding == nil {
175 return "", ErrInvalidKeyBinding
176 }
177 return rp.keyBinding.proof(method, htu, code)
178 }
179
180 func keyBindingRP(rp RelyingParty) (KeyBindingRelyingParty, bool) {
181 configured, ok := rp.(KeyBindingRelyingParty)
182 return configured, ok && configured.KeyBindingThumbprint() != ""
183 }
184
185 func isAsymmetricKeyBindingAlgorithm(alg jose.SignatureAlgorithm) bool {
186 switch alg {
187 case jose.RS256, jose.RS384, jose.RS512,
188 jose.PS256, jose.PS384, jose.PS512,
189 jose.ES256, jose.ES384, jose.ES512,
190 jose.EdDSA:
191 return true
192 default:
193 return false
194 }
195 }
196
197 // keyBindingAlgMatchesKey reports whether alg can be produced by the public
198 // key pub. For the standard Go key types the pairing is fully determined (an
199 // EC key only matches the ES alg for its curve, an Ed25519 key only EdDSA, an
200 // RSA key any RS*/PS* alg). For opaque or KMS-backed keys that do not expose a
201 // standard public key type it falls back to requiring an asymmetric alg and
202 // lets the signer reject a genuine mismatch.
203 func keyBindingAlgMatchesKey(alg jose.SignatureAlgorithm, pub crypto.PublicKey) bool {
204 switch key := pub.(type) {
205 case *rsa.PublicKey:
206 switch alg {
207 case jose.RS256, jose.RS384, jose.RS512, jose.PS256, jose.PS384, jose.PS512:
208 return true
209 default:
210 return false
211 }
212 case *ecdsa.PublicKey:
213 switch alg {
214 case jose.ES256:
215 return key.Curve == elliptic.P256()
216 case jose.ES384:
217 return key.Curve == elliptic.P384()
218 case jose.ES512:
219 return key.Curve == elliptic.P521()
220 default:
221 return false
222 }
223 case ed25519.PublicKey:
224 return alg == jose.EdDSA
225 default:
226 return isAsymmetricKeyBindingAlgorithm(alg)
227 }
228 }
229
230 func (k *keyBinding) proof(method, tokenEndpoint, code string) (string, error) {
231 claims := oidc.DPoPProofClaims{
232 JWTID: uuid.NewString(),
233 HTTPMethod: method,
234 HTTPURI: tokenEndpoint,
235 IssuedAt: oidc.FromTime(time.Now()),
236 }
237 if code != "" {
238 claims.CodeHash = oidc.CodeHash(code)
239 }
240 payload, err := json.Marshal(claims)
241 if err != nil {
242 return "", err
243 }
244 signed, err := k.signer.Sign(payload)
245 if err != nil {
246 return "", err
247 }
248 return signed.CompactSerialize()
249 }
250
251 type keyBindingTransport struct {
252 base http.RoundTripper
253 binding KeyBindingRelyingParty
254 code string
255 tokenEndpointURI *url.URL
256 }
257
258 // htuClaim returns the DPoP htu value defined in RFC 9449, section 4.2,
259 // i.e., removing the query and fragment from a URI.
260 func htuClaim(u *url.URL) string {
261 n := *u
262 n.User = nil
263 n.RawQuery = ""
264 n.ForceQuery = false
265 n.Fragment = ""
266 n.RawFragment = ""
267 return n.String()
268 }
269
270 // htuKey returns a normalized version of the token endpoint URI
271 // for comparison per RFC 3986, sections 6.2.2 and 6.2.3.
272 func htuKey(u *url.URL) string {
273 n := *u
274 n.Scheme = strings.ToLower(n.Scheme)
275 n.Host = strings.ToLower(n.Host)
276 port := n.Port()
277
278 // Trim the default port off of the host. This avoids rebuilding
279 // from Hostname() as Hostname() removes the square brackets from
280 // IPv6 literals.
281 if n.Scheme == "https" && port == "443" {
282 n.Host = strings.TrimSuffix(n.Host, ":443")
283 } else if n.Scheme == "http" && port == "80" {
284 n.Host = strings.TrimSuffix(n.Host, ":80")
285 }
286 return htuClaim(&n)
287 }
288
289 func (t *keyBindingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
290 // Use the normalized htuKey for correct htu comparison
291 htuExpected := htuKey(t.tokenEndpointURI)
292 htuGot := htuKey(req.URL)
293
294 // Only ever sign a proof for the configured token endpoint. Without this,
295 // a 307/308 redirect from the token endpoint would make net/http replay the
296 // POST body (authorization code and client secret) to the redirect target,
297 // and this transport would helpfully mint a fresh proof for that host,
298 // disclosing c_s256 = SHA256(code) to it.
299 if htuGot != htuExpected {
300 return nil, fmt.Errorf("%w: got %q, expected %q", ErrKeyBindingEndpoint, htuGot, htuExpected)
301 }
302
303 // We should not perform full normalization on the actual htu claim in the DPoP proof.
304 htuClaim := htuClaim(t.tokenEndpointURI)
305 proof, err := t.binding.SignDPoPProof(req.Method, htuClaim, t.code)
306 if err != nil {
307 return nil, err
308 }
309 req = req.Clone(req.Context())
310 req.Header.Set(oidc.DPoPHeader, proof)
311 return t.base.RoundTrip(req)
312 }
313
314 // keyBindingHTTPClient returns a shallow copy of client whose transport adds a
315 // DPoP proof to a single token-endpoint request. tokenEndpoint pins the only
316 // URL a proof will be signed for. The token endpoint is validated here before
317 // any request is made.
318 func keyBindingHTTPClient(client *http.Client, binding KeyBindingRelyingParty, code, tokenEndpoint string) (*http.Client, error) {
319 if tokenEndpoint == "" {
320 return nil, fmt.Errorf("%w: token endpoint is not set", ErrInvalidKeyBinding)
321 }
322 tokenEndpointURI, err := url.Parse(tokenEndpoint)
323 if err != nil || !tokenEndpointURI.IsAbs() || tokenEndpointURI.Host == "" {
324 return nil, fmt.Errorf("%w: invalid token endpoint %q", ErrInvalidKeyBinding, tokenEndpoint)
325 }
326 clone := http.Client{}
327 if client != nil {
328 clone = *client
329 }
330 base := clone.Transport
331 if base == nil {
332 base = http.DefaultTransport
333 }
334 clone.Transport = &keyBindingTransport{
335 base: base,
336 binding: binding,
337 code: code,
338 tokenEndpointURI: tokenEndpointURI,
339 }
340 // Refuse redirects rather than re-POST the code to another host.
341 clone.CheckRedirect = func(req *http.Request, via []*http.Request) error {
342 return fmt.Errorf("%w: token endpoint redirect to %q refused", ErrKeyBindingEndpoint, req.URL.Redacted())
343 }
344 return &clone, nil
345 }
346
347 // verifyKeyBindingIDToken checks that token is actually bound to the RP's
348 // binding key, by requiring the protected `typ` header to be
349 // [oidc.IDTokenTypeDPoP] and cnf.jwk to be the key identified by expectedJKT.
350 // The token is re-parsed here solely to reach the protected header and the
351 // `cnf` claim, which the generic claims types do not expose.
352 func verifyKeyBindingIDToken(token string, alg jose.SignatureAlgorithm, expectedJKT string) error {
353 signed, err := jose.ParseSigned(token, []jose.SignatureAlgorithm{alg})
354 if err != nil || len(signed.Signatures) != 1 {
355 return ErrKeyBindingIDToken
356 }
357 typ, _ := signed.Signatures[0].Header.ExtraHeaders[jose.HeaderType].(string)
358 if typ != string(oidc.IDTokenTypeDPoP) {
359 return fmt.Errorf("%w: unexpected typ %q", ErrKeyBindingIDToken, typ)
360 }
361 // Safe: the signature over this exact token string was already verified by
362 // the caller (see the contract above), so the payload is authentic. Parsing
363 // it again only to read `cnf` avoids re-implementing signature checks.
364 payload := signed.UnsafePayloadWithoutVerification()
365 var claims struct {
366 Confirmation *oidc.Confirmation `json:"cnf"`
367 }
368 if err := json.Unmarshal(payload, &claims); err != nil || claims.Confirmation == nil {
369 return fmt.Errorf("%w: missing cnf.jwk", ErrKeyBindingIDToken)
370 }
371 var jwk jose.JSONWebKey
372 if err := json.Unmarshal(claims.Confirmation.JWK, &jwk); err != nil || !jwk.Valid() || !jwk.IsPublic() {
373 return fmt.Errorf("%w: invalid cnf.jwk", ErrKeyBindingIDToken)
374 }
375 actualJKT, err := oidc.JWKThumbprint(&jwk)
376 if err != nil {
377 return fmt.Errorf("%w: invalid cnf.jwk", ErrKeyBindingIDToken)
378 }
379 if actualJKT != expectedJKT {
380 return ErrKeyBindingConfirmation
381 }
382 return nil
383 }