forked from kubevirt/containerized-data-importer
/
keystore.go
444 lines (359 loc) · 13.1 KB
/
keystore.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
/*
Copyright 2018 The CDI Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package keys
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"io/ioutil"
"path/filepath"
"github.com/pkg/errors"
v1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/util/cert"
"k8s.io/klog"
"kubevirt.io/containerized-data-importer/pkg/common"
"kubevirt.io/containerized-data-importer/pkg/operator"
"kubevirt.io/containerized-data-importer/pkg/util/cert/triple"
)
const (
// KeyStoreTLSKeyFile is the key in a secret containing the TLS key
KeyStoreTLSKeyFile = "tls.key"
// KeyStoreTLSCertFile is the key in a secret containing the TLS cert
KeyStoreTLSCertFile = "tls.crt"
// KeyStoreTLSCAFile is the key in a secret containing a CA cert
KeyStoreTLSCAFile = "ca.crt"
// KeyStorePrivateKeyFile is the key in a secret containing an RSA private key
KeyStorePrivateKeyFile = "id_rsa"
// KeyStorePublicKeyFile is the key in a secret containing an RSA publis key
KeyStorePublicKeyFile = "id_rsa.pub"
)
// KeyPairAndCert holds a KeyPair and optional CA
// In the case of a server key pair, the CA is the CA that signed client certs
// In the case of a client key pair, the CA is the CA that signed the server cert
type KeyPairAndCert struct {
KeyPair triple.KeyPair
CACert *x509.Certificate
}
// KeyPairAndCertBytes contains the PEM encoded key data
type KeyPairAndCertBytes struct {
PrivateKey []byte
Cert []byte
CACert []byte
}
// GetOrCreateCA will get the CA KeyPair, creating it if necessary
func GetOrCreateCA(client kubernetes.Interface, namespace, secretName, caName string) (*triple.KeyPair, error) {
keyPairAndCert, err := GetKeyPairAndCert(client, namespace, secretName)
if err != nil {
return nil, errors.Wrap(err, "Error getting CA")
}
if keyPairAndCert != nil {
klog.Infof("Retrieved CA key/cert %s from kubernetes", caName)
return &keyPairAndCert.KeyPair, nil
}
klog.Infof("Recreating CA %s", caName)
keyPair, err := triple.NewCA(caName)
if err != nil {
return nil, errors.Wrap(err, "Error creating CA")
}
exists, err := SaveKeyPairAndCert(client, namespace, secretName, &KeyPairAndCert{*keyPair, nil}, nil)
if !exists && err != nil {
return nil, errors.Wrap(err, "Error saving CA")
}
// do another get
// this should be very unlikely to hit code path
if exists {
keyPairAndCert, err = GetKeyPairAndCert(client, namespace, secretName)
if keyPairAndCert == nil || err != nil {
return nil, errors.Wrap(err, "Error getting CA second time around")
}
keyPair = &keyPairAndCert.KeyPair
}
return keyPair, nil
}
// GetOrCreateServerKeyPairAndCert creates secret for an upload server
func GetOrCreateServerKeyPairAndCert(client kubernetes.Interface,
namespace,
secretName string,
caKeyPair *triple.KeyPair,
clientCACert *x509.Certificate,
commonName string,
serviceName string,
owner *metav1.OwnerReference) (*KeyPairAndCert, error) {
keyPairAndCert, err := GetKeyPairAndCert(client, namespace, secretName)
if err != nil {
return nil, errors.Wrap(err, "Error getting server cert")
}
if keyPairAndCert != nil {
klog.Infof("Retrieved server key/cert %s from kubernetes", commonName)
return keyPairAndCert, nil
}
keyPair, err := triple.NewServerKeyPair(caKeyPair, commonName, serviceName, namespace, "cluster.local", []string{}, []string{})
if err != nil {
return nil, errors.Wrap(err, "Error creating server key pair")
}
keyPairAndCert = &KeyPairAndCert{*keyPair, clientCACert}
exists, err := SaveKeyPairAndCert(client, namespace, secretName, keyPairAndCert, owner)
if !exists && err != nil {
return nil, errors.Wrap(err, "Error saving server key pair")
}
if exists {
// race condition
return GetKeyPairAndCert(client, namespace, secretName)
}
return keyPairAndCert, nil
}
// GetOrCreateClientKeyPairAndCert creates a secret for upload proxy
func GetOrCreateClientKeyPairAndCert(client kubernetes.Interface,
namespace, secretName string,
caKeyPair *triple.KeyPair,
caCert *x509.Certificate,
commonName string,
organizations []string,
owner *metav1.OwnerReference) (*KeyPairAndCert, error) {
keyPairAndCert, err := GetKeyPairAndCert(client, namespace, secretName)
if err != nil {
return nil, errors.Wrap(err, "Error getting client cert")
}
if keyPairAndCert != nil {
klog.Infof("Retrieved client key/cert %s from kubernetes", commonName)
return keyPairAndCert, nil
}
keyPair, err := triple.NewClientKeyPair(caKeyPair, commonName, organizations)
if err != nil {
return nil, errors.Wrap(err, "Error creating client key pair")
}
keyPairAndCert = &KeyPairAndCert{*keyPair, caCert}
exists, err := SaveKeyPairAndCert(client, namespace, secretName, keyPairAndCert, owner)
if !exists && err != nil {
return nil, errors.Wrap(err, "Error saving server key pair")
}
if exists {
// race condition
return GetKeyPairAndCert(client, namespace, secretName)
}
return keyPairAndCert, nil
}
// GetKeyPairAndCert will return the secret data if it exists
func GetKeyPairAndCert(client kubernetes.Interface, namespace, secretName string) (*KeyPairAndCert, error) {
var keyPairAndCert KeyPairAndCert
keyPairAndCertBytes, err := GetKeyPairAndCertBytes(client, namespace, secretName)
if err != nil {
return nil, errors.Wrap(err, "Error retrieving key bytes")
}
if keyPairAndCertBytes == nil {
return nil, nil
}
key, err := parsePrivateKey(keyPairAndCertBytes.PrivateKey)
if err != nil {
return nil, errors.Wrap(err, "Error parsing private key")
}
keyPairAndCert.KeyPair.Key = key
certs, err := cert.ParseCertsPEM(keyPairAndCertBytes.Cert)
if err != nil || len(certs) != 1 {
return nil, errors.Errorf("Cert parse error %s, %d", err, len(certs))
}
keyPairAndCert.KeyPair.Cert = certs[0]
if keyPairAndCertBytes.CACert != nil {
certs, err := cert.ParseCertsPEM(keyPairAndCertBytes.CACert)
if err != nil || len(certs) != 1 {
return nil, errors.Errorf("CA cert parse error %s, %d", err, len(certs))
}
keyPairAndCert.CACert = certs[0]
}
return &keyPairAndCert, nil
}
// GetKeyPairAndCertBytes returns the raw bytes stored in the secret
func GetKeyPairAndCertBytes(client kubernetes.Interface, namespace, secretName string) (*KeyPairAndCertBytes, error) {
var keyPairAndCertBytes KeyPairAndCertBytes
secret, err := client.CoreV1().Secrets(namespace).Get(secretName, metav1.GetOptions{})
if err != nil {
if k8serrors.IsNotFound(err) {
return nil, nil
}
return nil, errors.Wrap(err, "Error getting secret")
}
bytes, ok := secret.Data[KeyStoreTLSKeyFile]
if !ok {
return nil, errors.Errorf("Private key missing from secret")
}
keyPairAndCertBytes.PrivateKey = bytes
if bytes, ok = secret.Data[KeyStoreTLSCertFile]; !ok {
return nil, errors.Errorf("Cert missing from secret")
}
keyPairAndCertBytes.Cert = bytes
// okay if this doesn't exist
if bytes, ok = secret.Data[KeyStoreTLSCAFile]; ok {
keyPairAndCertBytes.CACert = bytes
}
return &keyPairAndCertBytes, nil
}
// SaveKeyPairAndCert saves a private key, cert, and maybe a ca cert to kubernetes
func SaveKeyPairAndCert(client kubernetes.Interface, namespace, secretName string, keyPairAndCA *KeyPairAndCert, owner *metav1.OwnerReference) (bool, error) {
secret, err := newTLSSecret(client, namespace, secretName, keyPairAndCA, owner)
if err != nil {
return false, errors.Wrap(err, "Unable to save KeyPairAndCert")
}
_, err = client.CoreV1().Secrets(namespace).Create(secret)
if err != nil {
return k8serrors.IsAlreadyExists(err), errors.Wrap(err, "Error creating cert")
}
return false, nil
}
// newTLSSecret returns a new TLS secret from objects
func newTLSSecret(client kubernetes.Interface,
namespace, secretName string,
keyPairAndCA *KeyPairAndCert,
owner *metav1.OwnerReference) (*v1.Secret, error) {
var privateKeyBytes, certBytes, caCertBytes []byte
privateKeyBytes = cert.EncodePrivateKeyPEM(keyPairAndCA.KeyPair.Key)
certBytes = cert.EncodeCertPEM(keyPairAndCA.KeyPair.Cert)
if keyPairAndCA.CACert != nil {
caCertBytes = cert.EncodeCertPEM(keyPairAndCA.CACert)
}
secret, err := newTLSSecretFromBytes(client, namespace, secretName, privateKeyBytes, certBytes, caCertBytes, owner)
if err != nil {
return nil, errors.Wrap(err, "Unable to create secret")
}
return secret, nil
}
// newTLSSecretFromBytes returns a new TLS secret from bytes
func newTLSSecretFromBytes(client kubernetes.Interface,
namespace, secretName string,
privateKeyBytes, certBytes, caCertBytes []byte,
owner *metav1.OwnerReference) (*v1.Secret, error) {
data := map[string][]byte{
KeyStoreTLSKeyFile: privateKeyBytes,
KeyStoreTLSCertFile: certBytes,
}
if caCertBytes != nil {
data[KeyStoreTLSCAFile] = caCertBytes
}
secret, err := newSecret(client, namespace, secretName, data, owner)
if err != nil {
return nil, errors.Wrap(err, "Unable to create secret")
}
return secret, nil
}
// GetOrCreatePrivateKey gets or creates a private key secret
func GetOrCreatePrivateKey(client kubernetes.Interface, namespace, secretName string) (*rsa.PrivateKey, error) {
secret, err := client.CoreV1().Secrets(namespace).Get(secretName, metav1.GetOptions{})
if err != nil {
if !k8serrors.IsNotFound(err) {
return nil, errors.Wrap(err, "Error getting secret")
}
// let's create the secret
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, errors.Wrap(err, "Error generating key")
}
secret, err = newPrivateKeySecret(client, namespace, secretName, privateKey)
if err != nil {
return nil, errors.Wrap(err, "Error creating prvate key secret")
}
secret, err = client.CoreV1().Secrets(namespace).Create(secret)
if err != nil {
if !k8serrors.IsAlreadyExists(err) {
return nil, errors.Wrap(err, "Error creating secret")
}
secret, err = client.CoreV1().Secrets(namespace).Get(secretName, metav1.GetOptions{})
if err != nil {
return nil, errors.Wrap(err, "Error getting secret, second time")
}
}
}
bytes, ok := secret.Data[KeyStorePrivateKeyFile]
if !ok {
return nil, errors.Wrap(err, "Secret missing private key")
}
return parsePrivateKey(bytes)
}
// newPrivateKeySecret returns a new private key secret
func newPrivateKeySecret(client kubernetes.Interface, namespace, secretName string, privateKey *rsa.PrivateKey) (*v1.Secret, error) {
privateKeyBytes := cert.EncodePrivateKeyPEM(privateKey)
publicKeyBytes, err := cert.EncodePublicKeyPEM(&privateKey.PublicKey)
if err != nil {
return nil, errors.Wrap(err, "Error encoding public key")
}
data := map[string][]byte{
KeyStorePrivateKeyFile: privateKeyBytes,
KeyStorePublicKeyFile: publicKeyBytes,
}
secret, err := newSecret(client, namespace, secretName, data, nil)
if err != nil {
return nil, errors.Wrap(err, "Unable to create PrivateKeySecret")
}
return secret, nil
}
func newSecret(client kubernetes.Interface, namespace, secretName string, data map[string][]byte, owner *metav1.OwnerReference) (*v1.Secret, error) {
secret := &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: secretName,
Namespace: namespace,
Labels: map[string]string{
common.CDIComponentLabel: "keystore",
},
},
Type: "Opaque",
Data: data,
}
if owner == nil {
err := operator.SetOwner(client, secret)
if err != nil {
return nil, errors.Wrap(err, "Error setting secret owner ref")
}
} else {
secret.OwnerReferences = []metav1.OwnerReference{*owner}
}
return secret, nil
}
func parsePrivateKey(bytes []byte) (*rsa.PrivateKey, error) {
obj, err := cert.ParsePrivateKeyPEM(bytes)
if err != nil {
return nil, errors.Wrap(err, "Error parsing secret")
}
key, ok := obj.(*rsa.PrivateKey)
if !ok {
return nil, errors.New("Invalid pem format")
}
return key, nil
}
// GenerateSelfSignedCert generates a self signed certificate keyFile, certFile pair to be passed to http.ListenAndServeTLS
// The first return value is the keyFile name, the second the certFile name
// The caller is responsible for creating a writeable directory and cleaning up the generated files afterwards.
func GenerateSelfSignedCert(certsDirectory string, name string, namespace string) (string, string, error) {
// Generic self signed CA.
caKeyPair, _ := triple.NewCA("cdi.kubevirt.io")
keyPair, _ := triple.NewServerKeyPair(
caKeyPair,
name+"."+namespace+".pod.cluster.local",
name,
namespace,
"cluster.local",
[]string{},
[]string{},
)
keyFile := filepath.Join(certsDirectory, "key.pem")
certFile := filepath.Join(certsDirectory, "cert.pem")
err := ioutil.WriteFile(keyFile, cert.EncodePrivateKeyPEM(keyPair.Key), 0600)
if err != nil {
return "", "", err
}
err = ioutil.WriteFile(certFile, cert.EncodeCertPEM(keyPair.Cert), 0600)
if err != nil {
return "", "", err
}
return keyFile, certFile, nil
}