-
Notifications
You must be signed in to change notification settings - Fork 3
/
client_authentication_strategy.go
443 lines (360 loc) · 20 KB
/
client_authentication_strategy.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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
package oauth2
import (
"context"
"crypto/subtle"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"
xjwt "github.com/golang-jwt/jwt/v5"
"authelia.com/provider/oauth2/internal/consts"
"authelia.com/provider/oauth2/x/errorsx"
)
type DefaultClientAuthenticationStrategy struct {
Store interface {
ClientManager
}
Config interface {
JWKSFetcherStrategyProvider
AllowedJWTAssertionAudiencesProvider
}
}
func (s *DefaultClientAuthenticationStrategy) AuthenticateClient(ctx context.Context, r *http.Request, form url.Values, resolver EndpointClientAuthHandler) (client Client, method string, err error) {
var (
id, secret string
idBasic, secretBasic string
assertionValue, assertionType string
hasPost, hasBasic, hasAssertion bool
)
idBasic, secretBasic, hasBasic, err = getClientCredentialsSecretBasic(r)
if err != nil {
return nil, "", errorsx.WithStack(ErrInvalidRequest.WithHint("The client credentials in the HTTP authorization header could not be parsed. Either the scheme was missing, the scheme was invalid, or the value had malformed data.").WithWrap(err).WithDebugError(err))
}
id, secret, hasPost = s.getClientCredentialsSecretPost(form)
assertionValue, assertionType, hasAssertion = getClientCredentialsClientAssertion(form)
var assertion *ClientAssertion
if hasAssertion {
if assertion, err = NewClientAssertion(ctx, s.Store, assertionValue, assertionType, resolver); err != nil {
return nil, "", err
}
}
if id, err = getClientCredentialsClientIDValid(id, idBasic, assertion); err != nil {
return nil, "", err
}
// Allow simplification of client authentication.
if !hasPost && hasBasic {
secret = secretBasic
}
hasNone := !hasPost && !hasBasic && assertion == nil && len(id) != 0
return s.authenticate(ctx, id, secret, assertion, hasBasic, hasPost, hasNone, resolver)
}
func (s *DefaultClientAuthenticationStrategy) authenticate(ctx context.Context, id, secret string, assertion *ClientAssertion, hasBasic, hasPost, hasNone bool, resolver EndpointClientAuthHandler) (client Client, method string, err error) {
var methods []string
if hasBasic {
methods = append(methods, consts.ClientAuthMethodClientSecretBasic)
}
if hasPost {
methods = append(methods, consts.ClientAuthMethodClientSecretPost)
}
if hasNone {
methods = append(methods, consts.ClientAuthMethodNone)
}
if assertion != nil {
methods = append(methods, fmt.Sprintf("%s (i.e. %s or %s)", consts.ClientAssertionTypeJWTBearer, consts.ClientAuthMethodPrivateKeyJWT, consts.ClientAuthMethodClientSecretJWT))
if assertion.Client != nil {
client = assertion.Client
}
}
if client == nil {
if client, err = s.Store.GetClient(ctx, id); err != nil {
return nil, "", errorsx.WithStack(ErrInvalidClient.WithWrap(err).WithDebugError(err))
}
}
switch len(methods) {
case 0:
// The 0 case means no authentication information at all exists even if the client is a public client. This
// likely only occurs on requests where the client_id is not known.
return nil, "", errorsx.WithStack(ErrInvalidRequest.WithHint("Client Authentication failed with no known authentication method."))
case 1:
// Proper authentication has occurred.
break
default:
// The default case handles the situation where a client has leveraged multiple client authentication methods
// within a request per https://datatracker.ietf.org/doc/html/rfc6749#section-2.3 clients MUST NOT use more than
// one, however some bad clients use a shotgun approach to authentication. This allows developing a personal
// policy around these bad clients on a per-client basis.
if capc, ok := client.(ClientAuthenticationPolicyClient); ok && capc.GetAllowMultipleAuthenticationMethods() {
break
}
return nil, "", errorsx.WithStack(ErrInvalidRequest.
WithHintf("Client Authentication failed with more than one known authentication method included in the request which is not permitted.").
WithDebugf("The registered client with id '%s' and the authorization server policy does not permit this malformed request. The `%s_endpoint_auth_method` methods determined to be used were '%s'.", client.GetID(), resolver.Name(), strings.Join(methods, "', '")))
}
switch {
case assertion != nil:
method, err = s.doAuthenticateAssertionJWTBearer(ctx, client, assertion, resolver)
case hasBasic, hasPost:
method, err = s.doAuthenticateClientSecret(ctx, client, secret, hasBasic, hasPost, resolver)
default:
method, err = s.doAuthenticateNone(ctx, client, resolver)
}
if err != nil {
return nil, "", err
}
return client, method, nil
}
func NewClientAssertion(ctx context.Context, store ClientManager, raw, assertionType string, resolver EndpointClientAuthHandler) (assertion *ClientAssertion, err error) {
var (
token *xjwt.Token
id, alg, method string
client Client
)
switch assertionType {
case consts.ClientAssertionTypeJWTBearer:
if len(raw) == 0 {
return &ClientAssertion{Raw: raw, Type: assertionType}, errorsx.WithStack(ErrInvalidRequest.WithHintf("The request parameter 'client_assertion' must be set when using 'client_assertion_type' of '%s'.", consts.ClientAssertionTypeJWTBearer))
}
default:
return &ClientAssertion{Raw: raw, Type: assertionType}, errorsx.WithStack(ErrInvalidRequest.WithHintf("Unknown client_assertion_type '%s'.", assertionType))
}
if token, _, err = xjwt.NewParser(xjwt.WithoutClaimsValidation()).ParseUnverified(raw, &xjwt.MapClaims{}); err != nil {
return &ClientAssertion{Raw: raw, Type: assertionType}, resolveJWTErrorToRFCError(err)
}
if id, err = token.Claims.GetSubject(); err != nil {
if id, err = token.Claims.GetIssuer(); err != nil {
return &ClientAssertion{Raw: raw, Type: assertionType}, nil
}
}
if client, err = store.GetClient(ctx, id); err != nil {
return &ClientAssertion{Raw: raw, Type: assertionType, ID: id}, nil
}
if c, ok := client.(AuthenticationMethodClient); ok {
alg, method = resolver.GetAuthSigningAlg(c), resolver.GetAuthMethod(c)
}
return &ClientAssertion{
Raw: raw,
Type: assertionType,
Parsed: true,
ID: id,
Method: method,
Algorithm: alg,
Client: client,
}, nil
}
type ClientAssertion struct {
Raw, Type string
Parsed bool
ID, Method, Algorithm string
Client Client
}
func (s *DefaultClientAuthenticationStrategy) doAuthenticateNone(ctx context.Context, client Client, handler EndpointClientAuthHandler) (method string, err error) {
if c, ok := client.(AuthenticationMethodClient); ok {
if method = handler.GetAuthMethod(c); method != consts.ClientAuthMethodNone {
return "", errorsx.WithStack(
ErrInvalidClient.
WithHintf("The request was determined to be using '%s_endpoint_auth_method' method '%s', however the OAuth 2.0 client registration does not allow this method.", handler.Name(), consts.ClientAuthMethodNone).
WithDebugf("The registered client with id '%s' is configured to only support '%s_endpoint_auth_method' method '%s'. Either the Authorization Server client registration will need to have the '%s_endpoint_auth_method' updated to '%s' or the Relying Party will need to be configured to use '%s'.", client.GetID(), handler.Name(), method, handler.Name(), consts.ClientAuthMethodNone, method))
}
}
if !client.IsPublic() {
return "", errorsx.WithStack(
ErrInvalidClient.
WithHintf("The request was determined to be using '%s_endpoint_auth_method' method '%s', however the OAuth 2.0 client registration does not allow this method.", consts.ClientAuthMethodNone, handler.Name()).
WithDebugf("The registered client with id '%s' is configured with a confidential client type but only client registrations with a public client type can use this '%s_endpoint_auth_method'.", client.GetID(), handler.Name()))
}
return consts.ClientAuthMethodNone, nil
}
func (s *DefaultClientAuthenticationStrategy) doAuthenticateClientSecret(ctx context.Context, client Client, rawSecret string, hasBasic, hasPost bool, handler EndpointClientAuthHandler) (method string, err error) {
method = consts.ClientAuthMethodClientSecretBasic
if !hasBasic && hasPost {
method = consts.ClientAuthMethodClientSecretPost
}
if c, ok := client.(AuthenticationMethodClient); ok {
switch cmethod := handler.GetAuthMethod(c); {
case cmethod == "" && handler.AllowAuthMethodAny():
break
case cmethod != method:
return "", errorsx.WithStack(
ErrInvalidClient.
WithHintf("The request was determined to be using '%s_endpoint_auth_method' method '%s', however the OAuth 2.0 client registration does not allow this method.", handler.Name(), method).
WithDebugf("The registered client with id '%s' is configured to only support '%s_endpoint_auth_method' method '%s'. Either the Authorization Server client registration will need to have the '%s_endpoint_auth_method' updated to '%s' or the Relying Party will need to be configured to use '%s'.", client.GetID(), handler.Name(), cmethod, handler.Name(), method, cmethod))
}
}
switch err = CompareClientSecret(ctx, client, []byte(rawSecret)); {
case err == nil:
return method, nil
case errors.Is(err, ErrClientSecretNotRegistered):
return "", errorsx.WithStack(
ErrInvalidClient.
WithHintf("The request was determined to be using '%s_endpoint_auth_method' method '%s', however the OAuth 2.0 client registration does not allow this method.", handler.Name(), method).
WithDebugf("The registered client with id '%s' has no 'client_secret' however this is required to process the particular request.", client.GetID()),
)
default:
return "", errorsx.WithStack(ErrInvalidClient.WithWrap(err).WithDebugError(err))
}
}
func (s *DefaultClientAuthenticationStrategy) doAuthenticateAssertionJWTBearer(ctx context.Context, client Client, assertion *ClientAssertion, resolver EndpointClientAuthHandler) (method string, err error) {
var (
token *xjwt.Token
claims *xjwt.RegisteredClaims
)
if method, _, _, token, claims, err = s.doAuthenticateAssertionParseAssertionJWTBearer(ctx, client, assertion, resolver); err != nil {
return "", err
}
if token == nil {
return "", err
}
clientID := []byte(client.GetID())
switch {
case subtle.ConstantTimeCompare([]byte(claims.Issuer), clientID) == 0:
return "", errorsx.WithStack(ErrInvalidClient.WithHint("Claim 'iss' from 'client_assertion' must match the 'client_id' of the OAuth 2.0 Client."))
case subtle.ConstantTimeCompare([]byte(claims.Subject), clientID) == 0:
return "", errorsx.WithStack(ErrInvalidClient.WithHint("Claim 'sub' from 'client_assertion' must match the 'client_id' of the OAuth 2.0 Client."))
case claims.ID == "":
return "", errorsx.WithStack(ErrInvalidClient.WithHint("Claim 'jti' from 'client_assertion' must be set but is not."))
default:
if err = s.Store.ClientAssertionJWTValid(ctx, claims.ID); err != nil {
return "", errorsx.WithStack(ErrJTIKnown.WithHint("Claim 'jti' from 'client_assertion' MUST only be used once.").WithDebugError(err))
}
if err = s.Store.SetClientAssertionJWT(ctx, claims.ID, time.Unix(claims.ExpiresAt.Unix(), 0)); err != nil {
return "", err
}
return method, nil
}
}
func (s *DefaultClientAuthenticationStrategy) doAuthenticateAssertionParseAssertionJWTBearer(ctx context.Context, client Client, assertion *ClientAssertion, resolver EndpointClientAuthHandler) (method, kid, alg string, token *xjwt.Token, claims *xjwt.RegisteredClaims, err error) {
audience := s.Config.GetAllowedJWTAssertionAudiences(ctx)
if len(audience) == 0 {
return "", "", "", nil, nil, errorsx.WithStack(ErrMisconfiguration.WithHint("The authorization server does not support OAuth 2.0 JWT Profile Client Authentication RFC7523 or OpenID Connect 1.0 specific authentication methods.").WithDebug("The authorization server could not determine any safe value for it's audience but it's required to validate the RFC7523 client assertions."))
}
opts := []xjwt.ParserOption{
xjwt.WithStrictDecoding(),
//xjwt.WithAudience(tokenURI), // Satisfies RFC7523 Section 3 Point 3.
xjwt.WithExpirationRequired(), // Satisfies RFC7523 Section 3 Point 4.
xjwt.WithIssuedAt(), // Satisfies RFC7523 Section 3 Point 6.
}
// Automatically satisfies RFC7523 Section 3 Point 5, 8, 9, and 10.
parser := xjwt.NewParser(opts...)
claims = &xjwt.RegisteredClaims{}
if token, err = parser.ParseWithClaims(assertion.Raw, claims, func(token *xjwt.Token) (key any, err error) {
if subtle.ConstantTimeCompare([]byte(client.GetID()), []byte(claims.Subject)) == 0 {
return nil, errorsx.WithStack(ErrInvalidClient.WithHint("The supplied 'client_id' did not match the 'sub' claim of the 'client_assertion'."))
}
// The following check satisfies RFC7523 Section 3 Point 2.
// See: https://datatracker.ietf.org/doc/html/rfc7523#section-3.
if claims.Subject == "" {
return nil, errorsx.WithStack(ErrInvalidClient.WithHint("The claim 'sub' from the 'client_assertion' isn't defined."))
}
var (
c AuthenticationMethodClient
ok bool
)
if c, ok = client.(AuthenticationMethodClient); !ok {
return nil, errorsx.WithStack(ErrInvalidRequest.WithHint("The registered client does not support OAuth 2.0 JWT Profile Client Authentication RFC7523 or OpenID Connect 1.0 specific authentication methods."))
}
return s.doAuthenticateAssertionParseAssertionJWTBearerFindKey(ctx, token.Header, c, resolver)
}); err != nil {
return "", "", "", nil, nil, resolveJWTErrorToRFCError(err)
}
// Satisfies RFC7523 Section 3 Point 3.
if err = s.doAuthenticateAssertionJWTBearerClaimAudience(ctx, audience, claims); err != nil {
return "", "", "", nil, nil, err
}
return method, kid, alg, token, claims, nil
}
func (s *DefaultClientAuthenticationStrategy) doAuthenticateAssertionJWTBearerClaimAudience(ctx context.Context, audience []string, claims *xjwt.RegisteredClaims) (err error) {
if len(claims.Audience) == 0 {
return errorsx.WithStack(
ErrInvalidClient.
WithHint("Unable to verify the integrity of the 'client_assertion' value. It may have been used before it was issued, may have been used before it's allowed to be used, may have been used after it's expired, or otherwise doesn't meet a particular validation constraint.").
WithDebug("Unable to validate the 'aud' claim of the 'client_assertion' as it was empty."),
)
}
validAudience := false
var aud, unverified string
verification:
for _, unverified = range claims.Audience {
for _, aud = range audience {
if subtle.ConstantTimeCompare([]byte(aud), []byte(unverified)) == 1 {
validAudience = true
break verification
}
}
}
if !validAudience {
return errorsx.WithStack(
ErrInvalidClient.
WithHint("Unable to verify the integrity of the 'client_assertion' value. It may have been used before it was issued, may have been used before it's allowed to be used, may have been used after it's expired, or otherwise doesn't meet a particular validation constraint.").
WithDebugf("Unable to validate the 'aud' claim of the 'client_assertion' value '%s' as it doesn't match any of the expected values '%s'.", strings.Join(claims.Audience, "', '"), strings.Join(audience, "', '")),
)
}
return nil
}
func (s *DefaultClientAuthenticationStrategy) doAuthenticateAssertionParseAssertionJWTBearerFindKey(ctx context.Context, header map[string]any, client AuthenticationMethodClient, handler EndpointClientAuthHandler) (key any, err error) {
var kid, alg, method string
kid, alg = getJWTHeaderKIDAlg(header)
if calg := handler.GetAuthSigningAlg(client); calg != alg && calg != "" {
return nil, errorsx.WithStack(ErrInvalidClient.WithHintf("The requested OAuth 2.0 client does not support the '%s_endpoint_auth_signing_alg' value '%s'.", handler.Name(), alg).WithDebugf("The registered OAuth 2.0 client with id '%s' only supports the '%s' algorithm.", client.GetID(), calg))
}
switch method = handler.GetAuthMethod(client); method {
case consts.ClientAuthMethodClientSecretJWT:
return s.doAuthenticateAssertionParseAssertionJWTBearerFindKeyClientSecretJWT(ctx, kid, alg, client, handler)
case consts.ClientAuthMethodPrivateKeyJWT:
return s.doAuthenticateAssertionParseAssertionJWTBearerFindKeyPrivateKeyJWT(ctx, kid, alg, client, handler)
case consts.ClientAuthMethodNone:
return nil, errorsx.WithStack(ErrInvalidClient.WithHint("This requested OAuth 2.0 client does not support client authentication, however 'client_assertion' was provided in the request."))
case consts.ClientAuthMethodClientSecretBasic, consts.ClientAuthMethodClientSecretPost:
return nil, errorsx.WithStack(ErrInvalidClient.WithHintf("This requested OAuth 2.0 client only supports client authentication method '%s', however 'client_assertion' was provided in the request.", method))
default:
return nil, errorsx.WithStack(ErrInvalidClient.WithHintf("This requested OAuth 2.0 client only supports client authentication method '%s', however that method is not supported by this server.", method))
}
}
func (s *DefaultClientAuthenticationStrategy) doAuthenticateAssertionParseAssertionJWTBearerFindKeyClientSecretJWT(_ context.Context, _, alg string, client AuthenticationMethodClient, handler EndpointClientAuthHandler) (key any, err error) {
switch alg {
case xjwt.SigningMethodHS256.Alg(), xjwt.SigningMethodHS384.Alg(), xjwt.SigningMethodRS512.Alg():
secret := client.GetClientSecret()
if secret == nil || !secret.IsPlainText() {
return nil, errorsx.WithStack(ErrInvalidClient.WithHint("The requested OAuth 2.0 client does not support the client authentication method 'client_secret_jwt' "))
}
if key, err = secret.GetPlainTextValue(); err != nil {
return nil, errorsx.WithStack(ErrInvalidClient.WithHint("The requested OAuth 2.0 client does not support the client authentication method 'client_secret_jwt' "))
}
return key, nil
default:
return nil, errorsx.WithStack(ErrInvalidClient.WithHintf("The requested OAuth 2.0 client does not support the '%s_endpoint_auth_signing_alg' value '%s'.", handler.Name(), alg))
}
}
func (s *DefaultClientAuthenticationStrategy) doAuthenticateAssertionParseAssertionJWTBearerFindKeyPrivateKeyJWT(ctx context.Context, kid, alg string, client AuthenticationMethodClient, handler EndpointClientAuthHandler) (key any, err error) {
switch alg {
case xjwt.SigningMethodRS256.Alg(), xjwt.SigningMethodRS384.Alg(), xjwt.SigningMethodRS512.Alg(),
xjwt.SigningMethodPS256.Alg(), xjwt.SigningMethodPS384.Alg(), xjwt.SigningMethodPS512.Alg(),
xjwt.SigningMethodES256.Alg(), xjwt.SigningMethodES384.Alg(), xjwt.SigningMethodES512.Alg():
if key, err = FindClientPublicJWK(ctx, s.Config, client, kid, alg, "sig"); err != nil {
return nil, err
}
return key, nil
default:
return nil, errorsx.WithStack(ErrInvalidClient.WithHintf("The requested OAuth 2.0 client does not support the '%s_endpoint_auth_signing_alg' value '%s'.", handler.Name(), alg))
}
}
func (s *DefaultClientAuthenticationStrategy) getClientCredentialsSecretPost(form url.Values) (id, secret string, ok bool) {
id, secret = form.Get(consts.FormParameterClientID), form.Get(consts.FormParameterClientSecret)
return id, secret, len(id) != 0 && len(secret) != 0
}
func resolveJWTErrorToRFCError(err error) (rfc error) {
var e *RFC6749Error
switch {
case errors.As(err, &e):
return errorsx.WithStack(e)
case errors.Is(err, xjwt.ErrTokenMalformed):
return errorsx.WithStack(ErrInvalidClient.WithHint("Unable to decode the 'client_assertion' value as it is malformed or incomplete.").WithWrap(err).WithDebugError(err))
case errors.Is(err, xjwt.ErrTokenUnverifiable):
return errorsx.WithStack(ErrInvalidClient.WithHint("Unable to decode the 'client_assertion' value as it is missing the information required to validate it.").WithWrap(err).WithDebugError(err))
case errors.Is(err, xjwt.ErrTokenNotValidYet), errors.Is(err, xjwt.ErrTokenExpired), errors.Is(err, xjwt.ErrTokenUsedBeforeIssued):
return errorsx.WithStack(ErrInvalidClient.WithHint("Unable to verify the integrity of the 'client_assertion' value. It may have been used before it was issued, may have been used before it's allowed to be used, may have been used after it's expired, or otherwise doesn't meet a particular validation constraint.").WithWrap(err).WithDebugError(err))
default:
return errorsx.WithStack(ErrInvalidClient.WithHint("Unable to decode 'client_assertion' value for an unknown reason.").WithWrap(err).WithDebugError(err))
}
}