-
Notifications
You must be signed in to change notification settings - Fork 4
/
client_authentication.go
406 lines (313 loc) · 12.9 KB
/
client_authentication.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2
import (
"context"
"crypto"
"crypto/ecdsa"
"crypto/rsa"
"encoding/base64"
"errors"
"net/http"
"net/url"
"sort"
"strings"
"github.com/go-jose/go-jose/v4"
"authelia.com/provider/oauth2/internal/consts"
"authelia.com/provider/oauth2/token/jwt"
"authelia.com/provider/oauth2/x/errorsx"
)
// ClientAuthenticationStrategy describes a client authentication strategy implementation.
type ClientAuthenticationStrategy interface {
AuthenticateClient(ctx context.Context, r *http.Request, form url.Values, handler EndpointClientAuthHandler) (client Client, method string, err error)
}
var (
ErrClientSecretNotRegistered = errors.New("error occurred checking the client secret: the client is not registered with a secret")
)
// AuthenticateClient authenticates client requests using the configured strategy returned by the oauth2.Configurator
// function GetClientAuthenticationStrategy, if nil it uses `oauth2.DefaultClientAuthenticationStrategy`.
func (f *Fosite) AuthenticateClient(ctx context.Context, r *http.Request, form url.Values) (client Client, method string, err error) {
return f.AuthenticateClientWithAuthHandler(ctx, r, form, &TokenEndpointClientAuthHandler{})
}
func (f *Fosite) AuthenticateClientWithAuthHandler(ctx context.Context, r *http.Request, form url.Values, handler EndpointClientAuthHandler) (client Client, method string, err error) {
var strategy ClientAuthenticationStrategy
if strategy = f.Config.GetClientAuthenticationStrategy(ctx); strategy == nil {
strategy = &DefaultClientAuthenticationStrategy{Store: f.Store, Config: f.Config}
}
return strategy.AuthenticateClient(ctx, r, form, handler)
}
func (f *Fosite) findClientPublicJWK(ctx context.Context, client JARClient, t *jwt.Token, expectsRSAKey bool) (key any, err error) {
var (
keys *jose.JSONWebKeySet
)
if keys = client.GetJSONWebKeys(); keys != nil {
return findPublicKey(t, keys, expectsRSAKey)
}
if location := client.GetJSONWebKeysURI(); len(location) > 0 {
if keys, err = f.Config.GetJWKSFetcherStrategy(ctx).Resolve(ctx, location, false); err != nil {
return nil, err
}
if key, err = findPublicKey(t, keys, expectsRSAKey); err == nil {
return key, nil
}
if keys, err = f.Config.GetJWKSFetcherStrategy(ctx).Resolve(ctx, location, true); err != nil {
return nil, err
}
return findPublicKey(t, keys, expectsRSAKey)
}
return nil, errorsx.WithStack(ErrInvalidClient.WithHint("The OAuth 2.0 Client has no JSON Web Keys set registered, but they are needed to complete the request."))
}
// CompareClientSecret compares a raw secret input from a client to the registered client secret. If the secret is valid
// it returns nil, otherwise it returns an error. The ErrClientSecretNotRegistered error indicates the ClientSecret
// is nil, all other errors are returned directly from the ClientSecret.Compare function.
func CompareClientSecret(ctx context.Context, client Client, rawSecret []byte) (err error) {
secret := client.GetClientSecret()
if secret == nil || !secret.Valid() {
return ErrClientSecretNotRegistered
}
if err = secret.Compare(ctx, rawSecret); err == nil {
return nil
}
var (
rotated RotatedClientSecretsClient
ok bool
)
if rotated, ok = client.(RotatedClientSecretsClient); !ok {
return err
}
for _, secret = range rotated.GetRotatedClientSecrets() {
if secret == nil {
continue
}
if secret.Compare(ctx, rawSecret) == nil {
return nil
}
}
return err
}
// FindClientPublicJWK takes a JARClient and a kid, alg, and use to resolve a Public JWK for the client.
func FindClientPublicJWK(ctx context.Context, provider JWKSFetcherStrategyProvider, client JSONWebKeysClient, kid, alg, use string) (key any, err error) {
if set := client.GetJSONWebKeys(); set != nil {
return findPublicKeyByKID(kid, alg, use, set)
}
strategy := provider.GetJWKSFetcherStrategy(ctx)
var keys *jose.JSONWebKeySet
if location := client.GetJSONWebKeysURI(); len(location) > 0 {
if keys, err = strategy.Resolve(ctx, location, false); err != nil {
return nil, err
}
if key, err = findPublicKeyByKID(kid, alg, use, keys); err == nil {
return key, nil
}
if keys, err = strategy.Resolve(ctx, location, true); err != nil {
return nil, err
}
return findPublicKeyByKID(kid, alg, use, keys)
}
return nil, errorsx.WithStack(ErrInvalidClient.WithHint("The OAuth 2.0 Client has no JSON Web Keys set registered, but they are needed to complete the request."))
}
func getClientCredentialsSecretBasic(r *http.Request) (id, secret string, ok bool, err error) {
auth := r.Header.Get(consts.HeaderAuthorization)
if auth == "" {
return "", "", false, nil
}
scheme, value, ok := strings.Cut(auth, " ")
if !ok {
return "", "", false, errorsx.WithStack(ErrInvalidRequest.WithHint("The client credentials from the HTTP authorization header could not be parsed.").WithWrap(err).WithDebug("The header value is either missing a scheme, value, or the separator between them."))
}
if !strings.EqualFold(scheme, "Basic") {
return "", "", false, errorsx.WithStack(ErrInvalidRequest.WithHint("The client credentials from the HTTP authorization header had an unknown scheme.").WithDebugf("The scheme '%s' is not known for client authentication.", scheme))
}
c, err := base64.StdEncoding.DecodeString(value)
if err != nil {
return "", "", false, errorsx.WithStack(ErrInvalidRequest.WithHint("The client credentials from the HTTP authorization header could not be parsed.").WithWrap(err).WithDebugf("Error occurred performing a base64 decode: %+v.", err))
}
cs := string(c)
id, secret, ok = strings.Cut(cs, ":")
if !ok {
return "", "", false, errorsx.WithStack(ErrInvalidRequest.WithHint("The client credentials from the HTTP authorization header could not be parsed.").WithDebug("The basic scheme value was not separated by a colon."))
}
if id, err = url.QueryUnescape(id); err != nil {
return "", "", false, errorsx.WithStack(ErrInvalidRequest.WithHint("The client id in the HTTP authorization header could not be decoded from 'application/x-www-form-urlencoded'.").WithWrap(err).WithDebugError(err))
}
if secret, err = url.QueryUnescape(secret); err != nil {
return "", "", false, errorsx.WithStack(ErrInvalidRequest.WithHint("The client secret in the HTTP authorization header could not be decoded from 'application/x-www-form-urlencoded'.").WithWrap(err).WithDebugError(err))
}
if len(id) != 0 && !RegexSpecificationVSCHAR.MatchString(id) {
return "", "", false, errorsx.WithStack(ErrInvalidRequest.WithHint("The client id in the HTTP request had an invalid character."))
}
if len(secret) != 0 && !RegexSpecificationVSCHAR.MatchString(secret) {
return "", "", false, errorsx.WithStack(ErrInvalidRequest.WithHint("The client secret in the HTTP request had an invalid character."))
}
return id, secret, secret != "", nil
}
func getJWTHeaderKIDAlg(header map[string]any) (kid, alg string) {
kid, _ = header[consts.JSONWebTokenHeaderKeyIdentifier].(string)
alg, _ = header[consts.JSONWebTokenHeaderAlgorithm].(string)
return kid, alg
}
type partial struct {
points int
jwk jose.JSONWebKey
}
func findPublicKeyByKID(kid, alg, use string, set *jose.JSONWebKeySet) (key any, err error) {
if len(set.Keys) == 0 {
return nil, errorsx.WithStack(ErrInvalidRequest.WithHintf("The retrieved JSON Web Key Set does not contain any JSON Web Keys."))
}
partials := []partial{}
for _, jwk := range set.Keys {
if jwk.Use == use && jwk.Algorithm == alg && jwk.KeyID == kid {
switch k := jwk.Key.(type) {
case PrivateKey:
return k.Public(), nil
default:
return k, nil
}
}
p := partial{}
if jwk.KeyID != kid {
if jwk.KeyID == "" {
p.points -= 3
} else {
continue
}
}
if jwk.Use != use {
if jwk.Use == "" {
p.points -= 2
} else {
continue
}
}
if jwk.Algorithm != alg && jwk.Algorithm != "" {
if jwk.Algorithm == "" {
p.points -= 1
} else {
continue
}
}
p.jwk = jwk
partials = append(partials, p)
}
if len(partials) != 0 {
sort.Slice(partials, func(i, j int) bool {
return partials[i].points > partials[j].points
})
switch k := partials[0].jwk.Key.(type) {
case PrivateKey:
return k.Public(), nil
default:
return k, nil
}
}
return nil, errorsx.WithStack(ErrInvalidRequest.WithHintf("Unable to find JWK with kid value '%s', alg value '%s', and use value '%s' in the JSON Web Key Set.", kid, alg, use))
}
func findPublicKey(t *jwt.Token, set *jose.JSONWebKeySet, expectsRSAKey bool) (any, error) {
keys := set.Keys
if len(keys) == 0 {
return nil, errorsx.WithStack(ErrInvalidRequest.WithHintf("The retrieved JSON Web Key Set does not contain any key."))
}
kid, ok := t.Header[consts.JSONWebTokenHeaderKeyIdentifier].(string)
if ok {
keys = set.Key(kid)
}
if len(keys) == 0 {
return nil, errorsx.WithStack(ErrInvalidRequest.WithHintf("The JSON Web Token uses signing key with kid '%s', which could not be found.", kid))
}
for _, key := range keys {
if key.Use != consts.JSONWebTokenUseSignature {
continue
}
if expectsRSAKey {
if k, ok := key.Key.(*rsa.PublicKey); ok {
return k, nil
}
} else {
if k, ok := key.Key.(*ecdsa.PublicKey); ok {
return k, nil
}
}
}
if expectsRSAKey {
return nil, errorsx.WithStack(ErrInvalidRequest.WithHintf("Unable to find RSA public key with use='sig' for kid '%s' in JSON Web Key Set.", kid))
} else {
return nil, errorsx.WithStack(ErrInvalidRequest.WithHintf("Unable to find ECDSA public key with use='sig' for kid '%s' in JSON Web Key Set.", kid))
}
}
func getClientCredentialsClientAssertion(form url.Values) (assertion, assertionType string, hasAssertion bool) {
assertionType, assertion = form.Get(consts.FormParameterClientAssertionType), form.Get(consts.FormParameterClientAssertion)
return assertion, assertionType, len(assertion) != 0 || len(assertionType) != 0
}
func getClientCredentialsClientIDValid(post, header string, assertion *ClientAssertion) (id string, err error) {
if len(post) != 0 {
id = post
} else if len(header) != 0 {
id = header
}
if len(id) == 0 {
if assertion != nil {
return assertion.ID, nil
}
return id, errorsx.WithStack(ErrInvalidRequest.WithHint("Client Credentials missing or malformed.").WithDebug("The Client ID was missing from the request but it is required when there is no client assertion."))
}
if !RegexSpecificationVSCHAR.MatchString(id) {
return id, errorsx.WithStack(ErrInvalidRequest.WithHint("The client id in the request had an invalid character."))
}
return id, nil
}
// EndpointClientAuthHandler is a helper implementation to assist with producing the correct values while using multiple
// endpoint implementations.
type EndpointClientAuthHandler interface {
// GetAuthMethod returns the appropriate auth method for this client.
GetAuthMethod(client AuthenticationMethodClient) string
// GetAuthSigningAlg returns the appropriate auth signature algorithm for this client.
GetAuthSigningAlg(client AuthenticationMethodClient) string
// Name returns the appropriate name for this endpoint for logging purposes.
Name() string
// AllowAuthMethodAny returns true if this endpoint client auth handler is allowed to be used for any method if not configured.
AllowAuthMethodAny() bool
}
type TokenEndpointClientAuthHandler struct{}
func (h *TokenEndpointClientAuthHandler) GetAuthMethod(client AuthenticationMethodClient) string {
return client.GetTokenEndpointAuthMethod()
}
func (h *TokenEndpointClientAuthHandler) GetAuthSigningAlg(client AuthenticationMethodClient) string {
return client.GetTokenEndpointAuthSigningAlg()
}
func (h *TokenEndpointClientAuthHandler) Name() string {
return "token"
}
func (h *TokenEndpointClientAuthHandler) AllowAuthMethodAny() bool {
return false
}
type IntrospectionEndpointClientAuthHandler struct{}
func (h *IntrospectionEndpointClientAuthHandler) GetAuthMethod(client AuthenticationMethodClient) string {
return client.GetIntrospectionEndpointAuthMethod()
}
func (h *IntrospectionEndpointClientAuthHandler) GetAuthSigningAlg(client AuthenticationMethodClient) string {
return client.GetIntrospectionEndpointAuthSigningAlg()
}
func (h *IntrospectionEndpointClientAuthHandler) Name() string {
return "introspection"
}
func (h *IntrospectionEndpointClientAuthHandler) AllowAuthMethodAny() bool {
return true
}
type RevocationEndpointClientAuthHandler struct{}
func (h *RevocationEndpointClientAuthHandler) GetAuthMethod(client AuthenticationMethodClient) string {
return client.GetRevocationEndpointAuthMethod()
}
func (h *RevocationEndpointClientAuthHandler) GetAuthSigningAlg(client AuthenticationMethodClient) string {
return client.GetRevocationEndpointAuthSigningAlg()
}
func (h *RevocationEndpointClientAuthHandler) Name() string {
return "revocation"
}
func (h *RevocationEndpointClientAuthHandler) AllowAuthMethodAny() bool {
return true
}
// PrivateKey properly describes crypto.PrivateKey.
type PrivateKey interface {
Public() crypto.PublicKey
Equal(x crypto.PrivateKey) bool
}