forked from moby/swarmkit
/
keyreadwriter.go
388 lines (335 loc) · 11.1 KB
/
keyreadwriter.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
package ca
import (
cryptorand "crypto/rand"
"crypto/x509"
"encoding/pem"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"crypto/tls"
"github.com/docker/swarmkit/ioutils"
"github.com/pkg/errors"
)
const (
// keyPerms are the permissions used to write the TLS keys
keyPerms = 0600
// certPerms are the permissions used to write TLS certificates
certPerms = 0644
// versionHeader is the TLS PEM key header that contains the KEK version
versionHeader = "kek-version"
)
// PEMKeyHeaders is something that needs to know about PEM headers when reading
// or writing TLS keys.
type PEMKeyHeaders interface {
// UnmarshalHeaders loads the headers map given the current KEK
UnmarshalHeaders(map[string]string, KEKData) (PEMKeyHeaders, error)
// MarshalHeaders returns a header map given the current KEK
MarshalHeaders(KEKData) (map[string]string, error)
// UpdateKEK may get a new PEMKeyHeaders if the KEK changes
UpdateKEK(KEKData, KEKData) PEMKeyHeaders
}
// KeyReader reads a TLS cert and key from disk
type KeyReader interface {
Read() ([]byte, []byte, error)
Target() string
}
// KeyWriter writes a TLS key and cert to disk
type KeyWriter interface {
Write([]byte, []byte, *KEKData) error
ViewAndUpdateHeaders(func(PEMKeyHeaders) (PEMKeyHeaders, error)) error
ViewAndRotateKEK(func(KEKData, PEMKeyHeaders) (KEKData, PEMKeyHeaders, error)) error
GetCurrentState() (PEMKeyHeaders, KEKData)
Target() string
}
// KEKData provides an optional update to the kek when writing. The structure
// is needed so that we can tell the difference between "do not encrypt anymore"
// and there is "no update".
type KEKData struct {
KEK []byte
Version uint64
}
// ErrInvalidKEK means that we cannot decrypt the TLS key for some reason
type ErrInvalidKEK struct {
Wrapped error
}
func (e ErrInvalidKEK) Error() string {
return e.Wrapped.Error()
}
// KeyReadWriter is an object that knows how to read and write TLS keys and certs to disk,
// optionally encrypted and optionally updating PEM headers.
type KeyReadWriter struct {
mu sync.Mutex
kekData KEKData
paths CertPaths
headersObj PEMKeyHeaders
}
// NewKeyReadWriter creates a new KeyReadWriter
func NewKeyReadWriter(paths CertPaths, kek []byte, headersObj PEMKeyHeaders) *KeyReadWriter {
return &KeyReadWriter{
kekData: KEKData{KEK: kek},
paths: paths,
headersObj: headersObj,
}
}
// Migrate checks to see if a temporary key file exists. Older versions of
// swarmkit wrote temporary keys instead of temporary certificates, so
// migrate that temporary key if it exists. We want to write temporary certificates,
// instead of temporary keys, because we may need to periodically re-encrypt the
// keys and modify the headers, and it's easier to have a single canonical key
// location than two possible key locations.
func (k *KeyReadWriter) Migrate() error {
tmpPaths := k.genTempPaths()
keyBytes, err := ioutil.ReadFile(tmpPaths.Key)
if err != nil {
return nil // no key? no migration
}
// it does exist - no need to decrypt, because previous versions of swarmkit
// which supported this temporary key did not support encrypting TLS keys
cert, err := ioutil.ReadFile(k.paths.Cert)
if err != nil {
return os.RemoveAll(tmpPaths.Key) // no cert? no migration
}
// nope, this does not match the cert
if _, err = tls.X509KeyPair(cert, keyBytes); err != nil {
return os.RemoveAll(tmpPaths.Key)
}
return os.Rename(tmpPaths.Key, k.paths.Key)
}
// Read will read a TLS cert and key from the given paths
func (k *KeyReadWriter) Read() ([]byte, []byte, error) {
k.mu.Lock()
defer k.mu.Unlock()
keyBlock, err := k.readKey()
if err != nil {
return nil, nil, err
}
if version, ok := keyBlock.Headers[versionHeader]; ok {
if versionInt, err := strconv.ParseUint(version, 10, 64); err == nil {
k.kekData.Version = versionInt
}
}
delete(keyBlock.Headers, versionHeader)
if k.headersObj != nil {
newHeaders, err := k.headersObj.UnmarshalHeaders(keyBlock.Headers, k.kekData)
if err != nil {
return nil, nil, errors.Wrap(err, "unable to read TLS key headers")
}
k.headersObj = newHeaders
}
keyBytes := pem.EncodeToMemory(keyBlock)
cert, err := ioutil.ReadFile(k.paths.Cert)
// The cert is written to a temporary file first, then the key, and then
// the cert gets renamed - so, if interrupted, it's possible to end up with
// a cert that only exists in the temporary location.
switch {
case err == nil:
_, err = tls.X509KeyPair(cert, keyBytes)
case os.IsNotExist(err): //continue to try temp location
break
default:
return nil, nil, err
}
// either the cert doesn't exist, or it doesn't match the key - try the temp file, if it exists
if err != nil {
var tempErr error
tmpPaths := k.genTempPaths()
cert, tempErr = ioutil.ReadFile(tmpPaths.Cert)
if tempErr != nil {
return nil, nil, err // return the original error
}
if _, tempErr := tls.X509KeyPair(cert, keyBytes); tempErr != nil {
os.RemoveAll(tmpPaths.Cert) // nope, it doesn't match either - remove and return the original error
return nil, nil, err
}
os.Rename(tmpPaths.Cert, k.paths.Cert) // try to move the temp cert back to the regular location
}
return cert, keyBytes, nil
}
// ViewAndRotateKEK re-encrypts the key with a new KEK
func (k *KeyReadWriter) ViewAndRotateKEK(cb func(KEKData, PEMKeyHeaders) (KEKData, PEMKeyHeaders, error)) error {
k.mu.Lock()
defer k.mu.Unlock()
updatedKEK, updatedHeaderObj, err := cb(k.kekData, k.headersObj)
if err != nil {
return err
}
keyBlock, err := k.readKey()
if err != nil {
return err
}
if err := k.writeKey(keyBlock, updatedKEK, updatedHeaderObj); err != nil {
return err
}
return nil
}
// ViewAndUpdateHeaders updates the header manager, and updates any headers on the existing key
func (k *KeyReadWriter) ViewAndUpdateHeaders(cb func(PEMKeyHeaders) (PEMKeyHeaders, error)) error {
k.mu.Lock()
defer k.mu.Unlock()
pkh, err := cb(k.headersObj)
if err != nil {
return err
}
keyBlock, err := k.readKeyblock()
if err != nil {
return err
}
headers := make(map[string]string)
if pkh != nil {
var err error
headers, err = pkh.MarshalHeaders(k.kekData)
if err != nil {
return err
}
}
// we WANT any original encryption headers
for key, value := range keyBlock.Headers {
normalizedKey := strings.TrimSpace(strings.ToLower(key))
if normalizedKey == "proc-type" || normalizedKey == "dek-info" {
headers[key] = value
}
}
headers[versionHeader] = strconv.FormatUint(k.kekData.Version, 10)
keyBlock.Headers = headers
if err = ioutils.AtomicWriteFile(k.paths.Key, pem.EncodeToMemory(keyBlock), keyPerms); err != nil {
return err
}
k.headersObj = pkh
return nil
}
// GetCurrentState returns the current KEK data, including version
func (k *KeyReadWriter) GetCurrentState() (PEMKeyHeaders, KEKData) {
k.mu.Lock()
defer k.mu.Unlock()
return k.headersObj, k.kekData
}
// Write attempts write a cert and key to text. This can also optionally update
// the KEK while writing, if an updated KEK is provided. If the pointer to the
// update KEK is nil, then we don't update. If the updated KEK itself is nil,
// then we update the KEK to be nil (data should be unencrypted).
func (k *KeyReadWriter) Write(certBytes, plaintextKeyBytes []byte, kekData *KEKData) error {
k.mu.Lock()
defer k.mu.Unlock()
// current assumption is that the cert and key will be in the same directory
if err := os.MkdirAll(filepath.Dir(k.paths.Key), 0755); err != nil {
return err
}
// Ensure that we will have a keypair on disk at all times by writing the cert to a
// temp path first. This is because we want to have only a single copy of the key
// for rotation and header modification.
tmpPaths := k.genTempPaths()
if err := ioutils.AtomicWriteFile(tmpPaths.Cert, certBytes, certPerms); err != nil {
return err
}
keyBlock, _ := pem.Decode(plaintextKeyBytes)
if keyBlock == nil {
return errors.New("invalid PEM-encoded private key")
}
if kekData == nil {
kekData = &k.kekData
}
pkh := k.headersObj
if k.headersObj != nil {
pkh = k.headersObj.UpdateKEK(k.kekData, *kekData)
}
if err := k.writeKey(keyBlock, *kekData, pkh); err != nil {
return err
}
return os.Rename(tmpPaths.Cert, k.paths.Cert)
}
func (k *KeyReadWriter) genTempPaths() CertPaths {
return CertPaths{
Key: filepath.Join(filepath.Dir(k.paths.Key), "."+filepath.Base(k.paths.Key)),
Cert: filepath.Join(filepath.Dir(k.paths.Cert), "."+filepath.Base(k.paths.Cert)),
}
}
// Target returns a string representation of this KeyReadWriter, namely where
// it is writing to
func (k *KeyReadWriter) Target() string {
return k.paths.Cert
}
func (k *KeyReadWriter) readKeyblock() (*pem.Block, error) {
key, err := ioutil.ReadFile(k.paths.Key)
if err != nil {
return nil, err
}
// Decode the PEM private key
keyBlock, _ := pem.Decode(key)
if keyBlock == nil {
return nil, errors.New("invalid PEM-encoded private key")
}
return keyBlock, nil
}
// readKey returns the decrypted key pem bytes, and enforces the KEK if applicable
// (writes it back with the correct encryption if it is not correctly encrypted)
func (k *KeyReadWriter) readKey() (*pem.Block, error) {
keyBlock, err := k.readKeyblock()
if err != nil {
return nil, err
}
if !x509.IsEncryptedPEMBlock(keyBlock) {
return keyBlock, nil
}
// If it's encrypted, we can't read without a passphrase (we're assuming
// empty passphrases are invalid)
if k.kekData.KEK == nil {
return nil, ErrInvalidKEK{Wrapped: x509.IncorrectPasswordError}
}
derBytes, err := x509.DecryptPEMBlock(keyBlock, k.kekData.KEK)
if err != nil {
return nil, ErrInvalidKEK{Wrapped: err}
}
// remove encryption PEM headers
headers := make(map[string]string)
mergePEMHeaders(headers, keyBlock.Headers)
return &pem.Block{
Type: keyBlock.Type, // the key type doesn't change
Bytes: derBytes,
Headers: headers,
}, nil
}
// writeKey takes an unencrypted keyblock and, if the kek is not nil, encrypts it before
// writing it to disk. If the kek is nil, writes it to disk unencrypted.
func (k *KeyReadWriter) writeKey(keyBlock *pem.Block, kekData KEKData, pkh PEMKeyHeaders) error {
if kekData.KEK != nil {
encryptedPEMBlock, err := x509.EncryptPEMBlock(cryptorand.Reader,
keyBlock.Type,
keyBlock.Bytes,
kekData.KEK,
x509.PEMCipherAES256)
if err != nil {
return err
}
if encryptedPEMBlock.Headers == nil {
return errors.New("unable to encrypt key - invalid PEM file produced")
}
keyBlock = encryptedPEMBlock
}
if pkh != nil {
headers, err := pkh.MarshalHeaders(kekData)
if err != nil {
return err
}
mergePEMHeaders(keyBlock.Headers, headers)
}
keyBlock.Headers[versionHeader] = strconv.FormatUint(kekData.Version, 10)
if err := ioutils.AtomicWriteFile(k.paths.Key, pem.EncodeToMemory(keyBlock), keyPerms); err != nil {
return err
}
k.kekData = kekData
k.headersObj = pkh
return nil
}
// merges one set of PEM headers onto another, excepting for key encryption value
// "proc-type" and "dek-info"
func mergePEMHeaders(original, newSet map[string]string) {
for key, value := range newSet {
normalizedKey := strings.TrimSpace(strings.ToLower(key))
if normalizedKey != "proc-type" && normalizedKey != "dek-info" {
original[key] = value
}
}
}