/
path_login.go
541 lines (467 loc) · 15.4 KB
/
path_login.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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package kubeauth
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
capjwt "github.com/hashicorp/cap/jwt"
"github.com/hashicorp/go-secure-stdlib/strutil"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/cidrutil"
"github.com/hashicorp/vault/sdk/logical"
"github.com/mitchellh/mapstructure"
"gopkg.in/go-jose/go-jose.v2"
josejwt "gopkg.in/go-jose/go-jose.v2/jwt"
)
const (
metadataKeySAUID = "service_account_uid"
metadataKeySAName = "service_account_name"
metadataKeySANamespace = "service_account_namespace"
metadataKeySASecretName = "service_account_secret_name"
)
var reservedAliasMetadataKeys = map[string]struct{}{
metadataKeySAUID: {},
metadataKeySAName: {},
metadataKeySANamespace: {},
metadataKeySASecretName: {},
}
// defaultJWTIssuer is used to verify the iss header on the JWT if the config doesn't specify an issuer.
var defaultJWTIssuer = "kubernetes/serviceaccount"
// See https://datatracker.ietf.org/doc/html/rfc7518#section-3.
var supportedJwtAlgs = []capjwt.Alg{
capjwt.RS256, capjwt.RS384, capjwt.RS512,
capjwt.ES256, capjwt.ES384, capjwt.ES512,
}
// pathLogin returns the path configurations for login endpoints
func pathLogin(b *kubeAuthBackend) *framework.Path {
return &framework.Path{
Pattern: "login$",
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixKubernetes,
OperationVerb: "login",
},
Fields: map[string]*framework.FieldSchema{
"role": {
Type: framework.TypeString,
Description: `Name of the role against which the login is being attempted. This field is required`,
},
"jwt": {
Type: framework.TypeString,
Description: `A signed JWT for authenticating a service account. This field is required.`,
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathLogin,
logical.AliasLookaheadOperation: b.aliasLookahead,
logical.ResolveRoleOperation: b.pathResolveRole,
},
HelpSynopsis: pathLoginHelpSyn,
HelpDescription: pathLoginHelpDesc,
}
}
// pathLogin is used to resolve the role to be used from a login request
func (b *kubeAuthBackend) pathResolveRole(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName, resp := b.getFieldValueStr(data, "role")
if resp != nil {
return resp, nil
}
b.l.RLock()
defer b.l.RUnlock()
role, err := b.role(ctx, req.Storage, roleName)
if err != nil {
return nil, err
}
if role == nil {
return logical.ErrorResponse(fmt.Sprintf("invalid role name %q", roleName)), nil
}
return logical.ResolveRoleResponse(roleName)
}
// pathLogin is used to authenticate to this backend
func (b *kubeAuthBackend) pathLogin(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName, resp := b.getFieldValueStr(data, "role")
if resp != nil {
return resp, nil
}
jwtStr, resp := b.getFieldValueStr(data, "jwt")
if resp != nil {
return resp, nil
}
b.l.RLock()
defer b.l.RUnlock()
role, err := b.role(ctx, req.Storage, roleName)
if err != nil {
return nil, err
}
if role == nil {
return logical.ErrorResponse(fmt.Sprintf("invalid role name %q", roleName)), nil
}
// Check for a CIDR match.
if len(role.TokenBoundCIDRs) > 0 {
if req.Connection == nil {
b.Logger().Warn("token bound CIDRs found but no connection information available for validation")
return nil, logical.ErrPermissionDenied
}
if !cidrutil.RemoteAddrIsOk(req.Connection.RemoteAddr, role.TokenBoundCIDRs) {
return nil, logical.ErrPermissionDenied
}
}
config, err := b.loadConfig(ctx, req.Storage)
if err != nil {
return nil, err
}
if config == nil {
return nil, errors.New("could not load backend configuration")
}
client, err := b.getHTTPClient()
if err != nil {
b.Logger().Error("Failed to get the HTTP client", "err", err)
return nil, logical.ErrUnrecoverable
}
sa, err := b.parseAndValidateJWT(ctx, client, jwtStr, role, config)
if err != nil {
if err == jose.ErrCryptoFailure || strings.Contains(err.Error(), "verifying token signature") {
b.Logger().Debug(`login unauthorized`, "err", err)
return nil, logical.ErrPermissionDenied
}
return nil, err
}
aliasName, err := b.getAliasName(role, sa)
if err != nil {
return nil, err
}
// look up the JWT token in the kubernetes API
err = sa.lookup(ctx, client, jwtStr, role.Audience, b.reviewFactory(config))
if err != nil {
b.Logger().Debug(`login unauthorized`, "err", err)
return nil, logical.ErrPermissionDenied
}
annotations := map[string]string{}
if config.UseAnnotationsAsAliasMetadata {
annotations, err = b.serviceAccountGetterFactory(config).annotations(ctx, client, jwtStr, sa.namespace(), sa.name())
if err != nil {
if errors.Is(err, errAliasMetadataReservedKeysFound) {
return logical.ErrorResponse(err.Error()), nil
}
return nil, err
}
}
uid, err := sa.uid()
if err != nil {
return nil, err
}
metadata := annotations
metadata[metadataKeySAUID] = uid
metadata[metadataKeySAName] = sa.name()
metadata[metadataKeySANamespace] = sa.namespace()
metadata[metadataKeySASecretName] = sa.SecretName
auth := &logical.Auth{
Alias: &logical.Alias{
Name: aliasName,
Metadata: metadata,
},
InternalData: map[string]interface{}{
"role": roleName,
},
Metadata: map[string]string{
metadataKeySAUID: uid,
metadataKeySAName: sa.name(),
metadataKeySANamespace: sa.namespace(),
metadataKeySASecretName: sa.SecretName,
"role": roleName,
},
DisplayName: fmt.Sprintf("%s-%s", sa.namespace(), sa.name()),
}
role.PopulateTokenAuth(auth)
return &logical.Response{
Auth: auth,
}, nil
}
func (b *kubeAuthBackend) getFieldValueStr(data *framework.FieldData, param string) (string, *logical.Response) {
val := data.Get(param).(string)
if len(val) == 0 {
return "", logical.ErrorResponse("missing %s", param)
}
return val, nil
}
func (b *kubeAuthBackend) getAliasName(role *roleStorageEntry, serviceAccount *serviceAccount) (string, error) {
switch role.AliasNameSource {
case aliasNameSourceSAUid, aliasNameSourceUnset:
uid, err := serviceAccount.uid()
if err != nil {
return "", err
}
return uid, nil
case aliasNameSourceSAName:
ns, name := serviceAccount.namespace(), serviceAccount.name()
if ns == "" || name == "" {
return "", fmt.Errorf("service account namespace and name must be set")
}
return fmt.Sprintf("%s/%s", ns, name), nil
default:
return "", fmt.Errorf("unknown alias_name_source %q", role.AliasNameSource)
}
}
// aliasLookahead returns the alias object with the SA UID from the JWT
// Claims.
// Only JWTs matching the specified role's configuration will be accepted as valid.
func (b *kubeAuthBackend) aliasLookahead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName, resp := b.getFieldValueStr(data, "role")
if resp != nil {
return resp, nil
}
jwtStr, resp := b.getFieldValueStr(data, "jwt")
if resp != nil {
return resp, nil
}
b.l.RLock()
defer b.l.RUnlock()
role, err := b.role(ctx, req.Storage, roleName)
if err != nil {
return nil, err
}
if role == nil {
return logical.ErrorResponse(fmt.Sprintf("invalid role name %q", roleName)), nil
}
config, err := b.loadConfig(ctx, req.Storage)
if err != nil {
return nil, err
}
if config == nil {
return nil, errors.New("could not load backend configuration")
}
// validation of the JWT against the provided role ensures alias look ahead requests
// are authentic.
client, err := b.getHTTPClient()
if err != nil {
b.Logger().Error("Failed to get the HTTP client", "err", err)
return nil, logical.ErrUnrecoverable
}
sa, err := b.parseAndValidateJWT(ctx, client, jwtStr, role, config)
if err != nil {
return nil, err
}
aliasName, err := b.getAliasName(role, sa)
if err != nil {
return nil, err
}
return &logical.Response{
Auth: &logical.Auth{
Alias: &logical.Alias{
Name: aliasName,
},
},
}, nil
}
type DontVerifySignature struct{}
func (keySet DontVerifySignature) VerifySignature(_ context.Context, token string) (map[string]interface{}, error) {
parsed, err := josejwt.ParseSigned(token)
if err != nil {
return nil, err
}
claims := map[string]interface{}{}
err = parsed.UnsafeClaimsWithoutVerification(&claims)
if err != nil {
return nil, err
}
return claims, nil
}
// parseAndValidateJWT is used to parse, validate and lookup the JWT token.
func (b *kubeAuthBackend) parseAndValidateJWT(ctx context.Context, client *http.Client, jwtStr string,
role *roleStorageEntry, config *kubeConfig,
) (*serviceAccount, error) {
expected := capjwt.Expected{
SigningAlgorithms: supportedJwtAlgs,
}
// perform ISS Claim validation if configured
if !config.DisableISSValidation {
// set the expected issuer to the default kubernetes issuer if the config doesn't specify it
if config.Issuer != "" {
expected.Issuer = config.Issuer
} else {
config.Issuer = defaultJWTIssuer
}
}
// validate the audience if the role expects it
if role.Audience != "" {
expected.Audiences = []string{role.Audience}
}
// Parse into JWT
var err error
var keySet capjwt.KeySet
if len(config.PublicKeys) == 0 {
// we don't verify the signature if we aren't configured with public keys
keySet = DontVerifySignature{}
} else {
keySet, err = capjwt.NewStaticKeySet(config.PublicKeys)
if err != nil {
return nil, err
}
}
validator, err := capjwt.NewValidator(keySet)
if err != nil {
return nil, err
}
claims, err := validator.ValidateAllowMissingIatNbfExp(nil, jwtStr, expected)
if err != nil {
return nil, logical.CodedError(http.StatusForbidden, err.Error())
}
sa := &serviceAccount{}
// Decode claims into a service account object
err = mapstructure.Decode(claims, sa)
if err != nil {
return nil, err
}
// verify the service account name is allowed
if len(role.ServiceAccountNames) > 1 || role.ServiceAccountNames[0] != "*" {
if !strutil.StrListContainsGlob(role.ServiceAccountNames, sa.name()) {
return nil, logical.CodedError(http.StatusForbidden,
fmt.Sprintf("service account name not authorized"))
}
}
// verify the namespace is allowed
var allowed bool
if len(role.ServiceAccountNamespaces) > 0 {
if role.ServiceAccountNamespaces[0] == "*" || strutil.StrListContainsGlob(role.ServiceAccountNamespaces, sa.namespace()) {
allowed = true
}
}
// verify the namespace selector matches the namespace
if !allowed && role.ServiceAccountNamespaceSelector != "" {
allowed, err = b.namespaceValidatorFactory(config).validateLabels(ctx,
client, sa.namespace(), role.ServiceAccountNamespaceSelector)
}
if !allowed {
errMsg := "namespace not authorized"
if err != nil {
errMsg = fmt.Sprintf("%s err=%s", errMsg, err)
}
codedErr := logical.CodedError(http.StatusForbidden, errMsg)
return nil, codedErr
}
// If we don't have any public keys to verify, return the sa and end early.
if len(config.PublicKeys) == 0 {
return sa, nil
}
return sa, nil
}
// serviceAccount holds the metadata from the JWT token and is used to lookup
// the JWT in the kubernetes API and compare the results.
type serviceAccount struct {
Name string `mapstructure:"kubernetes.io/serviceaccount/service-account.name"`
UID string `mapstructure:"kubernetes.io/serviceaccount/service-account.uid"`
SecretName string `mapstructure:"kubernetes.io/serviceaccount/secret.name"`
Namespace string `mapstructure:"kubernetes.io/serviceaccount/namespace"`
Audience []string `mapstructure:"aud"`
// the JSON returned from reviewing a Projected Service account has a
// different structure, where the information is in a sub-structure instead of
// at the top level
Kubernetes *projectedServiceToken `mapstructure:"kubernetes.io"`
Expiration int64 `mapstructure:"exp"`
IssuedAt int64 `mapstructure:"iat"`
}
// uid returns the UID for the service account, preferring the projected service
// account value if found
// return an error when the UID is empty.
func (s *serviceAccount) uid() (string, error) {
uid := s.UID
if s.Kubernetes != nil && s.Kubernetes.ServiceAccount != nil {
uid = s.Kubernetes.ServiceAccount.UID
}
if uid == "" {
return "", errors.New("could not parse UID from claims")
}
return uid, nil
}
// name returns the name for the service account, preferring the projected
// service account value if found. This is "default" for projected service
// accounts
func (s *serviceAccount) name() string {
if s.Kubernetes != nil && s.Kubernetes.ServiceAccount != nil {
return s.Kubernetes.ServiceAccount.Name
}
return s.Name
}
// namespace returns the namespace for the service account, preferring the
// projected service account value if found
func (s *serviceAccount) namespace() string {
if s.Kubernetes != nil {
return s.Kubernetes.Namespace
}
return s.Namespace
}
type projectedServiceToken struct {
Namespace string `mapstructure:"namespace"`
Pod *k8sObjectRef `mapstructure:"pod"`
ServiceAccount *k8sObjectRef `mapstructure:"serviceaccount"`
}
type k8sObjectRef struct {
Name string `mapstructure:"name"`
UID string `mapstructure:"uid"`
}
// lookup calls the TokenReview API in kubernetes to verify the token and secret
// still exist.
func (s *serviceAccount) lookup(ctx context.Context, client *http.Client, jwtStr string, aud string, tr tokenReviewer) error {
// This is somewhat redundant, as we are asking k8s if the token's audiences
// overlap with wantAud, but setting wantAud to the token's own audiences by
// default. In the case that `audience` was set on the Vault role, we have
// already validated that it matches one of the token's audiences by this
// point, so we are essentially asking k8s to either ignore audience
// validation or check our homework.
wantAud := s.Audience
if aud != "" {
wantAud = []string{aud}
}
r, err := tr.Review(ctx, client, jwtStr, wantAud)
if err != nil {
return err
}
// Verify the returned metadata matches the expected data from the service
// account.
if s.name() != r.Name {
return errors.New("JWT names did not match")
}
uid, err := s.uid()
if err != nil {
return err
}
if uid != r.UID {
return errors.New("JWT UIDs did not match")
}
if s.namespace() != r.Namespace {
return errors.New("JWT namepaces did not match")
}
return nil
}
// Invoked when the token issued by this backend is attempting a renewal.
func (b *kubeAuthBackend) pathLoginRenew() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := req.Auth.InternalData["role"].(string)
if roleName == "" {
return nil, fmt.Errorf("failed to fetch role_name during renewal")
}
b.l.RLock()
defer b.l.RUnlock()
// Ensure that the Role still exists.
role, err := b.role(ctx, req.Storage, roleName)
if err != nil {
return nil, fmt.Errorf("failed to validate role %s during renewal:%s", roleName, err)
}
if role == nil {
return nil, fmt.Errorf("role %s does not exist during renewal", roleName)
}
resp := &logical.Response{Auth: req.Auth}
resp.Auth.TTL = role.TokenTTL
resp.Auth.MaxTTL = role.TokenMaxTTL
resp.Auth.Period = role.TokenPeriod
return resp, nil
}
}
const (
pathLoginHelpSyn = `Authenticates Kubernetes service accounts with Vault.`
pathLoginHelpDesc = `
Authenticate Kubernetes service accounts.
`
)