-
Notifications
You must be signed in to change notification settings - Fork 1
/
path_config.go
470 lines (412 loc) · 15.8 KB
/
path_config.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package jwtauth
import (
"context"
"crypto"
"crypto/tls"
"crypto/x509"
"errors"
"net/http"
"strings"
"github.com/hashicorp/cap/jwt"
"github.com/hashicorp/cap/oidc"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/go-cleanhttp"
"github.com/hashicorp/go-secure-stdlib/strutil"
"github.com/openbao/openbao/sdk/v2/framework"
"github.com/openbao/openbao/sdk/v2/helper/certutil"
"github.com/openbao/openbao/sdk/v2/logical"
"golang.org/x/oauth2"
)
const (
responseTypeCode = "code" // Authorization code flow
responseTypeIDToken = "id_token" // ID Token for form post
responseModeQuery = "query" // Response as a redirect with query parameters
responseModeFormPost = "form_post" // Response as an HTML Form
)
func pathConfig(b *jwtAuthBackend) *framework.Path {
return &framework.Path{
Pattern: `config`,
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixJWT,
},
Fields: map[string]*framework.FieldSchema{
"oidc_discovery_url": {
Type: framework.TypeString,
Description: `OIDC Discovery URL, without any .well-known component (base path). Cannot be used with "jwks_url" or "jwt_validation_pubkeys".`,
},
"oidc_discovery_ca_pem": {
Type: framework.TypeString,
Description: "The CA certificate or chain of certificates, in PEM format, to use to validate connections to the OIDC Discovery URL. If not set, system certificates are used.",
},
"oidc_client_id": {
Type: framework.TypeString,
Description: "The OAuth Client ID configured with your OIDC provider.",
},
"oidc_client_secret": {
Type: framework.TypeString,
Description: "The OAuth Client Secret configured with your OIDC provider.",
DisplayAttrs: &framework.DisplayAttributes{
Sensitive: true,
},
},
"oidc_response_mode": {
Type: framework.TypeString,
Description: "The response mode to be used in the OAuth2 request. Allowed values are 'query' and 'form_post'.",
},
"oidc_response_types": {
Type: framework.TypeCommaStringSlice,
Description: "The response types to request. Allowed values are 'code' and 'id_token'. Defaults to 'code'.",
},
"jwks_url": {
Type: framework.TypeString,
Description: `JWKS URL to use to authenticate signatures. Cannot be used with "oidc_discovery_url" or "jwt_validation_pubkeys".`,
},
"jwks_ca_pem": {
Type: framework.TypeString,
Description: "The CA certificate or chain of certificates, in PEM format, to use to validate connections to the JWKS URL. If not set, system certificates are used.",
},
"default_role": {
Type: framework.TypeLowerCaseString,
Description: "The default role to use if none is provided during login. If not set, a role is required during login.",
},
"jwt_validation_pubkeys": {
Type: framework.TypeCommaStringSlice,
Description: `A list of PEM-encoded public keys to use to authenticate signatures locally. Cannot be used with "jwks_url" or "oidc_discovery_url".`,
},
"jwt_supported_algs": {
Type: framework.TypeCommaStringSlice,
Description: `A list of supported signing algorithms. Defaults to RS256.`,
},
"bound_issuer": {
Type: framework.TypeString,
Description: "The value against which to match the 'iss' claim in a JWT. Optional.",
},
"provider_config": {
Type: framework.TypeMap,
Description: "Provider-specific configuration. Optional.",
DisplayAttrs: &framework.DisplayAttributes{
Name: "Provider Config",
},
},
"namespace_in_state": {
Type: framework.TypeBool,
Description: "Pass namespace in the OIDC state parameter instead of as a separate query parameter. With this setting, the allowed redirect URL(s) in OpenBao and on the provider side should not contain a namespace query parameter. This means only one redirect URL entry needs to be maintained on the provider side for all OpenBao namespaces that will be authenticating against it. Defaults to true for new configs.",
DisplayAttrs: &framework.DisplayAttributes{
Name: "Namespace in OIDC state",
Value: true,
},
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathConfigRead,
Summary: "Read the current JWT authentication backend configuration.",
DisplayAttrs: &framework.DisplayAttributes{
OperationSuffix: "configuration",
},
},
logical.UpdateOperation: &framework.PathOperation{
Callback: b.pathConfigWrite,
Summary: "Configure the JWT authentication backend.",
Description: confHelpDesc,
DisplayAttrs: &framework.DisplayAttributes{
OperationVerb: "configure",
},
},
},
HelpSynopsis: confHelpSyn,
HelpDescription: confHelpDesc,
}
}
func (b *jwtAuthBackend) config(ctx context.Context, s logical.Storage) (*jwtConfig, error) {
b.l.Lock()
defer b.l.Unlock()
if b.cachedConfig != nil {
return b.cachedConfig, nil
}
entry, err := s.Get(ctx, configPath)
if err != nil {
return nil, err
}
if entry == nil {
return nil, nil
}
config := &jwtConfig{}
if err := entry.DecodeJSON(config); err != nil {
return nil, err
}
for _, v := range config.JWTValidationPubKeys {
key, err := certutil.ParsePublicKeyPEM([]byte(v))
if err != nil {
return nil, errwrap.Wrapf("error parsing public key: {{err}}", err)
}
config.ParsedJWTPubKeys = append(config.ParsedJWTPubKeys, key)
}
b.cachedConfig = config
return config, nil
}
func (b *jwtAuthBackend) pathConfigRead(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 nil, nil
}
provider, err := NewProviderConfig(ctx, config, ProviderMap())
if err != nil {
return nil, err
}
// Omit sensitive keys from provider-specific config
providerConfig := make(map[string]interface{})
if provider != nil {
for k, v := range config.ProviderConfig {
providerConfig[k] = v
}
for _, k := range provider.SensitiveKeys() {
delete(providerConfig, k)
}
}
resp := &logical.Response{
Data: map[string]interface{}{
"oidc_discovery_url": config.OIDCDiscoveryURL,
"oidc_discovery_ca_pem": config.OIDCDiscoveryCAPEM,
"oidc_client_id": config.OIDCClientID,
"oidc_response_mode": config.OIDCResponseMode,
"oidc_response_types": config.OIDCResponseTypes,
"default_role": config.DefaultRole,
"jwt_validation_pubkeys": config.JWTValidationPubKeys,
"jwt_supported_algs": config.JWTSupportedAlgs,
"jwks_url": config.JWKSURL,
"jwks_ca_pem": config.JWKSCAPEM,
"bound_issuer": config.BoundIssuer,
"provider_config": providerConfig,
"namespace_in_state": config.NamespaceInState,
},
}
return resp, nil
}
func (b *jwtAuthBackend) pathConfigWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
config := &jwtConfig{
OIDCDiscoveryURL: d.Get("oidc_discovery_url").(string),
OIDCDiscoveryCAPEM: d.Get("oidc_discovery_ca_pem").(string),
OIDCClientID: d.Get("oidc_client_id").(string),
OIDCClientSecret: d.Get("oidc_client_secret").(string),
OIDCResponseMode: d.Get("oidc_response_mode").(string),
OIDCResponseTypes: d.Get("oidc_response_types").([]string),
JWKSURL: d.Get("jwks_url").(string),
JWKSCAPEM: d.Get("jwks_ca_pem").(string),
DefaultRole: d.Get("default_role").(string),
JWTValidationPubKeys: d.Get("jwt_validation_pubkeys").([]string),
JWTSupportedAlgs: d.Get("jwt_supported_algs").([]string),
BoundIssuer: d.Get("bound_issuer").(string),
ProviderConfig: d.Get("provider_config").(map[string]interface{}),
}
// Check if the config already exists, to determine if this is a create or
// an update, since req.Operation is always 'update' in this handler, and
// there's no existence check defined.
existingConfig, err := b.config(ctx, req.Storage)
if err != nil {
return nil, err
}
if nsInState, ok := d.GetOk("namespace_in_state"); ok {
config.NamespaceInState = nsInState.(bool)
} else if existingConfig == nil {
// new configs default to true
config.NamespaceInState = true
} else {
// maintain the existing value
config.NamespaceInState = existingConfig.NamespaceInState
}
// Run checks on values
methodCount := 0
if config.OIDCDiscoveryURL != "" {
methodCount++
}
if len(config.JWTValidationPubKeys) != 0 {
methodCount++
}
if config.JWKSURL != "" {
methodCount++
}
switch {
case methodCount != 1:
return logical.ErrorResponse("exactly one of 'jwt_validation_pubkeys', 'jwks_url' or 'oidc_discovery_url' must be set"), nil
case config.OIDCClientID != "" && config.OIDCClientSecret == "",
config.OIDCClientID == "" && config.OIDCClientSecret != "":
return logical.ErrorResponse("both 'oidc_client_id' and 'oidc_client_secret' must be set for OIDC"), nil
case config.OIDCDiscoveryURL != "":
var err error
if config.OIDCClientID != "" && config.OIDCClientSecret != "" {
_, err = b.createProvider(config)
} else {
_, err = jwt.NewOIDCDiscoveryKeySet(ctx, config.OIDCDiscoveryURL, config.OIDCDiscoveryCAPEM)
}
if err != nil {
b.Logger().Error("error checking oidc discovery URL", "error", err)
return logical.ErrorResponse("error checking oidc discovery URL"), nil
}
case config.OIDCClientID != "" && config.OIDCDiscoveryURL == "":
return logical.ErrorResponse("'oidc_discovery_url' must be set for OIDC"), nil
case config.JWKSURL != "":
keyset, err := jwt.NewJSONWebKeySet(ctx, config.JWKSURL, config.JWKSCAPEM)
if err != nil {
b.Logger().Error("error checking jwks_ca_pem", "error", err)
return logical.ErrorResponse("error checking jwks_ca_pem"), nil
}
// Try to verify a correctly formatted JWT. The signature will fail to match, but other
// errors with fetching the remote keyset should be reported.
testJWT := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.Hf3E3iCHzqC5QIQ0nCqS1kw78IiQTRVzsLTuKoDIpdk"
_, err = keyset.VerifySignature(ctx, testJWT)
if err == nil {
err = errors.New("unexpected verification of JWT")
}
if !strings.Contains(err.Error(), "failed to verify id token signature") {
b.Logger().Error("error checking jwks URL", "error", err)
return logical.ErrorResponse("error checking jwks URL"), nil
}
case len(config.JWTValidationPubKeys) != 0:
for _, v := range config.JWTValidationPubKeys {
if _, err := certutil.ParsePublicKeyPEM([]byte(v)); err != nil {
return logical.ErrorResponse(errwrap.Wrapf("error parsing public key: {{err}}", err).Error()), nil
}
}
default:
return nil, errors.New("unknown condition")
}
// NOTE: the OIDC lib states that if nothing is passed into its config, it
// defaults to "RS256". So in the case of a zero value here it won't
// default to e.g. "none".
if err := jwt.SupportedSigningAlgorithm(toAlg(config.JWTSupportedAlgs)...); err != nil {
return logical.ErrorResponse("invalid jwt_supported_algs: %s", err), nil
}
// Validate response_types
if !strutil.StrListSubset([]string{responseTypeCode, responseTypeIDToken}, config.OIDCResponseTypes) {
return logical.ErrorResponse("invalid response_types %v. 'code' and 'id_token' are allowed", config.OIDCResponseTypes), nil
}
// Validate response_mode
switch config.OIDCResponseMode {
case "", responseModeQuery:
if config.hasType(responseTypeIDToken) {
return logical.ErrorResponse("query response_mode may not be used with an id_token response_type"), nil
}
case responseModeFormPost:
default:
return logical.ErrorResponse("invalid response_mode: %q", config.OIDCResponseMode), nil
}
// Validate provider_config
if _, err := NewProviderConfig(ctx, config, ProviderMap()); err != nil {
return logical.ErrorResponse("invalid provider_config: %s", err), nil
}
entry, err := logical.StorageEntryJSON(configPath, config)
if err != nil {
return nil, err
}
if err := req.Storage.Put(ctx, entry); err != nil {
return nil, err
}
b.reset()
return nil, nil
}
func (b *jwtAuthBackend) createProvider(config *jwtConfig) (*oidc.Provider, error) {
supportedSigAlgs := make([]oidc.Alg, len(config.JWTSupportedAlgs))
for i, a := range config.JWTSupportedAlgs {
supportedSigAlgs[i] = oidc.Alg(a)
}
if len(supportedSigAlgs) == 0 {
supportedSigAlgs = []oidc.Alg{oidc.RS256}
}
c, err := oidc.NewConfig(config.OIDCDiscoveryURL, config.OIDCClientID,
oidc.ClientSecret(config.OIDCClientSecret), supportedSigAlgs, []string{},
oidc.WithProviderCA(config.OIDCDiscoveryCAPEM))
if err != nil {
return nil, errwrap.Wrapf("error creating provider: {{err}}", err)
}
provider, err := oidc.NewProvider(c)
if err != nil {
return nil, errwrap.Wrapf("error creating provider with given values: {{err}}", err)
}
return provider, nil
}
// createCAContext returns a context with custom TLS client, configured with the root certificates
// from caPEM. If no certificates are configured, the original context is returned.
func (b *jwtAuthBackend) createCAContext(ctx context.Context, caPEM string) (context.Context, error) {
if caPEM == "" {
return ctx, nil
}
certPool := x509.NewCertPool()
if ok := certPool.AppendCertsFromPEM([]byte(caPEM)); !ok {
return nil, errors.New("could not parse CA PEM value successfully")
}
tr := cleanhttp.DefaultPooledTransport()
if certPool != nil {
tr.TLSClientConfig = &tls.Config{
RootCAs: certPool,
}
}
tc := &http.Client{
Transport: tr,
}
caCtx := context.WithValue(ctx, oauth2.HTTPClient, tc)
return caCtx, nil
}
type jwtConfig struct {
OIDCDiscoveryURL string `json:"oidc_discovery_url"`
OIDCDiscoveryCAPEM string `json:"oidc_discovery_ca_pem"`
OIDCClientID string `json:"oidc_client_id"`
OIDCClientSecret string `json:"oidc_client_secret"`
OIDCResponseMode string `json:"oidc_response_mode"`
OIDCResponseTypes []string `json:"oidc_response_types"`
JWKSURL string `json:"jwks_url"`
JWKSCAPEM string `json:"jwks_ca_pem"`
JWTValidationPubKeys []string `json:"jwt_validation_pubkeys"`
JWTSupportedAlgs []string `json:"jwt_supported_algs"`
BoundIssuer string `json:"bound_issuer"`
DefaultRole string `json:"default_role"`
ProviderConfig map[string]interface{} `json:"provider_config"`
NamespaceInState bool `json:"namespace_in_state"`
ParsedJWTPubKeys []crypto.PublicKey `json:"-"`
}
const (
StaticKeys = iota
JWKS
OIDCDiscovery
OIDCFlow
unconfigured
)
// authType classifies the authorization type/flow based on config parameters.
func (c jwtConfig) authType() int {
switch {
case len(c.ParsedJWTPubKeys) > 0:
return StaticKeys
case c.JWKSURL != "":
return JWKS
case c.OIDCDiscoveryURL != "":
if c.OIDCClientID != "" && c.OIDCClientSecret != "" {
return OIDCFlow
}
return OIDCDiscovery
}
return unconfigured
}
// hasType returns whether the list of response types includes the requested
// type. The default type is 'code' so that special case is handled as well.
func (c jwtConfig) hasType(t string) bool {
if len(c.OIDCResponseTypes) == 0 && t == responseTypeCode {
return true
}
return strutil.StrListContains(c.OIDCResponseTypes, t)
}
const (
confHelpSyn = `
Configures the JWT authentication backend.
`
confHelpDesc = `
The JWT authentication backend validates JWTs (or OIDC) using the configured
credentials. If using OIDC Discovery, the URL must be provided, along
with (optionally) the CA cert to use for the connection. If performing JWT
validation locally, a set of public keys must be provided.
`
)