forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
585 lines (495 loc) · 15.8 KB
/
auth.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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
package vault
import (
"errors"
"fmt"
"strings"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/vault/helper/consts"
"github.com/hashicorp/vault/helper/jsonutil"
"github.com/hashicorp/vault/logical"
)
const (
// coreAuthConfigPath is used to store the auth configuration.
// Auth configuration is protected within the Vault itself, which means it
// can only be viewed or modified after an unseal.
coreAuthConfigPath = "core/auth"
// coreLocalAuthConfigPath is used to store credential configuration for
// local (non-replicated) mounts
coreLocalAuthConfigPath = "core/local-auth"
// credentialBarrierPrefix is the prefix to the UUID used in the
// barrier view for the credential backends.
credentialBarrierPrefix = "auth/"
// credentialRoutePrefix is the mount prefix used for the router
credentialRoutePrefix = "auth/"
// credentialTableType is the value we expect to find for the credential
// table and corresponding entries
credentialTableType = "auth"
)
var (
// errLoadAuthFailed if loadCredentials encounters an error
errLoadAuthFailed = errors.New("failed to setup auth table")
// credentialAliases maps old backend names to new backend names, allowing us
// to move/rename backends but maintain backwards compatibility
credentialAliases = map[string]string{"aws-ec2": "aws"}
)
// enableCredential is used to enable a new credential backend
func (c *Core) enableCredential(entry *MountEntry) error {
// Ensure we end the path in a slash
if !strings.HasSuffix(entry.Path, "/") {
entry.Path += "/"
}
// Ensure there is a name
if entry.Path == "/" {
return fmt.Errorf("backend path must be specified")
}
c.authLock.Lock()
defer c.authLock.Unlock()
// Look for matching name
for _, ent := range c.auth.Entries {
switch {
// Existing is oauth/github/ new is oauth/ or
// existing is oauth/ and new is oauth/github/
case strings.HasPrefix(ent.Path, entry.Path):
fallthrough
case strings.HasPrefix(entry.Path, ent.Path):
return logical.CodedError(409, "path is already in use")
}
}
// Ensure the token backend is a singleton
if entry.Type == "token" {
return fmt.Errorf("token credential backend cannot be instantiated")
}
if conflict := c.router.MountConflict(credentialRoutePrefix + entry.Path); conflict != "" {
return logical.CodedError(409, fmt.Sprintf("existing mount at %s", conflict))
}
// Generate a new UUID and view
if entry.UUID == "" {
entryUUID, err := uuid.GenerateUUID()
if err != nil {
return err
}
entry.UUID = entryUUID
}
if entry.Accessor == "" {
accessor, err := c.generateMountAccessor("auth_" + entry.Type)
if err != nil {
return err
}
entry.Accessor = accessor
}
viewPath := credentialBarrierPrefix + entry.UUID + "/"
view := NewBarrierView(c.barrier, viewPath)
var err error
var backend logical.Backend
sysView := c.mountEntrySysView(entry)
conf := make(map[string]string)
if entry.Config.PluginName != "" {
conf["plugin_name"] = entry.Config.PluginName
}
// Create the new backend
backend, err = c.newCredentialBackend(entry.Type, sysView, view, conf)
if err != nil {
return err
}
if backend == nil {
return fmt.Errorf("nil backend returned from %q factory", entry.Type)
}
// Check for the correct backend type
backendType := backend.Type()
if entry.Type == "plugin" && backendType != logical.TypeCredential {
return fmt.Errorf("cannot mount '%s' of type '%s' as an auth backend", entry.Config.PluginName, backendType)
}
if err := backend.Initialize(); err != nil {
return err
}
// Update the auth table
newTable := c.auth.shallowClone()
newTable.Entries = append(newTable.Entries, entry)
if err := c.persistAuth(newTable, entry.Local); err != nil {
return errors.New("failed to update auth table")
}
c.auth = newTable
path := credentialRoutePrefix + entry.Path
if err := c.router.Mount(backend, path, entry, view); err != nil {
return err
}
if c.logger.IsInfo() {
c.logger.Info("core: enabled credential backend", "path", entry.Path, "type", entry.Type)
}
return nil
}
// disableCredential is used to disable an existing credential backend; the
// boolean indicates if it existed
func (c *Core) disableCredential(path string) error {
// Ensure we end the path in a slash
if !strings.HasSuffix(path, "/") {
path += "/"
}
// Ensure the token backend is not affected
if path == "token/" {
return fmt.Errorf("token credential backend cannot be disabled")
}
// Store the view for this backend
fullPath := credentialRoutePrefix + path
view := c.router.MatchingStorageByAPIPath(fullPath)
if view == nil {
return fmt.Errorf("no matching backend %s", fullPath)
}
// Get the backend/mount entry for this path, used to remove ignored
// replication prefixes
backend := c.router.MatchingBackend(fullPath)
entry := c.router.MatchingMountEntry(fullPath)
// Mark the entry as tainted
if err := c.taintCredEntry(path); err != nil {
return err
}
// Taint the router path to prevent routing
if err := c.router.Taint(fullPath); err != nil {
return err
}
if backend != nil {
// Revoke credentials from this path
if err := c.expiration.RevokePrefix(fullPath); err != nil {
return err
}
// Call cleanup function if it exists
backend.Cleanup()
}
// Unmount the backend
if err := c.router.Unmount(fullPath); err != nil {
return err
}
switch {
case entry.Local, !c.replicationState.HasState(consts.ReplicationPerformanceSecondary):
// Have writable storage, remove the whole thing
if err := logical.ClearView(view); err != nil {
c.logger.Error("core: failed to clear view for path being unmounted", "error", err, "path", path)
return err
}
}
// Remove the mount table entry
if err := c.removeCredEntry(path); err != nil {
return err
}
if c.logger.IsInfo() {
c.logger.Info("core: disabled credential backend", "path", path)
}
return nil
}
// removeCredEntry is used to remove an entry in the auth table
func (c *Core) removeCredEntry(path string) error {
c.authLock.Lock()
defer c.authLock.Unlock()
// Taint the entry from the auth table
newTable := c.auth.shallowClone()
entry := newTable.remove(path)
if entry == nil {
c.logger.Error("core: nil entry found removing entry in auth table", "path", path)
return logical.CodedError(500, "failed to remove entry in auth table")
}
// Update the auth table
if err := c.persistAuth(newTable, entry.Local); err != nil {
return errors.New("failed to update auth table")
}
c.auth = newTable
return nil
}
// remountCredEntryForce takes a copy of the mount entry for the path and fully
// unmounts and remounts the backend to pick up any changes, such as filtered
// paths
func (c *Core) remountCredEntryForce(path string) error {
fullPath := credentialRoutePrefix + path
me := c.router.MatchingMountEntry(fullPath)
if me == nil {
return fmt.Errorf("cannot find mount for path '%s'", path)
}
me, err := me.Clone()
if err != nil {
return err
}
if err := c.disableCredential(path); err != nil {
return err
}
return c.enableCredential(me)
}
// taintCredEntry is used to mark an entry in the auth table as tainted
func (c *Core) taintCredEntry(path string) error {
c.authLock.Lock()
defer c.authLock.Unlock()
// Taint the entry from the auth table
// We do this on the original since setting the taint operates
// on the entries which a shallow clone shares anyways
entry := c.auth.setTaint(path, true)
// Ensure there was a match
if entry == nil {
return fmt.Errorf("no matching backend")
}
// Update the auth table
if err := c.persistAuth(c.auth, entry.Local); err != nil {
return errors.New("failed to update auth table")
}
return nil
}
// loadCredentials is invoked as part of postUnseal to load the auth table
func (c *Core) loadCredentials() error {
authTable := &MountTable{}
localAuthTable := &MountTable{}
// Load the existing mount table
raw, err := c.barrier.Get(coreAuthConfigPath)
if err != nil {
c.logger.Error("core: failed to read auth table", "error", err)
return errLoadAuthFailed
}
rawLocal, err := c.barrier.Get(coreLocalAuthConfigPath)
if err != nil {
c.logger.Error("core: failed to read local auth table", "error", err)
return errLoadAuthFailed
}
c.authLock.Lock()
defer c.authLock.Unlock()
if raw != nil {
if err := jsonutil.DecodeJSON(raw.Value, authTable); err != nil {
c.logger.Error("core: failed to decode auth table", "error", err)
return errLoadAuthFailed
}
c.auth = authTable
}
var needPersist bool
if c.auth == nil {
c.auth = c.defaultAuthTable()
needPersist = true
}
if rawLocal != nil {
if err := jsonutil.DecodeJSON(rawLocal.Value, localAuthTable); err != nil {
c.logger.Error("core: failed to decode local auth table", "error", err)
return errLoadAuthFailed
}
if localAuthTable != nil && len(localAuthTable.Entries) > 0 {
c.auth.Entries = append(c.auth.Entries, localAuthTable.Entries...)
}
}
// Upgrade to typed auth table
if c.auth.Type == "" {
c.auth.Type = credentialTableType
needPersist = true
}
// Upgrade to table-scoped entries
for _, entry := range c.auth.Entries {
if entry.Table == "" {
entry.Table = c.auth.Type
needPersist = true
}
if entry.Accessor == "" {
accessor, err := c.generateMountAccessor("auth_" + entry.Type)
if err != nil {
return err
}
entry.Accessor = accessor
needPersist = true
}
}
if !needPersist {
return nil
}
if err := c.persistAuth(c.auth, false); err != nil {
c.logger.Error("core: failed to persist auth table", "error", err)
return errLoadAuthFailed
}
return nil
}
// persistAuth is used to persist the auth table after modification
func (c *Core) persistAuth(table *MountTable, localOnly bool) error {
if table.Type != credentialTableType {
c.logger.Error("core: given table to persist has wrong type", "actual_type", table.Type, "expected_type", credentialTableType)
return fmt.Errorf("invalid table type given, not persisting")
}
for _, entry := range table.Entries {
if entry.Table != table.Type {
c.logger.Error("core: given entry to persist in auth table has wrong table value", "path", entry.Path, "entry_table_type", entry.Table, "actual_type", table.Type)
return fmt.Errorf("invalid auth entry found, not persisting")
}
}
nonLocalAuth := &MountTable{
Type: credentialTableType,
}
localAuth := &MountTable{
Type: credentialTableType,
}
for _, entry := range table.Entries {
if entry.Local {
localAuth.Entries = append(localAuth.Entries, entry)
} else {
nonLocalAuth.Entries = append(nonLocalAuth.Entries, entry)
}
}
if !localOnly {
// Marshal the table
compressedBytes, err := jsonutil.EncodeJSONAndCompress(nonLocalAuth, nil)
if err != nil {
c.logger.Error("core: failed to encode and/or compress auth table", "error", err)
return err
}
// Create an entry
entry := &Entry{
Key: coreAuthConfigPath,
Value: compressedBytes,
}
// Write to the physical backend
if err := c.barrier.Put(entry); err != nil {
c.logger.Error("core: failed to persist auth table", "error", err)
return err
}
}
// Repeat with local auth
compressedBytes, err := jsonutil.EncodeJSONAndCompress(localAuth, nil)
if err != nil {
c.logger.Error("core: failed to encode and/or compress local auth table", "error", err)
return err
}
entry := &Entry{
Key: coreLocalAuthConfigPath,
Value: compressedBytes,
}
if err := c.barrier.Put(entry); err != nil {
c.logger.Error("core: failed to persist local auth table", "error", err)
return err
}
return nil
}
// setupCredentials is invoked after we've loaded the auth table to
// initialize the credential backends and setup the router
func (c *Core) setupCredentials() error {
var err error
var persistNeeded bool
var view *BarrierView
var backendType logical.BackendType
c.authLock.Lock()
defer c.authLock.Unlock()
for _, entry := range c.auth.Entries {
var backend logical.Backend
// Work around some problematic code that existed in master for a while
if strings.HasPrefix(entry.Path, credentialRoutePrefix) {
entry.Path = strings.TrimPrefix(entry.Path, credentialRoutePrefix)
persistNeeded = true
}
// Create a barrier view using the UUID
viewPath := credentialBarrierPrefix + entry.UUID + "/"
view = NewBarrierView(c.barrier, viewPath)
// Initialize the backend
sysView := c.mountEntrySysView(entry)
conf := make(map[string]string)
if entry.Config.PluginName != "" {
conf["plugin_name"] = entry.Config.PluginName
}
backend, err = c.newCredentialBackend(entry.Type, sysView, view, conf)
if err != nil {
c.logger.Error("core: failed to create credential entry", "path", entry.Path, "error", err)
if entry.Type == "plugin" {
// If we encounter an error instantiating the backend due to an error,
// skip backend initialization but register the entry to the mount table
// to preserve storage and path.
c.logger.Warn("core: skipping plugin-based credential entry", "path", entry.Path)
goto ROUTER_MOUNT
}
return errLoadAuthFailed
}
if backend == nil {
return fmt.Errorf("nil backend returned from %q factory", entry.Type)
}
// Check for the correct backend type
backendType = backend.Type()
if entry.Type == "plugin" && backendType != logical.TypeCredential {
return fmt.Errorf("cannot mount '%s' of type '%s' as an auth backend", entry.Config.PluginName, backendType)
}
if err := backend.Initialize(); err != nil {
return err
}
ROUTER_MOUNT:
// Mount the backend
path := credentialRoutePrefix + entry.Path
err = c.router.Mount(backend, path, entry, view)
if err != nil {
c.logger.Error("core: failed to mount auth entry", "path", entry.Path, "error", err)
return errLoadAuthFailed
}
// Ensure the path is tainted if set in the mount table
if entry.Tainted {
c.router.Taint(path)
}
// Check if this is the token store
if entry.Type == "token" {
c.tokenStore = backend.(*TokenStore)
// this is loaded *after* the normal mounts, including cubbyhole
c.router.tokenStoreSaltFunc = c.tokenStore.Salt
c.tokenStore.cubbyholeBackend = c.router.MatchingBackend("cubbyhole/").(*CubbyholeBackend)
}
}
if persistNeeded {
return c.persistAuth(c.auth, false)
}
return nil
}
// teardownCredentials is used before we seal the vault to reset the credential
// backends to their unloaded state. This is reversed by loadCredentials.
func (c *Core) teardownCredentials() error {
c.authLock.Lock()
defer c.authLock.Unlock()
if c.auth != nil {
authTable := c.auth.shallowClone()
for _, e := range authTable.Entries {
backend := c.router.MatchingBackend(credentialRoutePrefix + e.Path)
if backend != nil {
backend.Cleanup()
}
}
}
c.auth = nil
c.tokenStore = nil
return nil
}
// newCredentialBackend is used to create and configure a new credential backend by name
func (c *Core) newCredentialBackend(
t string, sysView logical.SystemView, view logical.Storage, conf map[string]string) (logical.Backend, error) {
if alias, ok := credentialAliases[t]; ok {
t = alias
}
f, ok := c.credentialBackends[t]
if !ok {
return nil, fmt.Errorf("unknown backend type: %s", t)
}
config := &logical.BackendConfig{
StorageView: view,
Logger: c.logger,
Config: conf,
System: sysView,
}
b, err := f(config)
if err != nil {
return nil, err
}
return b, nil
}
// defaultAuthTable creates a default auth table
func (c *Core) defaultAuthTable() *MountTable {
table := &MountTable{
Type: credentialTableType,
}
tokenUUID, err := uuid.GenerateUUID()
if err != nil {
panic(fmt.Sprintf("could not generate UUID for default auth table token entry: %v", err))
}
tokenAccessor, err := c.generateMountAccessor("auth_token")
if err != nil {
panic(fmt.Sprintf("could not generate accessor for default auth table token entry: %v", err))
}
tokenAuth := &MountEntry{
Table: credentialTableType,
Path: "token/",
Type: "token",
Description: "token based credentials",
UUID: tokenUUID,
Accessor: tokenAccessor,
}
table.Entries = append(table.Entries, tokenAuth)
return table
}