forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 2
/
token_store.go
2307 lines (1955 loc) · 72.8 KB
/
token_store.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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package vault
import (
"encoding/json"
"fmt"
"regexp"
"strings"
"sync"
"time"
"github.com/armon/go-metrics"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/vault/helper/duration"
"github.com/hashicorp/vault/helper/jsonutil"
"github.com/hashicorp/vault/helper/locksutil"
"github.com/hashicorp/vault/helper/policyutil"
"github.com/hashicorp/vault/helper/salt"
"github.com/hashicorp/vault/helper/strutil"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
"github.com/mitchellh/mapstructure"
)
const (
// lookupPrefix is the prefix used to store tokens for their
// primary ID based index
lookupPrefix = "id/"
// accessorPrefix is the prefix used to store the index from
// Accessor to Token ID
accessorPrefix = "accessor/"
// parentPrefix is the prefix used to store tokens for their
// secondar parent based index
parentPrefix = "parent/"
// tokenSubPath is the sub-path used for the token store
// view. This is nested under the system view.
tokenSubPath = "token/"
// rolesPrefix is the prefix used to store role information
rolesPrefix = "roles/"
// tokenRevocationDeferred indicates that the token should not be used
// again but is currently fulfilling its final use
tokenRevocationDeferred = -1
// tokenRevocationInProgress indicates that revocation of that token/its
// leases is ongoing
tokenRevocationInProgress = -2
// tokenRevocationFailed indicates that revocation failed; the entry is
// kept around so that when the tidy function is run it can be tried
// again (or when the revocation function is run again), but all other uses
// will report the token invalid
tokenRevocationFailed = -3
)
var (
// displayNameSanitize is used to sanitize a display name given to a token.
displayNameSanitize = regexp.MustCompile("[^a-zA-Z0-9-]")
// pathSuffixSanitize is used to ensure a path suffix in a role is valid.
pathSuffixSanitize = regexp.MustCompile("\\w[\\w-.]+\\w")
destroyCubbyhole = func(ts *TokenStore, saltedID string) error {
if ts.cubbyholeBackend == nil {
// Should only ever happen in testing
return nil
}
return ts.cubbyholeBackend.revoke(salt.SaltID(ts.cubbyholeBackend.saltUUID, saltedID, salt.SHA1Hash))
}
)
// TokenStore is used to manage client tokens. Tokens are used for
// clients to authenticate, and each token is mapped to an applicable
// set of policy which is used for authorization.
type TokenStore struct {
*framework.Backend
view *BarrierView
salt *salt.Salt
expiration *ExpirationManager
cubbyholeBackend *CubbyholeBackend
policyLookupFunc func(string) (*Policy, error)
tokenLocks map[string]*sync.RWMutex
cubbyholeDestroyer func(*TokenStore, string) error
}
// NewTokenStore is used to construct a token store that is
// backed by the given barrier view.
func NewTokenStore(c *Core, config *logical.BackendConfig) (*TokenStore, error) {
// Create a sub-view
view := c.systemBarrierView.SubView(tokenSubPath)
// Initialize the store
t := &TokenStore{
view: view,
cubbyholeDestroyer: destroyCubbyhole,
}
if c.policyStore != nil {
t.policyLookupFunc = c.policyStore.GetPolicy
}
t.tokenLocks = map[string]*sync.RWMutex{}
// Create 256 locks
if err := locksutil.CreateLocks(t.tokenLocks, 256); err != nil {
return nil, fmt.Errorf("failed to create locks: %v", err)
}
t.tokenLocks["custom"] = &sync.RWMutex{}
// Setup the framework endpoints
t.Backend = &framework.Backend{
AuthRenew: t.authRenew,
PathsSpecial: &logical.Paths{
Root: []string{
"revoke-orphan/*",
"accessors*",
},
// Most token store items are local since tokens are local, but a
// notable exception is roles
LocalStorage: []string{
lookupPrefix,
accessorPrefix,
parentPrefix,
"salt",
},
},
Paths: []*framework.Path{
&framework.Path{
Pattern: "roles/?$",
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ListOperation: t.tokenStoreRoleList,
},
HelpSynopsis: tokenListRolesHelp,
HelpDescription: tokenListRolesHelp,
},
&framework.Path{
Pattern: "accessors/?$",
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ListOperation: t.tokenStoreAccessorList,
},
HelpSynopsis: tokenListAccessorsHelp,
HelpDescription: tokenListAccessorsHelp,
},
&framework.Path{
Pattern: "roles/" + framework.GenericNameRegex("role_name"),
Fields: map[string]*framework.FieldSchema{
"role_name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role",
},
"allowed_policies": &framework.FieldSchema{
Type: framework.TypeString,
Default: "",
Description: tokenAllowedPoliciesHelp,
},
"disallowed_policies": &framework.FieldSchema{
Type: framework.TypeString,
Default: "",
Description: tokenDisallowedPoliciesHelp,
},
"orphan": &framework.FieldSchema{
Type: framework.TypeBool,
Default: false,
Description: tokenOrphanHelp,
},
"period": &framework.FieldSchema{
Type: framework.TypeDurationSecond,
Default: 0,
Description: tokenPeriodHelp,
},
"path_suffix": &framework.FieldSchema{
Type: framework.TypeString,
Default: "",
Description: tokenPathSuffixHelp + pathSuffixSanitize.String(),
},
"explicit_max_ttl": &framework.FieldSchema{
Type: framework.TypeDurationSecond,
Default: 0,
Description: tokenExplicitMaxTTLHelp,
},
"renewable": &framework.FieldSchema{
Type: framework.TypeBool,
Default: true,
Description: tokenRenewableHelp,
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: t.tokenStoreRoleRead,
logical.CreateOperation: t.tokenStoreRoleCreateUpdate,
logical.UpdateOperation: t.tokenStoreRoleCreateUpdate,
logical.DeleteOperation: t.tokenStoreRoleDelete,
},
ExistenceCheck: t.tokenStoreRoleExistenceCheck,
HelpSynopsis: tokenPathRolesHelp,
HelpDescription: tokenPathRolesHelp,
},
&framework.Path{
Pattern: "create-orphan$",
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: t.handleCreateOrphan,
},
HelpSynopsis: strings.TrimSpace(tokenCreateOrphanHelp),
HelpDescription: strings.TrimSpace(tokenCreateOrphanHelp),
},
&framework.Path{
Pattern: "create/" + framework.GenericNameRegex("role_name"),
Fields: map[string]*framework.FieldSchema{
"role_name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: t.handleCreateAgainstRole,
},
HelpSynopsis: strings.TrimSpace(tokenCreateRoleHelp),
HelpDescription: strings.TrimSpace(tokenCreateRoleHelp),
},
&framework.Path{
Pattern: "create$",
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: t.handleCreate,
},
HelpSynopsis: strings.TrimSpace(tokenCreateHelp),
HelpDescription: strings.TrimSpace(tokenCreateHelp),
},
&framework.Path{
Pattern: "lookup" + framework.OptionalParamRegex("urltoken"),
Fields: map[string]*framework.FieldSchema{
"urltoken": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Token to lookup (URL parameter)",
},
"token": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Token to lookup (POST request body)",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: t.handleLookup,
logical.UpdateOperation: t.handleLookup,
},
HelpSynopsis: strings.TrimSpace(tokenLookupHelp),
HelpDescription: strings.TrimSpace(tokenLookupHelp),
},
&framework.Path{
Pattern: "lookup-accessor" + framework.OptionalParamRegex("urlaccessor"),
Fields: map[string]*framework.FieldSchema{
"urlaccessor": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Accessor of the token to look up (URL parameter)",
},
"accessor": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Accessor of the token to look up (request body)",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: t.handleUpdateLookupAccessor,
},
HelpSynopsis: strings.TrimSpace(tokenLookupAccessorHelp),
HelpDescription: strings.TrimSpace(tokenLookupAccessorHelp),
},
&framework.Path{
Pattern: "lookup-self$",
Fields: map[string]*framework.FieldSchema{
"token": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Token to look up (unused, does not need to be set)",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: t.handleLookupSelf,
logical.ReadOperation: t.handleLookupSelf,
},
HelpSynopsis: strings.TrimSpace(tokenLookupHelp),
HelpDescription: strings.TrimSpace(tokenLookupHelp),
},
&framework.Path{
Pattern: "revoke-accessor" + framework.OptionalParamRegex("urlaccessor"),
Fields: map[string]*framework.FieldSchema{
"urlaccessor": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Accessor of the token (URL parameter)",
},
"accessor": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Accessor of the token (request body)",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: t.handleUpdateRevokeAccessor,
},
HelpSynopsis: strings.TrimSpace(tokenRevokeAccessorHelp),
HelpDescription: strings.TrimSpace(tokenRevokeAccessorHelp),
},
&framework.Path{
Pattern: "revoke-self$",
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: t.handleRevokeSelf,
},
HelpSynopsis: strings.TrimSpace(tokenRevokeSelfHelp),
HelpDescription: strings.TrimSpace(tokenRevokeSelfHelp),
},
&framework.Path{
Pattern: "revoke" + framework.OptionalParamRegex("urltoken"),
Fields: map[string]*framework.FieldSchema{
"urltoken": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Token to revoke (URL parameter)",
},
"token": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Token to revoke (request body)",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: t.handleRevokeTree,
},
HelpSynopsis: strings.TrimSpace(tokenRevokeHelp),
HelpDescription: strings.TrimSpace(tokenRevokeHelp),
},
&framework.Path{
Pattern: "revoke-orphan" + framework.OptionalParamRegex("urltoken"),
Fields: map[string]*framework.FieldSchema{
"urltoken": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Token to revoke (URL parameter)",
},
"token": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Token to revoke (request body)",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: t.handleRevokeOrphan,
},
HelpSynopsis: strings.TrimSpace(tokenRevokeOrphanHelp),
HelpDescription: strings.TrimSpace(tokenRevokeOrphanHelp),
},
&framework.Path{
Pattern: "renew-self$",
Fields: map[string]*framework.FieldSchema{
"token": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Token to renew (unused, does not need to be set)",
},
"increment": &framework.FieldSchema{
Type: framework.TypeDurationSecond,
Default: 0,
Description: "The desired increment in seconds to the token expiration",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: t.handleRenewSelf,
},
HelpSynopsis: strings.TrimSpace(tokenRenewSelfHelp),
HelpDescription: strings.TrimSpace(tokenRenewSelfHelp),
},
&framework.Path{
Pattern: "renew" + framework.OptionalParamRegex("urltoken"),
Fields: map[string]*framework.FieldSchema{
"urltoken": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Token to renew (URL parameter)",
},
"token": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Token to renew (request body)",
},
"increment": &framework.FieldSchema{
Type: framework.TypeDurationSecond,
Default: 0,
Description: "The desired increment in seconds to the token expiration",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: t.handleRenew,
},
HelpSynopsis: strings.TrimSpace(tokenRenewHelp),
HelpDescription: strings.TrimSpace(tokenRenewHelp),
},
&framework.Path{
Pattern: "tidy$",
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: t.handleTidy,
},
HelpSynopsis: strings.TrimSpace(tokenTidyHelp),
HelpDescription: strings.TrimSpace(tokenTidyDesc),
},
},
Init: t.Initialize,
}
t.Backend.Setup(config)
return t, nil
}
func (ts *TokenStore) Initialize() error {
// Setup the salt
salt, err := salt.NewSalt(ts.view, &salt.Config{
HashFunc: salt.SHA1Hash,
})
if err != nil {
return err
}
ts.salt = salt
return nil
}
// TokenEntry is used to represent a given token
type TokenEntry struct {
// ID of this entry, generally a random UUID
ID string `json:"id" mapstructure:"id" structs:"id"`
// Accessor for this token, a random UUID
Accessor string `json:"accessor" mapstructure:"accessor" structs:"accessor"`
// Parent token, used for revocation trees
Parent string `json:"parent" mapstructure:"parent" structs:"parent"`
// Which named policies should be used
Policies []string `json:"policies" mapstructure:"policies" structs:"policies"`
// Used for audit trails, this is something like "auth/user/login"
Path string `json:"path" mapstructure:"path" structs:"path"`
// Used for auditing. This could include things like "source", "user", "ip"
Meta map[string]string `json:"meta" mapstructure:"meta" structs:"meta"`
// Used for operators to be able to associate with the source
DisplayName string `json:"display_name" mapstructure:"display_name" structs:"display_name"`
// Used to restrict the number of uses (zero is unlimited). This is to
// support one-time-tokens (generalized). There are a few special values:
// if it's -1 it has run through its use counts and is executing its final
// use; if it's -2 it is tainted, which means revocation is currently
// running on it; and if it's -3 it's also tainted but revocation
// previously ran and failed, so this hints the tidy function to try it
// again.
NumUses int `json:"num_uses" mapstructure:"num_uses" structs:"num_uses"`
// Time of token creation
CreationTime int64 `json:"creation_time" mapstructure:"creation_time" structs:"creation_time"`
// Duration set when token was created
TTL time.Duration `json:"ttl" mapstructure:"ttl" structs:"ttl"`
// Explicit maximum TTL on the token
ExplicitMaxTTL time.Duration `json:"explicit_max_ttl" mapstructure:"explicit_max_ttl" structs:"explicit_max_ttl"`
// If set, the role that was used for parameters at creation time
Role string `json:"role" mapstructure:"role" structs:"role"`
// If set, the period of the token. This is only used when created directly
// through the create endpoint; periods managed by roles or other auth
// backends are subject to those renewal rules.
Period time.Duration `json:"period" mapstructure:"period" structs:"period"`
// These are the deprecated fields
DisplayNameDeprecated string `json:"DisplayName" mapstructure:"DisplayName" structs:"DisplayName"`
NumUsesDeprecated int `json:"NumUses" mapstructure:"NumUses" structs:"NumUses"`
CreationTimeDeprecated int64 `json:"CreationTime" mapstructure:"CreationTime" structs:"CreationTime"`
ExplicitMaxTTLDeprecated time.Duration `json:"ExplicitMaxTTL" mapstructure:"ExplicitMaxTTL" structs:"ExplicitMaxTTL"`
}
// tsRoleEntry contains token store role information
type tsRoleEntry struct {
// The name of the role. Embedded so it can be used for pathing
Name string `json:"name" mapstructure:"name" structs:"name"`
// The policies that creation functions using this role can assign to a token,
// escaping or further locking down normal subset checking
AllowedPolicies []string `json:"allowed_policies" mapstructure:"allowed_policies" structs:"allowed_policies"`
// List of policies to be not allowed during token creation using this role
DisallowedPolicies []string `json:"disallowed_policies" mapstructure:"disallowed_policies" structs:"disallowed_policies"`
// If true, tokens created using this role will be orphans
Orphan bool `json:"orphan" mapstructure:"orphan" structs:"orphan"`
// If non-zero, tokens created using this role will be able to be renewed
// forever, but will have a fixed renewal period of this value
Period time.Duration `json:"period" mapstructure:"period" structs:"period"`
// If set, a suffix will be set on the token path, making it easier to
// revoke using 'revoke-prefix'
PathSuffix string `json:"path_suffix" mapstructure:"path_suffix" structs:"path_suffix"`
// If set, controls whether created tokens are marked as being renewable
Renewable bool `json:"renewable" mapstructure:"renewable" structs:"renewable"`
// If set, the token entry will have an explicit maximum TTL set, rather
// than deferring to role/mount values
ExplicitMaxTTL time.Duration `json:"explicit_max_ttl" mapstructure:"explicit_max_ttl" structs:"explicit_max_ttl"`
}
type accessorEntry struct {
TokenID string `json:"token_id"`
AccessorID string `json:"accessor_id"`
}
// SetExpirationManager is used to provide the token store with
// an expiration manager. This is used to manage prefix based revocation
// of tokens and to tidy entries when removed from the token store.
func (ts *TokenStore) SetExpirationManager(exp *ExpirationManager) {
ts.expiration = exp
}
// SaltID is used to apply a salt and hash to an ID to make sure its not reversible
func (ts *TokenStore) SaltID(id string) string {
return ts.salt.SaltID(id)
}
// RootToken is used to generate a new token with root privileges and no parent
func (ts *TokenStore) rootToken() (*TokenEntry, error) {
te := &TokenEntry{
Policies: []string{"root"},
Path: "auth/token/root",
DisplayName: "root",
CreationTime: time.Now().Unix(),
}
if err := ts.create(te); err != nil {
return nil, err
}
return te, nil
}
func (ts *TokenStore) tokenStoreAccessorList(
req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
entries, err := ts.view.List(accessorPrefix)
if err != nil {
return nil, err
}
resp := &logical.Response{}
ret := make([]string, 0, len(entries))
for _, entry := range entries {
aEntry, err := ts.lookupBySaltedAccessor(entry)
if err != nil {
resp.AddWarning("Found an accessor entry that could not be successfully decoded")
continue
}
if aEntry.TokenID == "" {
resp.AddWarning(fmt.Sprintf("Found an accessor entry missing a token: %v", aEntry.AccessorID))
} else {
ret = append(ret, aEntry.AccessorID)
}
}
resp.Data = map[string]interface{}{
"keys": ret,
}
return resp, nil
}
// createAccessor is used to create an identifier for the token ID.
// A storage index, mapping the accessor to the token ID is also created.
func (ts *TokenStore) createAccessor(entry *TokenEntry) error {
defer metrics.MeasureSince([]string{"token", "createAccessor"}, time.Now())
// Create a random accessor
accessorUUID, err := uuid.GenerateUUID()
if err != nil {
return err
}
entry.Accessor = accessorUUID
// Create index entry, mapping the accessor to the token ID
path := accessorPrefix + ts.SaltID(entry.Accessor)
aEntry := &accessorEntry{
TokenID: entry.ID,
AccessorID: entry.Accessor,
}
aEntryBytes, err := jsonutil.EncodeJSON(aEntry)
if err != nil {
return fmt.Errorf("failed to marshal accessor index entry: %v", err)
}
le := &logical.StorageEntry{Key: path, Value: aEntryBytes}
if err := ts.view.Put(le); err != nil {
return fmt.Errorf("failed to persist accessor index entry: %v", err)
}
return nil
}
// Create is used to create a new token entry. The entry is assigned
// a newly generated ID if not provided.
func (ts *TokenStore) create(entry *TokenEntry) error {
defer metrics.MeasureSince([]string{"token", "create"}, time.Now())
// Generate an ID if necessary
if entry.ID == "" {
entryUUID, err := uuid.GenerateUUID()
if err != nil {
return err
}
entry.ID = entryUUID
}
entry.Policies = policyutil.SanitizePolicies(entry.Policies, policyutil.DoNotAddDefaultPolicy)
err := ts.createAccessor(entry)
if err != nil {
return err
}
return ts.storeCommon(entry, true)
}
// Store is used to store an updated token entry without writing the
// secondary index.
func (ts *TokenStore) store(entry *TokenEntry) error {
defer metrics.MeasureSince([]string{"token", "store"}, time.Now())
return ts.storeCommon(entry, false)
}
// storeCommon handles the actual storage of an entry, possibly generating
// secondary indexes
func (ts *TokenStore) storeCommon(entry *TokenEntry, writeSecondary bool) error {
saltedId := ts.SaltID(entry.ID)
// Marshal the entry
enc, err := json.Marshal(entry)
if err != nil {
return fmt.Errorf("failed to encode entry: %v", err)
}
if writeSecondary {
// Write the secondary index if necessary. This is done before the
// primary index because we'd rather have a dangling pointer with
// a missing primary instead of missing the parent index and potentially
// escaping the revocation chain.
if entry.Parent != "" {
// Ensure the parent exists
parent, err := ts.Lookup(entry.Parent)
if err != nil {
return fmt.Errorf("failed to lookup parent: %v", err)
}
if parent == nil {
return fmt.Errorf("parent token not found")
}
// Create the index entry
path := parentPrefix + ts.SaltID(entry.Parent) + "/" + saltedId
le := &logical.StorageEntry{Key: path}
if err := ts.view.Put(le); err != nil {
return fmt.Errorf("failed to persist entry: %v", err)
}
}
}
// Write the primary ID
path := lookupPrefix + saltedId
le := &logical.StorageEntry{Key: path, Value: enc}
if err := ts.view.Put(le); err != nil {
return fmt.Errorf("failed to persist entry: %v", err)
}
return nil
}
func (ts *TokenStore) getTokenLock(id string) *sync.RWMutex {
// Find our multilevel lock, or fall back to global
var lock *sync.RWMutex
var ok bool
if len(id) >= 2 {
lock, ok = ts.tokenLocks[id[0:2]]
}
if !ok || lock == nil {
// Fall back for custom token IDs
lock = ts.tokenLocks["custom"]
}
return lock
}
// UseToken is used to manage restricted use tokens and decrement their
// available uses. Returns two values: a potentially updated entry or, if the
// token has been revoked, nil; and whether an error was encountered. The
// locking here isn't perfect, as other parts of the code may update an entry,
// but usually none after the entry is already created...so this is pretty
// good.
func (ts *TokenStore) UseToken(te *TokenEntry) (*TokenEntry, error) {
if te == nil {
return nil, fmt.Errorf("invalid token entry provided for use count decrementing")
}
// This case won't be hit with a token with restricted uses because we go
// from 1 to -1. So it's a nice optimization to check this without a read
// lock.
if te.NumUses == 0 {
return te, nil
}
lock := ts.getTokenLock(te.ID)
lock.Lock()
defer lock.Unlock()
// Call lookupSalted instead of Lookup to avoid deadlocking since Lookup grabs a read lock
te, err := ts.lookupSalted(ts.SaltID(te.ID), false)
if err != nil {
return nil, fmt.Errorf("failed to refresh entry: %v", err)
}
// If it can't be found we shouldn't be trying to use it, so if we get nil
// back, it is because it has been revoked in the interim or will be
// revoked (NumUses is -1)
if te == nil {
return nil, fmt.Errorf("token not found or fully used already")
}
// Decrement the count. If this is our last use count, we need to indicate
// that this is no longer valid, but revocation is deferred to the end of
// the call, so this will make sure that any Lookup that happens doesn't
// return an entry. This essentially acts as a write-ahead lock and is
// especially useful since revocation can end up (via the expiration
// manager revoking children) attempting to acquire the same lock
// repeatedly.
if te.NumUses == 1 {
te.NumUses = -1
} else {
te.NumUses -= 1
}
err = ts.storeCommon(te, false)
if err != nil {
return nil, err
}
return te, nil
}
func (ts *TokenStore) UseTokenByID(id string) (*TokenEntry, error) {
te, err := ts.Lookup(id)
if err != nil {
return te, err
}
return ts.UseToken(te)
}
// Lookup is used to find a token given its ID. It acquires a read lock, then calls lookupSalted.
func (ts *TokenStore) Lookup(id string) (*TokenEntry, error) {
defer metrics.MeasureSince([]string{"token", "lookup"}, time.Now())
if id == "" {
return nil, fmt.Errorf("cannot lookup blank token")
}
lock := ts.getTokenLock(id)
lock.RLock()
defer lock.RUnlock()
return ts.lookupSalted(ts.SaltID(id), false)
}
// lookupSalted is used to find a token given its salted ID. If tainted is
// true, entries that are in some revocation state (currently, indicated by num
// uses < 0), the entry will be returned anyways
func (ts *TokenStore) lookupSalted(saltedId string, tainted bool) (*TokenEntry, error) {
// Lookup token
path := lookupPrefix + saltedId
raw, err := ts.view.Get(path)
if err != nil {
return nil, fmt.Errorf("failed to read entry: %v", err)
}
// Bail if not found
if raw == nil {
return nil, nil
}
// Unmarshal the token
entry := new(TokenEntry)
if err := jsonutil.DecodeJSON(raw.Value, entry); err != nil {
return nil, fmt.Errorf("failed to decode entry: %v", err)
}
// This is a token that is awaiting deferred revocation or tainted
if entry.NumUses < 0 && !tainted {
return nil, nil
}
persistNeeded := false
// Upgrade the deprecated fields
if entry.DisplayNameDeprecated != "" {
if entry.DisplayName == "" {
entry.DisplayName = entry.DisplayNameDeprecated
}
entry.DisplayNameDeprecated = ""
persistNeeded = true
}
if entry.CreationTimeDeprecated != 0 {
if entry.CreationTime == 0 {
entry.CreationTime = entry.CreationTimeDeprecated
}
entry.CreationTimeDeprecated = 0
persistNeeded = true
}
if entry.ExplicitMaxTTLDeprecated != 0 {
if entry.ExplicitMaxTTL == 0 {
entry.ExplicitMaxTTL = entry.ExplicitMaxTTLDeprecated
}
entry.ExplicitMaxTTLDeprecated = 0
persistNeeded = true
}
if entry.NumUsesDeprecated != 0 {
if entry.NumUses == 0 || entry.NumUsesDeprecated < entry.NumUses {
entry.NumUses = entry.NumUsesDeprecated
}
entry.NumUsesDeprecated = 0
persistNeeded = true
}
// If fields are getting upgraded, store the changes
if persistNeeded {
if err := ts.storeCommon(entry, false); err != nil {
return nil, fmt.Errorf("failed to persist token upgrade: %v", err)
}
}
return entry, nil
}
// Revoke is used to invalidate a given token, any child tokens
// will be orphaned.
func (ts *TokenStore) Revoke(id string) error {
defer metrics.MeasureSince([]string{"token", "revoke"}, time.Now())
if id == "" {
return fmt.Errorf("cannot revoke blank token")
}
return ts.revokeSalted(ts.SaltID(id))
}
// revokeSalted is used to invalidate a given salted token,
// any child tokens will be orphaned.
func (ts *TokenStore) revokeSalted(saltedId string) (ret error) {
// Protect the entry lookup/writing with locks. The rub here is that we
// don't know the ID until we look it up once, so first we look it up, then
// do a locked lookup.
entry, err := ts.lookupSalted(saltedId, true)
if err != nil {
return err
}
if entry == nil {
return nil
}
lock := ts.getTokenLock(entry.ID)
lock.Lock()
// Lookup the token first
entry, err = ts.lookupSalted(saltedId, true)
if err != nil {
lock.Unlock()
return err
}
if entry == nil {
lock.Unlock()
return nil
}
// On failure we write -3, so if we hit -2 here we're already running a
// revocation operation. This can happen due to e.g. recursion into this
// function via the expiration manager's RevokeByToken.
if entry.NumUses == tokenRevocationInProgress {
lock.Unlock()
return nil
}
// This acts as a WAL. lookupSalted will no longer return this entry,
// so the token cannot be used, but this way we can keep the entry
// around until after the rest of this function is attempted, and a
// tidy function can key off of this value to try again.
entry.NumUses = tokenRevocationInProgress
err = ts.storeCommon(entry, false)
lock.Unlock()
if err != nil {
return err
}
// If we are returning an error, mark the entry with -3 to indicate
// failed revocation. This way we don't try to clean up during active
// revocation (-2).
defer func() {
if ret != nil {
lock.Lock()
defer lock.Unlock()
// Lookup the token again to make sure something else didn't
// revoke in the interim
entry, err := ts.lookupSalted(saltedId, true)
if err != nil {
return
}
// If it exists just taint to -3 rather than trying to figure
// out what it means if it's already -3 after the -2 above
if entry != nil {
entry.NumUses = tokenRevocationFailed
ts.storeCommon(entry, false)
}
}
}()
// Destroy the token's cubby. This should go first as it's a
// security-sensitive item.
err = ts.cubbyholeDestroyer(ts, saltedId)
if err != nil {
return err
}
// Revoke all secrets under this token. This should go first as it's a