forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lock_manager.go
516 lines (432 loc) · 12.5 KB
/
lock_manager.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
package keysutil
import (
"context"
"encoding/base64"
"errors"
"fmt"
"sync"
"time"
"github.com/hashicorp/vault/helper/jsonutil"
"github.com/hashicorp/vault/logical"
)
const (
shared = false
exclusive = true
)
var (
errNeedExclusiveLock = errors.New("an exclusive lock is needed for this operation")
)
// PolicyRequest holds values used when requesting a policy. Most values are
// only used during an upsert.
type PolicyRequest struct {
// The storage to use
Storage logical.Storage
// The name of the policy
Name string
// The key type
KeyType KeyType
// Whether it should be derived
Derived bool
// Whether to enable convergent encryption
Convergent bool
// Whether to allow export
Exportable bool
// Whether to upsert
Upsert bool
// Whether to allow plaintext backup
AllowPlaintextBackup bool
}
type LockManager struct {
// A lock for each named key
locks map[string]*sync.RWMutex
// A mutex for the map itself
locksMutex sync.RWMutex
// If caching is enabled, the map of name to in-memory policy cache
cache map[string]*Policy
// Used for global locking, and as the cache map mutex
cacheMutex sync.RWMutex
}
func NewLockManager(cacheDisabled bool) *LockManager {
lm := &LockManager{
locks: map[string]*sync.RWMutex{},
}
if !cacheDisabled {
lm.cache = map[string]*Policy{}
}
return lm
}
func (lm *LockManager) CacheActive() bool {
return lm.cache != nil
}
func (lm *LockManager) InvalidatePolicy(name string) {
// Check if it's in our cache. If so, return right away.
if lm.CacheActive() {
lm.cacheMutex.Lock()
defer lm.cacheMutex.Unlock()
delete(lm.cache, name)
}
}
func (lm *LockManager) policyLock(name string, lockType bool) *sync.RWMutex {
lm.locksMutex.RLock()
lock := lm.locks[name]
if lock != nil {
// We want to give this up before locking the lock, but it's safe --
// the only time we ever write to a value in this map is the first time
// we access the value, so it won't be changing out from under us
lm.locksMutex.RUnlock()
if lockType == exclusive {
lock.Lock()
} else {
lock.RLock()
}
return lock
}
lm.locksMutex.RUnlock()
lm.locksMutex.Lock()
// Don't defer the unlock call because if we get a valid lock below we want
// to release the lock mutex right away to avoid the possibility of
// deadlock by trying to grab the second lock
// Check to make sure it hasn't been created since
lock = lm.locks[name]
if lock != nil {
lm.locksMutex.Unlock()
if lockType == exclusive {
lock.Lock()
} else {
lock.RLock()
}
return lock
}
lock = &sync.RWMutex{}
lm.locks[name] = lock
lm.locksMutex.Unlock()
if lockType == exclusive {
lock.Lock()
} else {
lock.RLock()
}
return lock
}
func (lm *LockManager) UnlockPolicy(lock *sync.RWMutex, lockType bool) {
if lockType == exclusive {
lock.Unlock()
} else {
lock.RUnlock()
}
}
func (lm *LockManager) UpdateCache(name string, policy *Policy) {
if lm.CacheActive() {
lm.cacheMutex.Lock()
defer lm.cacheMutex.Unlock()
lm.cache[name] = policy
}
}
// Get the policy with a read lock. If we get an error saying an exclusive lock
// is needed (for instance, for an upgrade/migration), give up the read lock,
// call again with an exclusive lock, then swap back out for a read lock.
func (lm *LockManager) GetPolicyShared(ctx context.Context, storage logical.Storage, name string) (*Policy, *sync.RWMutex, error) {
p, lock, _, err := lm.getPolicyCommon(ctx, PolicyRequest{
Storage: storage,
Name: name,
}, shared)
if err == nil ||
(err != nil && err != errNeedExclusiveLock) {
return p, lock, err
}
// Try again while asking for an exlusive lock
p, lock, _, err = lm.getPolicyCommon(ctx, PolicyRequest{
Storage: storage,
Name: name,
}, exclusive)
if err != nil || p == nil || lock == nil {
return p, lock, err
}
lock.Unlock()
p, lock, _, err = lm.getPolicyCommon(ctx, PolicyRequest{
Storage: storage,
Name: name,
}, shared)
return p, lock, err
}
// Get the policy with an exclusive lock
func (lm *LockManager) GetPolicyExclusive(ctx context.Context, storage logical.Storage, name string) (*Policy, *sync.RWMutex, error) {
p, lock, _, err := lm.getPolicyCommon(ctx, PolicyRequest{
Storage: storage,
Name: name,
}, exclusive)
return p, lock, err
}
// Get the policy with a read lock; if it returns that an exclusive lock is
// needed, retry. If successful, call one more time to get a read lock and
// return the value.
func (lm *LockManager) GetPolicyUpsert(ctx context.Context, req PolicyRequest) (*Policy, *sync.RWMutex, bool, error) {
req.Upsert = true
p, lock, _, err := lm.getPolicyCommon(ctx, req, shared)
if err == nil ||
(err != nil && err != errNeedExclusiveLock) {
return p, lock, false, err
}
// Try again while asking for an exlusive lock
p, lock, upserted, err := lm.getPolicyCommon(ctx, req, exclusive)
if err != nil || p == nil || lock == nil {
return p, lock, upserted, err
}
lock.Unlock()
req.Upsert = false
// Now get a shared lock for the return, but preserve the value of upserted
p, lock, _, err = lm.getPolicyCommon(ctx, req, shared)
return p, lock, upserted, err
}
// RestorePolicy acquires an exclusive lock on the policy name and restores the
// given policy along with the archive.
func (lm *LockManager) RestorePolicy(ctx context.Context, storage logical.Storage, name, backup string) error {
var p *Policy
var err error
backupBytes, err := base64.StdEncoding.DecodeString(backup)
if err != nil {
return err
}
var keyData KeyData
err = jsonutil.DecodeJSON(backupBytes, &keyData)
if err != nil {
return err
}
// Set a different name if desired
if name != "" {
keyData.Policy.Name = name
}
name = keyData.Policy.Name
lockType := exclusive
lock := lm.policyLock(name, lockType)
defer lm.UnlockPolicy(lock, lockType)
// If the policy is in cache, error out
if lm.CacheActive() {
lm.cacheMutex.RLock()
p = lm.cache[name]
if p != nil {
lm.cacheMutex.RUnlock()
return fmt.Errorf(fmt.Sprintf("policy %q already exists", name))
}
lm.cacheMutex.RUnlock()
}
// If the policy exists in storage, error out
p, err = lm.getStoredPolicy(ctx, storage, name)
if err != nil {
return err
}
if p != nil {
return fmt.Errorf(fmt.Sprintf("policy %q already exists", name))
}
// Restore the archived keys
if keyData.ArchivedKeys != nil {
err = keyData.Policy.storeArchive(ctx, storage, keyData.ArchivedKeys)
if err != nil {
return fmt.Errorf("failed to restore archived keys for policy %q: %v", name, err)
}
}
// Mark that policy as a restored key
keyData.Policy.RestoreInfo = &RestoreInfo{
Time: time.Now(),
Version: keyData.Policy.LatestVersion,
}
// Restore the policy. This will also attempt to adjust the archive.
err = keyData.Policy.Persist(ctx, storage)
if err != nil {
return fmt.Errorf("failed to restore the policy %q: %v", name, err)
}
// Update the cache to contain the restored policy
lm.UpdateCache(name, keyData.Policy)
return nil
}
func (lm *LockManager) BackupPolicy(ctx context.Context, storage logical.Storage, name string) (string, error) {
p, lock, err := lm.GetPolicyExclusive(ctx, storage, name)
if lock != nil {
defer lock.Unlock()
}
if err != nil {
return "", err
}
if p == nil {
return "", fmt.Errorf("invalid key %q", name)
}
backup, err := p.Backup(ctx, storage)
if err != nil {
return "", err
}
// Update the cache since the policy would now have the backup information
lm.UpdateCache(name, p)
return backup, nil
}
// When the function returns, a lock will be held on the policy if err == nil.
// It is the caller's responsibility to unlock.
func (lm *LockManager) getPolicyCommon(ctx context.Context, req PolicyRequest, lockType bool) (*Policy, *sync.RWMutex, bool, error) {
lock := lm.policyLock(req.Name, lockType)
var p *Policy
var err error
// Check if it's in our cache. If so, return right away.
if lm.CacheActive() {
lm.cacheMutex.RLock()
p = lm.cache[req.Name]
if p != nil {
lm.cacheMutex.RUnlock()
return p, lock, false, nil
}
lm.cacheMutex.RUnlock()
}
// Load it from storage
p, err = lm.getStoredPolicy(ctx, req.Storage, req.Name)
if err != nil {
lm.UnlockPolicy(lock, lockType)
return nil, nil, false, err
}
if p == nil {
// This is the only place we upsert a new policy, so if upsert is not
// specified, or the lock type is wrong, unlock before returning
if !req.Upsert {
lm.UnlockPolicy(lock, lockType)
return nil, nil, false, nil
}
if lockType != exclusive {
lm.UnlockPolicy(lock, lockType)
return nil, nil, false, errNeedExclusiveLock
}
switch req.KeyType {
case KeyType_AES256_GCM96, KeyType_ChaCha20_Poly1305:
if req.Convergent && !req.Derived {
lm.UnlockPolicy(lock, lockType)
return nil, nil, false, fmt.Errorf("convergent encryption requires derivation to be enabled")
}
case KeyType_ECDSA_P256:
if req.Derived || req.Convergent {
lm.UnlockPolicy(lock, lockType)
return nil, nil, false, fmt.Errorf("key derivation and convergent encryption not supported for keys of type %v", req.KeyType)
}
case KeyType_ED25519:
if req.Convergent {
lm.UnlockPolicy(lock, lockType)
return nil, nil, false, fmt.Errorf("convergent encryption not supported for keys of type %v", req.KeyType)
}
case KeyType_RSA2048, KeyType_RSA4096:
if req.Derived || req.Convergent {
lm.UnlockPolicy(lock, lockType)
return nil, nil, false, fmt.Errorf("key derivation and convergent encryption not supported for keys of type %v", req.KeyType)
}
default:
lm.UnlockPolicy(lock, lockType)
return nil, nil, false, fmt.Errorf("unsupported key type %v", req.KeyType)
}
p = &Policy{
Name: req.Name,
Type: req.KeyType,
Derived: req.Derived,
Exportable: req.Exportable,
AllowPlaintextBackup: req.AllowPlaintextBackup,
}
if req.Derived {
p.KDF = Kdf_hkdf_sha256
p.ConvergentEncryption = req.Convergent
p.ConvergentVersion = 2
}
err = p.Rotate(ctx, req.Storage)
if err != nil {
lm.UnlockPolicy(lock, lockType)
return nil, nil, false, err
}
if lm.CacheActive() {
// Since we didn't have the policy in the cache, if there was no
// error, write the value in.
lm.cacheMutex.Lock()
defer lm.cacheMutex.Unlock()
// Make sure a policy didn't appear. If so, it will only be set if
// there was no error, so assume it's good and return that
exp := lm.cache[req.Name]
if exp != nil {
return exp, lock, false, nil
}
if err == nil {
lm.cache[req.Name] = p
}
}
// We don't need to worry about upgrading since it will be a new policy
return p, lock, true, nil
}
if p.NeedsUpgrade() {
if lockType == shared {
lm.UnlockPolicy(lock, lockType)
return nil, nil, false, errNeedExclusiveLock
}
err = p.Upgrade(ctx, req.Storage)
if err != nil {
lm.UnlockPolicy(lock, lockType)
return nil, nil, false, err
}
}
if lm.CacheActive() {
// Since we didn't have the policy in the cache, if there was no
// error, write the value in.
lm.cacheMutex.Lock()
defer lm.cacheMutex.Unlock()
// Make sure a policy didn't appear. If so, it will only be set if
// there was no error, so assume it's good and return that
exp := lm.cache[req.Name]
if exp != nil {
return exp, lock, false, nil
}
if err == nil {
lm.cache[req.Name] = p
}
}
return p, lock, false, nil
}
func (lm *LockManager) DeletePolicy(ctx context.Context, storage logical.Storage, name string) error {
lm.cacheMutex.Lock()
lock := lm.policyLock(name, exclusive)
defer lock.Unlock()
defer lm.cacheMutex.Unlock()
var p *Policy
var err error
if lm.CacheActive() {
p = lm.cache[name]
}
if p == nil {
p, err = lm.getStoredPolicy(ctx, storage, name)
if err != nil {
return err
}
if p == nil {
return fmt.Errorf("could not delete policy; not found")
}
}
if !p.DeletionAllowed {
return fmt.Errorf("deletion is not allowed for this policy")
}
err = storage.Delete(ctx, "policy/"+name)
if err != nil {
return fmt.Errorf("error deleting policy %s: %s", name, err)
}
err = storage.Delete(ctx, "archive/"+name)
if err != nil {
return fmt.Errorf("error deleting archive %s: %s", name, err)
}
if lm.CacheActive() {
delete(lm.cache, name)
}
return nil
}
func (lm *LockManager) getStoredPolicy(ctx context.Context, storage logical.Storage, name string) (*Policy, error) {
// Check if the policy already exists
raw, err := storage.Get(ctx, "policy/"+name)
if err != nil {
return nil, err
}
if raw == nil {
return nil, nil
}
// Decode the policy
var policy Policy
err = jsonutil.DecodeJSON(raw.Value, &policy)
if err != nil {
return nil, err
}
return &policy, nil
}