forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate_root.go
305 lines (263 loc) · 7.85 KB
/
generate_root.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
package vault
import (
"bytes"
"encoding/base64"
"fmt"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/vault/helper/pgpkeys"
"github.com/hashicorp/vault/helper/xor"
"github.com/hashicorp/vault/shamir"
)
// GenerateRootConfig holds the configuration for a root generation
// command.
type GenerateRootConfig struct {
Nonce string
PGPKey string
PGPFingerprint string
OTP string
}
// GenerateRootResult holds the result of a root generation update
// command
type GenerateRootResult struct {
Progress int
Required int
EncodedRootToken string
PGPFingerprint string
}
// GenerateRoot is used to return the root generation progress (num shares)
func (c *Core) GenerateRootProgress() (int, error) {
c.stateLock.RLock()
defer c.stateLock.RUnlock()
if c.sealed {
return 0, ErrSealed
}
if c.standby {
return 0, ErrStandby
}
c.generateRootLock.Lock()
defer c.generateRootLock.Unlock()
return len(c.generateRootProgress), nil
}
// GenerateRootConfig is used to read the root generation configuration
// It stubbornly refuses to return the OTP if one is there.
func (c *Core) GenerateRootConfiguration() (*GenerateRootConfig, error) {
c.stateLock.RLock()
defer c.stateLock.RUnlock()
if c.sealed {
return nil, ErrSealed
}
if c.standby {
return nil, ErrStandby
}
c.generateRootLock.Lock()
defer c.generateRootLock.Unlock()
// Copy the config if any
var conf *GenerateRootConfig
if c.generateRootConfig != nil {
conf = new(GenerateRootConfig)
*conf = *c.generateRootConfig
conf.OTP = ""
}
return conf, nil
}
// GenerateRootInit is used to initialize the root generation settings
func (c *Core) GenerateRootInit(otp, pgpKey string) error {
var fingerprint string
switch {
case len(otp) > 0:
otpBytes, err := base64.StdEncoding.DecodeString(otp)
if err != nil {
return fmt.Errorf("error decoding base64 OTP value: %s", err)
}
if otpBytes == nil || len(otpBytes) != 16 {
return fmt.Errorf("decoded OTP value is invalid or wrong length")
}
case len(pgpKey) > 0:
fingerprints, err := pgpkeys.GetFingerprints([]string{pgpKey}, nil)
if err != nil {
return fmt.Errorf("error parsing PGP key: %s", err)
}
if len(fingerprints) != 1 || fingerprints[0] == "" {
return fmt.Errorf("could not acquire PGP key entity")
}
fingerprint = fingerprints[0]
default:
return fmt.Errorf("unreachable condition")
}
c.stateLock.RLock()
defer c.stateLock.RUnlock()
if c.sealed {
return ErrSealed
}
if c.standby {
return ErrStandby
}
c.generateRootLock.Lock()
defer c.generateRootLock.Unlock()
// Prevent multiple concurrent root generations
if c.generateRootConfig != nil {
return fmt.Errorf("root generation already in progress")
}
// Copy the configuration
generationNonce, err := uuid.GenerateUUID()
if err != nil {
return err
}
c.generateRootConfig = &GenerateRootConfig{
Nonce: generationNonce,
OTP: otp,
PGPKey: pgpKey,
PGPFingerprint: fingerprint,
}
c.logger.Printf("[INFO] core: root generation initialized (nonce: %s)",
c.generateRootConfig.Nonce)
return nil
}
// GenerateRootUpdate is used to provide a new key part
func (c *Core) GenerateRootUpdate(key []byte, nonce string) (*GenerateRootResult, error) {
// Verify the key length
min, max := c.barrier.KeyLength()
max += shamir.ShareOverhead
if len(key) < min {
return nil, &ErrInvalidKey{fmt.Sprintf("key is shorter than minimum %d bytes", min)}
}
if len(key) > max {
return nil, &ErrInvalidKey{fmt.Sprintf("key is longer than maximum %d bytes", max)}
}
// Get the seal configuration
config, err := c.SealConfig()
if err != nil {
return nil, err
}
// Ensure the barrier is initialized
if config == nil {
return nil, ErrNotInit
}
// Ensure we are already unsealed
c.stateLock.RLock()
defer c.stateLock.RUnlock()
if c.sealed {
return nil, ErrSealed
}
if c.standby {
return nil, ErrStandby
}
c.generateRootLock.Lock()
defer c.generateRootLock.Unlock()
// Ensure a generateRoot is in progress
if c.generateRootConfig == nil {
return nil, fmt.Errorf("no root generation in progress")
}
if nonce != c.generateRootConfig.Nonce {
return nil, fmt.Errorf("incorrect nonce supplied; nonce for this root generation operation is %s", c.generateRootConfig.Nonce)
}
// Check if we already have this piece
for _, existing := range c.generateRootProgress {
if bytes.Equal(existing, key) {
return nil, nil
}
}
// Store this key
c.generateRootProgress = append(c.generateRootProgress, key)
progress := len(c.generateRootProgress)
// Check if we don't have enough keys to unlock
if len(c.generateRootProgress) < config.SecretThreshold {
c.logger.Printf("[DEBUG] core: cannot generate root, have %d of %d keys",
progress, config.SecretThreshold)
return &GenerateRootResult{
Progress: progress,
Required: config.SecretThreshold,
PGPFingerprint: c.generateRootConfig.PGPFingerprint,
}, nil
}
// Recover the master key
var masterKey []byte
if config.SecretThreshold == 1 {
masterKey = c.generateRootProgress[0]
c.generateRootProgress = nil
} else {
masterKey, err = shamir.Combine(c.generateRootProgress)
c.generateRootProgress = nil
if err != nil {
return nil, fmt.Errorf("failed to compute master key: %v", err)
}
}
// Verify the master key
if err := c.barrier.VerifyMaster(masterKey); err != nil {
c.logger.Printf("[ERR] core: root generation aborted, master key verification failed: %v", err)
return nil, err
}
te, err := c.tokenStore.rootToken()
if err != nil {
c.logger.Printf("[ERR] core: root token generation failed: %v", err)
return nil, err
}
if te == nil {
c.logger.Printf("[ERR] core: got nil token entry back from root generation")
return nil, fmt.Errorf("got nil token entry back from root generation")
}
uuidBytes, err := uuid.ParseUUID(te.ID)
if err != nil {
c.tokenStore.Revoke(te.ID)
c.logger.Printf("[ERR] core: error getting generated token bytes: %v", err)
return nil, err
}
if uuidBytes == nil {
c.tokenStore.Revoke(te.ID)
c.logger.Printf("[ERR] core: got nil parsed UUID bytes")
return nil, fmt.Errorf("got nil parsed UUID bytes")
}
var tokenBytes []byte
// Get the encoded value first so that if there is an error we don't create
// the root token.
switch {
case len(c.generateRootConfig.OTP) > 0:
// This function performs decoding checks so rather than decode the OTP,
// just encode the value we're passing in.
tokenBytes, err = xor.XORBase64(c.generateRootConfig.OTP, base64.StdEncoding.EncodeToString(uuidBytes))
if err != nil {
c.tokenStore.Revoke(te.ID)
c.logger.Printf("[ERR] core: xor of root token failed: %v", err)
return nil, err
}
case len(c.generateRootConfig.PGPKey) > 0:
_, tokenBytesArr, err := pgpkeys.EncryptShares([][]byte{[]byte(te.ID)}, []string{c.generateRootConfig.PGPKey})
if err != nil {
c.tokenStore.Revoke(te.ID)
c.logger.Printf("[ERR] core: error encrypting new root token: %v", err)
return nil, err
}
tokenBytes = tokenBytesArr[0]
default:
c.tokenStore.Revoke(te.ID)
return nil, fmt.Errorf("unreachable condition")
}
results := &GenerateRootResult{
Progress: progress,
Required: config.SecretThreshold,
EncodedRootToken: base64.StdEncoding.EncodeToString(tokenBytes),
PGPFingerprint: c.generateRootConfig.PGPFingerprint,
}
c.logger.Printf("[INFO] core: root generation finished (nonce: %s)",
c.generateRootConfig.Nonce)
c.generateRootProgress = nil
c.generateRootConfig = nil
return results, nil
}
// GenerateRootCancel is used to cancel an in-progress root generation
func (c *Core) GenerateRootCancel() error {
c.stateLock.RLock()
defer c.stateLock.RUnlock()
if c.sealed {
return ErrSealed
}
if c.standby {
return ErrStandby
}
c.generateRootLock.Lock()
defer c.generateRootLock.Unlock()
// Clear any progress or config
c.generateRootConfig = nil
c.generateRootProgress = nil
return nil
}