This repository was archived by the owner on Jan 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsecrets.go
381 lines (301 loc) · 10.3 KB
/
secrets.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
package secrets
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/binary"
"errors"
"fmt"
"strings"
)
var ErrNotFound = fmt.Errorf("secret not found")
// SecretStorage is implemented by a provider if the provider gives a mechanism for storing arbitrary secrets.
type SecretStorage interface {
// Use secrets when you don't want to store the underlying data, eg secret tokens
SetSecret(name string, secret []byte) error
GetSecret(name string) (secret []byte, err error)
}
var SecretStorageProviderKinds = []string{
"vault",
"awsssm",
"awssecretsmanager",
"kubernetes",
"env",
"file",
"plaintext",
}
// SymmetricKeyProvider is implemented by a provider that provides encryption-as-a-service.
// Its use is opinionated about the provider in the following ways:
// - A root key will be created or referenced and never leaves the provider
// - the root key will be used to encrypt a "data key"
// - the data key is given to the client (us) for encrypting data
// - the client shall store only the encrypted data key
// - the client shall remove the plaintext data key from memory as soon as it is no longer needed
// - the client will request the data key be decrypted by the provider if it is needed subsequently.
// In this way the encryption-as-a-service provider scales to unlimited data sizes without needing to transfer the data to the remote service for symmetric encryption/decryption.
// To rotate root keys, generate new ones periodically and reencrypt data you touch with the new root. This can either be done all at once or gradually over time. Old root keys are out of circulation when no data exists that points to them.
type SymmetricKeyProvider interface {
// GenerateDataKey makes a data key from a root key id: if "", a root key is created. It is okay to generate many data keys.
GenerateDataKey(rootKeyID string) (*SymmetricKey, error)
// DecryptDataKey decrypts the encrypted data key on the provider given a root key id
DecryptDataKey(rootKeyID string, keyData []byte) (*SymmetricKey, error)
}
var SymmetricKeyProviderKinds = []string{
"vault",
"awskms",
"native",
}
type SymmetricKey struct {
unencrypted []byte `json:"-"` // the unencrypted data key. Retrieved with DecryptDataKey or set by GenerateDataKey. This field *MUST NOT* be persisted.
Encrypted []byte `json:"key"` // the encrypted data key. To be stored by caller.
Algorithm string `json:"alg"` // Algorithm key used for encryption. To be stored by caller.
RootKeyID string `json:"rkid"` // ID of the root key used to encrypt the data key on the provider. To be stored by caller.
}
type encryptedPayload struct {
Ciphertext []byte // base64 encoded
Algorithm string // name of the algorithm used to encrypt the Ciphertext
KeyID []byte // A unique identifier for the key used. Could be checksum or a version number
RootKeyID string // id of the root key the Key field is encrypted with
Nonce []byte // must be crypto-random unique every time, size = block size
}
// cryptoRandRead is a safe read from crypto/rand, checking errors and number of bytes read, erroring if we don't get enough
func cryptoRandRead(length int) ([]byte, error) {
b := make([]byte, length)
i, err := rand.Read(b)
if err != nil {
return nil, fmt.Errorf("crypto/rand read: %w", err)
}
if i != length {
return nil, fmt.Errorf("could not read %d random characters from crypto/rand, only got %d", length, i)
}
return b, nil
}
func secretKindAndName(secret string) (kind string, name string, err error) {
if !strings.Contains(secret, ":") {
return "plaintext", secret, nil
}
parts := strings.SplitN(secret, ":", 2)
if len(parts) < 2 {
return "", "", fmt.Errorf("unexpected secret provider format %q. Expecting <kind>:<secret name>, eg env:ACCESS_TOKEN", name)
}
kind = parts[0]
name = parts[1]
return kind, name, nil
}
// GetSecret implements the secret definition scheme for Infra.
// eg plaintext:pass123, or kubernetes:infra-okta/clientSecret
// it's an abstraction around all secret providers
func GetSecret(name string, storage map[string]SecretStorage) (string, error) {
b, err := GetSecretRaw(name, storage)
if err != nil {
return "", fmt.Errorf("getting secret: %w", err)
}
if b == nil {
return "", nil
}
return string(b), nil
}
func GetSecretRaw(name string, storage map[string]SecretStorage) ([]byte, error) {
kind, name, err := secretKindAndName(name)
if err != nil {
return nil, err
}
secretProvider, found := storage[kind]
if !found {
return nil, fmt.Errorf("provider %q not found for field %q", kind, name)
}
return secretProvider.GetSecret(name)
}
func SetSecret(name, value string, storage map[string]SecretStorage) error {
kind, name, err := secretKindAndName(name)
if err != nil {
return err
}
secretProvider, found := storage[kind]
if !found {
return fmt.Errorf("provider %q not found for field %q", kind, name)
}
err = secretProvider.SetSecret(name, []byte(value))
if err != nil {
return fmt.Errorf("setting secret: %w", err)
}
return nil
}
// SealRaw encrypts plaintext with a decrypted data key and returns it in a raw binary format
func SealRaw(key *SymmetricKey, plain []byte) ([]byte, error) {
if len(key.unencrypted) == 0 {
return nil, errors.New("missing key")
}
if len(key.unencrypted) != 32 {
return nil, errors.New("expected 256 bit key size")
}
blk, err := aes.NewCipher(key.unencrypted)
if err != nil {
return nil, err
}
aesgcm, err := cipher.NewGCM(blk)
if err != nil {
return nil, err
}
nonce, err := cryptoRandRead(aesgcm.NonceSize())
if err != nil {
return nil, fmt.Errorf("generating nonce: %w", err)
}
encrypted := aesgcm.Seal(nil, nonce, plain, nil)
keyID, err := checksum(key.Encrypted)
if err != nil {
return nil, err
}
payload := encryptedPayload{
KeyID: keyID,
Ciphertext: encrypted,
Algorithm: key.Algorithm,
RootKeyID: key.RootKeyID,
Nonce: nonce,
}
marshalledPayload, err := marshalPayload(&payload)
if err != nil {
return nil, err
}
return marshalledPayload, nil
}
// Seal encrypts plaintext with a decrypted data key and returns it in base64
func Seal(key *SymmetricKey, plain []byte) ([]byte, error) {
marshalled, err := SealRaw(key, plain)
if err != nil {
return nil, err
}
encoded := make([]byte, base64.RawStdEncoding.EncodedLen(len(marshalled)))
base64.RawStdEncoding.Encode(encoded, marshalled)
return encoded, nil
}
// UnsealRaw decrypts ciphertext with a decrypted data key and returns a raw binary format
func UnsealRaw(key *SymmetricKey, encrypted []byte) ([]byte, error) {
if len(key.unencrypted) == 0 {
return nil, errors.New("missing key")
}
payload := &encryptedPayload{}
if err := unmarshalPayload(encrypted, payload); err != nil {
return nil, fmt.Errorf("unmarshalling: %w", err)
}
ck, err := checksum(key.Encrypted)
if err != nil {
return nil, err
}
if !bytes.Equal(ck, payload.KeyID) {
return nil, fmt.Errorf("supplied key cannot decrypt this message; wrong key was used")
}
blk, err := aes.NewCipher(key.unencrypted)
if err != nil {
return nil, fmt.Errorf("creating cipher: %w", err)
}
aesgcm, err := cipher.NewGCM(blk)
if err != nil {
return nil, fmt.Errorf("gcm: %w", err)
}
plaintext, err := aesgcm.Open(nil, payload.Nonce, payload.Ciphertext, nil)
if err != nil {
return nil, fmt.Errorf("opening seal: %w", err)
}
return plaintext, nil
}
// Unseal decrypts base64-encoded ciphertext with a decrypted data key
func Unseal(key *SymmetricKey, encoded []byte) ([]byte, error) {
encryptedPayload := make([]byte, base64.RawStdEncoding.DecodedLen(len(encoded)))
_, err := base64.RawStdEncoding.Decode(encryptedPayload, encoded)
if err != nil {
return nil, fmt.Errorf("decoding payload: %w", err)
}
return UnsealRaw(key, encryptedPayload)
}
func checksum(b []byte) ([]byte, error) {
keyIDChecksum := sha256.New()
ln, err := keyIDChecksum.Write(b)
if err != nil {
return nil, fmt.Errorf("creating checksum: %w", err)
}
if ln != len(b) {
return nil, fmt.Errorf("checksum write len")
}
return keyIDChecksum.Sum(nil)[:4], nil
}
func unmarshalPayload(mp []byte, p *encryptedPayload) error {
b := bytes.NewBuffer(mp)
var ln uint32
if err := binary.Read(b, binary.BigEndian, &ln); err != nil {
return err
}
p.Ciphertext = make([]byte, ln)
if err := binary.Read(b, binary.BigEndian, &p.Ciphertext); err != nil {
return err
}
var length uint8
if err := binary.Read(b, binary.BigEndian, &length); err != nil {
return err
}
alg := make([]byte, length)
if err := binary.Read(b, binary.BigEndian, &alg); err != nil {
return err
}
p.Algorithm = string(alg)
if err := binary.Read(b, binary.BigEndian, &length); err != nil {
return err
}
p.KeyID = make([]byte, length)
if err := binary.Read(b, binary.BigEndian, &p.KeyID); err != nil {
return err
}
if err := binary.Read(b, binary.BigEndian, &length); err != nil {
return err
}
rootKeyID := make([]byte, length)
if err := binary.Read(b, binary.BigEndian, &rootKeyID); err != nil {
return err
}
p.RootKeyID = string(rootKeyID)
if err := binary.Read(b, binary.BigEndian, &length); err != nil {
return err
}
p.Nonce = make([]byte, length)
if err := binary.Read(b, binary.BigEndian, &p.Nonce); err != nil {
return err
}
return nil
}
func marshalPayload(p *encryptedPayload) ([]byte, error) {
b := bytes.NewBuffer(nil)
if err := binary.Write(b, binary.BigEndian, uint32(len(p.Ciphertext))); err != nil {
return nil, err
}
if err := binary.Write(b, binary.BigEndian, p.Ciphertext); err != nil {
return nil, err
}
if err := binary.Write(b, binary.BigEndian, uint8(len(p.Algorithm))); err != nil {
return nil, err
}
if err := binary.Write(b, binary.BigEndian, []byte(p.Algorithm)); err != nil {
return nil, err
}
if err := binary.Write(b, binary.BigEndian, uint8(len(p.KeyID))); err != nil {
return nil, err
}
if err := binary.Write(b, binary.BigEndian, p.KeyID); err != nil {
return nil, err
}
if err := binary.Write(b, binary.BigEndian, uint8(len(p.RootKeyID))); err != nil {
return nil, err
}
if err := binary.Write(b, binary.BigEndian, []byte(p.RootKeyID)); err != nil {
return nil, err
}
if err := binary.Write(b, binary.BigEndian, uint8(len(p.Nonce))); err != nil {
return nil, err
}
if err := binary.Write(b, binary.BigEndian, p.Nonce); err != nil {
return nil, err
}
return b.Bytes(), nil
}