-
Notifications
You must be signed in to change notification settings - Fork 61
/
path_login.go
352 lines (301 loc) · 10.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package jwtauth
import (
"context"
"errors"
"fmt"
"github.com/hashicorp/cap/jwt"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/cidrutil"
"github.com/hashicorp/vault/sdk/logical"
"golang.org/x/oauth2"
)
func pathLogin(b *jwtAuthBackend) *framework.Path {
return &framework.Path{
Pattern: `login$`,
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixJWT,
OperationVerb: "login",
},
Fields: map[string]*framework.FieldSchema{
"role": {
Type: framework.TypeLowerCaseString,
Description: "The role to log in against.",
},
"jwt": {
Type: framework.TypeString,
Description: "The signed JWT to validate.",
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.UpdateOperation: &framework.PathOperation{
Callback: b.pathLogin,
Summary: pathLoginHelpSyn,
},
logical.AliasLookaheadOperation: &framework.PathOperation{
Callback: b.pathLogin,
},
logical.ResolveRoleOperation: &framework.PathOperation{
Callback: b.pathResolveRole,
},
},
HelpSynopsis: pathLoginHelpSyn,
HelpDescription: pathLoginHelpDesc,
}
}
func (b *jwtAuthBackend) pathResolveRole(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
config, err := b.config(ctx, req.Storage)
if err != nil {
return nil, err
}
if config == nil {
return logical.ErrorResponse("could not load configuration"), nil
}
roleName, _, resp, err := b.getRoleNameAndRoleFromLoginRequest(config, ctx, req, d)
if resp != nil || err != nil {
return resp, err
}
return logical.ResolveRoleResponse(roleName)
}
func (b *jwtAuthBackend) getRoleNameAndRoleFromLoginRequest(config *jwtConfig, ctx context.Context, req *logical.Request, d *framework.FieldData) (string, *jwtRole, *logical.Response, error) {
roleName := d.Get("role").(string)
if roleName == "" {
roleName = config.DefaultRole
}
if roleName == "" {
return "", nil, logical.ErrorResponse("missing role"), nil
}
role, err := b.role(ctx, req.Storage, roleName)
if err != nil {
return "", nil, nil, err
}
if role == nil {
return "", nil, logical.ErrorResponse("role %q could not be found", roleName), nil
}
return roleName, role, nil, nil
}
func (b *jwtAuthBackend) pathLogin(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
config, err := b.config(ctx, req.Storage)
if err != nil {
return nil, err
}
if config == nil {
return logical.ErrorResponse("could not load configuration"), nil
}
roleName, role, resp, err := b.getRoleNameAndRoleFromLoginRequest(config, ctx, req, d)
if resp != nil || err != nil {
return resp, err
}
if role.RoleType == "oidc" {
return logical.ErrorResponse("role with oidc role_type is not allowed"), nil
}
token := d.Get("jwt").(string)
if len(token) == 0 {
return logical.ErrorResponse("missing token"), nil
}
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
}
}
// Get the JWT validator based on the configured auth type
validator, err := b.jwtValidator(config)
if err != nil {
return logical.ErrorResponse("error configuring token validator: %s", err.Error()), nil
}
// Validate JWT supported algorithms if they've been provided. Otherwise,
// ensure that the signing algorithm is a member of the supported set.
signingAlgorithms := toAlg(config.JWTSupportedAlgs)
if len(signingAlgorithms) == 0 {
signingAlgorithms = []jwt.Alg{
jwt.RS256, jwt.RS384, jwt.RS512, jwt.ES256, jwt.ES384,
jwt.ES512, jwt.PS256, jwt.PS384, jwt.PS512, jwt.EdDSA,
}
}
// Set expected claims values to assert on the JWT
expected := jwt.Expected{
Issuer: config.BoundIssuer,
Subject: role.BoundSubject,
Audiences: role.BoundAudiences,
SigningAlgorithms: signingAlgorithms,
NotBeforeLeeway: role.NotBeforeLeeway,
ExpirationLeeway: role.ExpirationLeeway,
ClockSkewLeeway: role.ClockSkewLeeway,
}
// Validate the JWT by verifying its signature and asserting expected claims values
allClaims, err := validator.Validate(ctx, token, expected)
if err != nil {
return logical.ErrorResponse("error validating token: %s", err.Error()), nil
}
// If there are no bound audiences for the role, then the existence of any audience
// in the audience claim should result in an error.
// "aud" value may be a single case-sensitive string if JWT has one audience
// See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3
if len(role.BoundAudiences) == 0 {
audClaim := getClaim(b.Logger(), allClaims, "aud")
switch aud := audClaim.(type) {
case []interface{}:
if len(aud) > 0 {
return logical.ErrorResponse("audience claim found in JWT but no audiences bound to the role"), nil
}
case string:
if aud != "" {
return logical.ErrorResponse("audience claim found in JWT but no audiences bound to the role"), nil
}
}
}
alias, groupAliases, err := b.createIdentity(ctx, allClaims, roleName, role, nil)
if err != nil {
return logical.ErrorResponse(err.Error()), nil
}
if err := validateBoundClaims(b.Logger(), role.BoundClaimsType, role.BoundClaims, allClaims); err != nil {
return logical.ErrorResponse("error validating claims: %s", err.Error()), nil
}
tokenMetadata := make(map[string]string)
for k, v := range alias.Metadata {
tokenMetadata[k] = v
}
auth := &logical.Auth{
DisplayName: alias.Name,
Alias: alias,
GroupAliases: groupAliases,
InternalData: map[string]interface{}{
"role": roleName,
},
Metadata: tokenMetadata,
}
role.PopulateTokenAuth(auth)
return &logical.Response{
Auth: auth,
}, nil
}
func (b *jwtAuthBackend) pathLoginRenew(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := req.Auth.InternalData["role"].(string)
if roleName == "" {
return nil, errors.New("failed to fetch role_name during renewal")
}
// Ensure that the Role still exists.
role, err := b.role(ctx, req.Storage, roleName)
if err != nil {
return nil, errwrap.Wrapf(fmt.Sprintf("failed to validate role %s during renewal: {{err}}", 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
}
// createIdentity creates an alias and set of groups aliases based on the role
// definition and received claims.
func (b *jwtAuthBackend) createIdentity(ctx context.Context, allClaims map[string]interface{}, roleName string, role *jwtRole, tokenSource oauth2.TokenSource) (*logical.Alias, []*logical.Alias, error) {
var userClaimRaw interface{}
if role.UserClaimJSONPointer {
userClaimRaw = getClaim(b.Logger(), allClaims, role.UserClaim)
} else {
userClaimRaw = allClaims[role.UserClaim]
}
if userClaimRaw == nil {
return nil, nil, fmt.Errorf("claim %q not found in token", role.UserClaim)
}
userName, ok := userClaimRaw.(string)
if !ok {
return nil, nil, fmt.Errorf("claim %q could not be converted to string", role.UserClaim)
}
pConfig, err := NewProviderConfig(ctx, b.cachedConfig, ProviderMap())
if err != nil {
return nil, nil, fmt.Errorf("failed to load custom provider config: %s", err)
}
if err := b.fetchUserInfo(ctx, pConfig, allClaims, role); err != nil {
return nil, nil, err
}
metadata, err := extractMetadata(b.Logger(), allClaims, role.ClaimMappings)
if err != nil {
return nil, nil, err
}
// add role name to the Entity Alias metadata
metadata["role"] = roleName
alias := &logical.Alias{
Name: userName,
Metadata: metadata,
}
var groupAliases []*logical.Alias
if role.GroupsClaim == "" {
return alias, groupAliases, nil
}
groupsClaimRaw, err := b.fetchGroups(ctx, pConfig, allClaims, role, tokenSource)
if err != nil {
return nil, nil, fmt.Errorf("failed to fetch groups: %s", err)
}
groups, ok := normalizeList(groupsClaimRaw)
if !ok {
return nil, nil, fmt.Errorf("%q claim could not be converted to string list", role.GroupsClaim)
}
for _, groupRaw := range groups {
group, ok := groupRaw.(string)
if !ok {
return nil, nil, fmt.Errorf("value %v in groups claim could not be parsed as string", groupRaw)
}
if group == "" {
continue
}
groupAliases = append(groupAliases, &logical.Alias{
Name: group,
})
}
return alias, groupAliases, nil
}
// Checks if there's a custom provider_config and calls FetchUserInfo() if implemented.
func (b *jwtAuthBackend) fetchUserInfo(ctx context.Context, pConfig CustomProvider, allClaims map[string]interface{}, role *jwtRole) error {
// Fetch user info from custom provider if it's implemented
if pConfig != nil {
if uif, ok := pConfig.(UserInfoFetcher); ok {
return uif.FetchUserInfo(ctx, b, allClaims, role)
}
}
return nil
}
// Checks if there's a custom provider_config and calls FetchGroups() if implemented
func (b *jwtAuthBackend) fetchGroups(ctx context.Context, pConfig CustomProvider, allClaims map[string]interface{}, role *jwtRole, tokenSource oauth2.TokenSource) (interface{}, error) {
// If the custom provider implements interface GroupsFetcher, call it,
// otherwise fall through to the default method
if pConfig != nil {
if gf, ok := pConfig.(GroupsFetcher); ok {
groupsRaw, err := gf.FetchGroups(ctx, b, allClaims, role, tokenSource)
if err != nil {
return nil, err
}
// Add groups obtained by provider-specific fetching to the claims
// so that they can be used for bound_claims validation on the role.
setClaim(b.Logger(), allClaims, role.GroupsClaim, groupsRaw)
}
}
groupsClaimRaw := getClaim(b.Logger(), allClaims, role.GroupsClaim)
if groupsClaimRaw == nil {
return nil, fmt.Errorf("%q claim not found in token", role.GroupsClaim)
}
return groupsClaimRaw, nil
}
func toAlg(a []string) []jwt.Alg {
alg := make([]jwt.Alg, len(a))
for i, e := range a {
alg[i] = jwt.Alg(e)
}
return alg
}
const (
pathLoginHelpSyn = `
Authenticates to Vault using a JWT (or OIDC) token.
`
pathLoginHelpDesc = `
Authenticates JWTs.
`
)