forked from kubernetes/kops
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vfs_castore.go
762 lines (636 loc) · 16.8 KB
/
vfs_castore.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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
package fi
import (
"bytes"
"crypto/md5"
crypto_rand "crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"fmt"
"github.com/golang/glog"
"golang.org/x/crypto/ssh"
"k8s.io/kops/util/pkg/vfs"
"math/big"
"os"
"strings"
"sync"
"time"
)
type VFSCAStore struct {
DryRun bool
basedir vfs.Path
mutex sync.Mutex
cacheCaCertificates *certificates
cacheCaPrivateKeys *privateKeys
}
var _ CAStore = &VFSCAStore{}
func NewVFSCAStore(basedir vfs.Path) CAStore {
c := &VFSCAStore{
basedir: basedir,
}
return c
}
func (s *VFSCAStore) VFSPath() vfs.Path {
return s.basedir
}
// Retrieves the CA keypair, generating a new keypair if not found
func (s *VFSCAStore) readCAKeypairs() (*certificates, *privateKeys, error) {
s.mutex.Lock()
defer s.mutex.Unlock()
if s.cacheCaPrivateKeys != nil {
return s.cacheCaCertificates, s.cacheCaPrivateKeys, nil
}
caCertificates, err := s.loadCertificates(s.buildCertificatePoolPath(CertificateId_CA))
if err != nil {
return nil, nil, err
}
var caPrivateKeys *privateKeys
if caCertificates != nil {
caPrivateKeys, err = s.loadPrivateKeys(s.buildPrivateKeyPoolPath(CertificateId_CA))
if err != nil {
return nil, nil, err
}
if caPrivateKeys == nil {
glog.Warningf("CA private key was not found; will generate new key")
//return nil, fmt.Errorf("error loading CA private key - key not found")
}
}
if caPrivateKeys == nil {
caCertificates, caPrivateKeys, err = s.generateCACertificate()
if err != nil {
return nil, nil, err
}
}
s.cacheCaCertificates = caCertificates
s.cacheCaPrivateKeys = caPrivateKeys
return s.cacheCaCertificates, s.cacheCaPrivateKeys, nil
}
// Creates and stores CA keypair
// Should be called with the mutex held, to prevent concurrent creation of different keys
func (c *VFSCAStore) generateCACertificate() (*certificates, *privateKeys, error) {
subject := &pkix.Name{
CommonName: "kubernetes",
}
serial := c.buildSerial()
template := &x509.Certificate{
Subject: *subject,
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
ExtKeyUsage: []x509.ExtKeyUsage{},
BasicConstraintsValid: true,
IsCA: true,
}
caRsaKey, err := rsa.GenerateKey(crypto_rand.Reader, 2048)
if err != nil {
return nil, nil, fmt.Errorf("error generating RSA private key: %v", err)
}
caPrivateKey := &PrivateKey{Key: caRsaKey}
caCertificate, err := SignNewCertificate(caPrivateKey, template, nil, nil)
if err != nil {
return nil, nil, err
}
keyPath := c.buildPrivateKeyPath(CertificateId_CA, serial)
err = c.storePrivateKey(caPrivateKey, keyPath)
if err != nil {
return nil, nil, err
}
// Make double-sure it round-trips
privateKeys, err := c.loadPrivateKeys(c.buildPrivateKeyPoolPath(CertificateId_CA))
if err != nil {
return nil, nil, err
}
if privateKeys == nil || privateKeys.primary != serial.String() {
return nil, nil, fmt.Errorf("failed to round-trip CA private key")
}
certPath := c.buildCertificatePath(CertificateId_CA, serial)
err = c.storeCertificate(caCertificate, certPath)
if err != nil {
return nil, nil, err
}
// Make double-sure it round-trips
certificates, err := c.loadCertificates(c.buildCertificatePoolPath(CertificateId_CA))
if err != nil {
return nil, nil, err
}
if certificates == nil || certificates.primary != serial.String() {
return nil, nil, fmt.Errorf("failed to round-trip CA certifiacate")
}
return certificates, privateKeys, nil
}
func (c *VFSCAStore) buildCertificatePoolPath(id string) vfs.Path {
return c.basedir.Join("issued", id)
}
func (c *VFSCAStore) buildCertificatePath(id string, serial *big.Int) vfs.Path {
return c.basedir.Join("issued", id, serial.String()+".crt")
}
func (c *VFSCAStore) buildPrivateKeyPoolPath(id string) vfs.Path {
return c.basedir.Join("private", id)
}
func (c *VFSCAStore) buildPrivateKeyPath(id string, serial *big.Int) vfs.Path {
return c.basedir.Join("private", id, serial.String()+".key")
}
type certificates struct {
certificates map[string]*Certificate
primary string
}
func (p *certificates) Primary() *Certificate {
if p.primary == "" {
return nil
}
return p.certificates[p.primary]
}
func (c *VFSCAStore) loadCertificates(p vfs.Path) (*certificates, error) {
files, err := p.ReadDir()
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
certs := &certificates{
certificates: make(map[string]*Certificate),
}
for _, f := range files {
cert, err := c.loadOneCertificate(f)
if err != nil {
return nil, fmt.Errorf("error loading certificate %q: %v", f, err)
}
name := f.Base()
name = strings.TrimSuffix(name, ".crt")
certs.certificates[name] = cert
}
if len(certs.certificates) == 0 {
return nil, nil
}
var primaryVersion *big.Int
for k := range certs.certificates {
version, ok := big.NewInt(0).SetString(k, 10)
if !ok {
glog.Warningf("Ignoring certificate with non-integer version: %q", k)
continue
}
if primaryVersion == nil || version.Cmp(primaryVersion) > 0 {
certs.primary = k
primaryVersion = version
}
}
return certs, nil
}
func (c *VFSCAStore) loadOneCertificate(p vfs.Path) (*Certificate, error) {
data, err := p.ReadFile()
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
cert, err := LoadPEMCertificate(data)
if err != nil {
return nil, err
}
if cert == nil {
return nil, nil
}
return cert, nil
}
func (c *VFSCAStore) Cert(id string) (*Certificate, error) {
cert, err := c.FindCert(id)
if err == nil && cert == nil {
if c.DryRun {
glog.Warningf("using empty certificate, because running with DryRun")
return &Certificate{}, err
}
return nil, fmt.Errorf("cannot find certificate %q", id)
}
return cert, err
}
func (c *VFSCAStore) CertificatePool(id string) (*CertificatePool, error) {
cert, err := c.FindCertificatePool(id)
if err == nil && cert == nil {
if c.DryRun {
glog.Warningf("using empty certificate, because running with DryRun")
return &CertificatePool{}, err
}
return nil, fmt.Errorf("cannot find certificate pool %q", id)
}
return cert, err
}
func (c *VFSCAStore) FindCert(id string) (*Certificate, error) {
var certs *certificates
if id == CertificateId_CA {
caCertificates, _, err := c.readCAKeypairs()
if err != nil {
return nil, err
}
certs = caCertificates
} else {
var err error
p := c.buildCertificatePoolPath(id)
certs, err = c.loadCertificates(p)
if err != nil {
return nil, err
}
}
var cert *Certificate
if certs != nil && certs.primary != "" {
cert = certs.certificates[certs.primary]
}
return cert, nil
}
func (c *VFSCAStore) FindCertificatePool(id string) (*CertificatePool, error) {
var certs *certificates
if id == CertificateId_CA {
caCertificates, _, err := c.readCAKeypairs()
if err != nil {
return nil, err
}
certs = caCertificates
} else {
var err error
p := c.buildCertificatePoolPath(id)
certs, err = c.loadCertificates(p)
if err != nil {
return nil, err
}
}
pool := &CertificatePool{}
if certs != nil {
pool.Primary = certs.Primary()
for k, cert := range certs.certificates {
if k == certs.primary {
continue
}
pool.Secondary = append(pool.Secondary, cert)
}
}
return pool, nil
}
func (c *VFSCAStore) List() ([]*KeystoreItem, error) {
var items []*KeystoreItem
{
baseDir := c.basedir.Join("issued")
files, err := baseDir.ReadTree()
if err != nil {
return nil, fmt.Errorf("error reading directory %q: %v", baseDir, err)
}
for _, f := range files {
relativePath, err := vfs.RelativePath(baseDir, f)
if err != nil {
return nil, err
}
tokens := strings.Split(relativePath, "/")
if len(tokens) != 2 {
glog.V(2).Infof("ignoring unexpected file in keystore: %q", f)
continue
}
item := &KeystoreItem{
Name: tokens[0],
Id: strings.TrimSuffix(tokens[1], ".crt"),
Type: SecretTypeKeypair,
}
items = append(items, item)
}
}
{
baseDir := c.basedir.Join("ssh", "public")
files, err := baseDir.ReadTree()
if err != nil {
return nil, fmt.Errorf("error reading directory %q: %v", baseDir, err)
}
for _, f := range files {
relativePath, err := vfs.RelativePath(baseDir, f)
if err != nil {
return nil, err
}
tokens := strings.Split(relativePath, "/")
if len(tokens) != 2 {
glog.V(2).Infof("ignoring unexpected file in keystore: %q", f)
continue
}
item := &KeystoreItem{
Name: tokens[0],
Id: insertFingerprintColons(tokens[1]),
Type: SecretTypeSSHPublicKey,
}
items = append(items, item)
}
}
return items, nil
}
func (c *VFSCAStore) IssueCert(id string, serial *big.Int, privateKey *PrivateKey, template *x509.Certificate) (*Certificate, error) {
glog.Infof("Issuing new certificate: %q", id)
template.SerialNumber = serial
p := c.buildCertificatePath(id, serial)
caCertificates, caPrivateKeys, err := c.readCAKeypairs()
if err != nil {
return nil, err
}
if caPrivateKeys == nil || caPrivateKeys.Primary() == nil {
return nil, fmt.Errorf("ca.key was not found; cannot issue certificates")
}
cert, err := SignNewCertificate(privateKey, template, caCertificates.Primary().Certificate, caPrivateKeys.Primary())
if err != nil {
return nil, err
}
err = c.storeCertificate(cert, p)
if err != nil {
return nil, err
}
// Make double-sure it round-trips
return c.loadOneCertificate(p)
}
func (c *VFSCAStore) AddCert(id string, cert *Certificate) error {
glog.Infof("Issuing new certificate: %q", id)
// We add with a timestamp of zero so this will never be the newest cert
serial := buildSerial(0)
p := c.buildCertificatePath(id, serial)
err := c.storeCertificate(cert, p)
if err != nil {
return err
}
// Make double-sure it round-trips
_, err = c.loadOneCertificate(p)
return err
}
type privateKeys struct {
keys map[string]*PrivateKey
primary string
}
func (p *privateKeys) Primary() *PrivateKey {
if p.primary == "" {
return nil
}
return p.keys[p.primary]
}
func (c *VFSCAStore) loadPrivateKeys(p vfs.Path) (*privateKeys, error) {
files, err := p.ReadDir()
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
keys := &privateKeys{
keys: make(map[string]*PrivateKey),
}
for _, f := range files {
key, err := c.loadOnePrivateKey(f)
if err != nil {
return nil, fmt.Errorf("error loading private key %q: %v", f, err)
}
name := f.Base()
name = strings.TrimSuffix(name, ".key")
keys.keys[name] = key
}
if len(keys.keys) == 0 {
return nil, nil
}
var primaryVersion *big.Int
for k := range keys.keys {
version, ok := big.NewInt(0).SetString(k, 10)
if !ok {
glog.Warningf("Ignoring private key with non-integer version: %q", k)
continue
}
if primaryVersion == nil || version.Cmp(primaryVersion) > 0 {
keys.primary = k
primaryVersion = version
}
}
return keys, nil
}
func (c *VFSCAStore) loadOnePrivateKey(p vfs.Path) (*PrivateKey, error) {
data, err := p.ReadFile()
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
k, err := ParsePEMPrivateKey(data)
if err != nil {
return nil, fmt.Errorf("error parsing private key from %q: %v", p, err)
}
return k, err
}
func ParsePEMPrivateKey(data []byte) (*PrivateKey, error) {
k, err := parsePEMPrivateKey(data)
if err != nil {
return nil, err
}
if k == nil {
return nil, nil
}
return &PrivateKey{Key: k}, nil
}
func (c *VFSCAStore) FindPrivateKey(id string) (*PrivateKey, error) {
var keys *privateKeys
if id == CertificateId_CA {
_, caPrivateKeys, err := c.readCAKeypairs()
if err != nil {
return nil, err
}
keys = caPrivateKeys
} else {
var err error
p := c.buildPrivateKeyPoolPath(id)
keys, err = c.loadPrivateKeys(p)
if err != nil {
return nil, err
}
}
var key *PrivateKey
if keys != nil && keys.primary != "" {
key = keys.keys[keys.primary]
}
return key, nil
}
func (c *VFSCAStore) PrivateKey(id string) (*PrivateKey, error) {
key, err := c.FindPrivateKey(id)
if err == nil && key == nil {
if c.DryRun {
glog.Warningf("using empty certificate, because running with DryRun")
return &PrivateKey{}, err
}
return nil, fmt.Errorf("cannot find SSL key %q", id)
}
return key, err
}
func (c *VFSCAStore) CreateKeypair(id string, template *x509.Certificate) (*Certificate, *PrivateKey, error) {
serial := c.buildSerial()
privateKey, err := c.CreatePrivateKey(id, serial)
if err != nil {
return nil, nil, err
}
cert, err := c.IssueCert(id, serial, privateKey, template)
if err != nil {
// TODO: Delete cert?
return nil, nil, err
}
return cert, privateKey, nil
}
func (c *VFSCAStore) CreatePrivateKey(id string, serial *big.Int) (*PrivateKey, error) {
p := c.buildPrivateKeyPath(id, serial)
rsaKey, err := rsa.GenerateKey(crypto_rand.Reader, 2048)
if err != nil {
return nil, fmt.Errorf("error generating RSA private key: %v", err)
}
privateKey := &PrivateKey{Key: rsaKey}
err = c.storePrivateKey(privateKey, p)
if err != nil {
return nil, err
}
return privateKey, nil
}
func (c *VFSCAStore) storePrivateKey(privateKey *PrivateKey, p vfs.Path) error {
var data bytes.Buffer
_, err := privateKey.WriteTo(&data)
if err != nil {
return err
}
return p.WriteFile(data.Bytes())
}
func (c *VFSCAStore) storeCertificate(cert *Certificate, p vfs.Path) error {
// TODO: replace storePrivateKey & storeCertificate with writeFile(io.WriterTo)?
var data bytes.Buffer
_, err := cert.WriteTo(&data)
if err != nil {
return err
}
return p.WriteFile(data.Bytes())
}
func (c *VFSCAStore) buildSerial() *big.Int {
t := time.Now().UnixNano()
return buildSerial(t)
}
func buildSerial(timestamp int64) *big.Int {
randomLimit := new(big.Int).Lsh(big.NewInt(1), 32)
randomComponent, err := crypto_rand.Int(crypto_rand.Reader, randomLimit)
if err != nil {
glog.Fatalf("error generating random number: %v", err)
}
serial := big.NewInt(timestamp)
serial.Lsh(serial, 32)
serial.Or(serial, randomComponent)
return serial
}
func formatFingerprint(data []byte) string {
var buf bytes.Buffer
for i, b := range data {
s := fmt.Sprintf("%0.2x", b)
if i != 0 {
buf.WriteString(":")
}
buf.WriteString(s)
}
return buf.String()
}
func insertFingerprintColons(id string) string {
var buf bytes.Buffer
for {
if id == "" {
break
}
if buf.Len() != 0 {
buf.WriteString(":")
}
if len(id) < 2 {
buf.WriteString(id)
} else {
buf.WriteString(id[0:2])
id = id[2:]
}
}
return buf.String()
}
// AddSSHPublicKey stores an SSH public key
func (c *VFSCAStore) AddSSHPublicKey(name string, pubkey []byte) error {
var id string
{
sshPublicKey, _, _, _, err := ssh.ParseAuthorizedKey(pubkey)
if err != nil {
return fmt.Errorf("error parsing public key: %v", err)
}
// compute fingerprint to serve as id
h := md5.New()
_, err = h.Write(sshPublicKey.Marshal())
if err != nil {
return err
}
id = formatFingerprint(h.Sum(nil))
}
p := c.buildSSHPublicKeyPath(name, id)
return c.storeData(pubkey, p)
}
func (c *VFSCAStore) buildSSHPublicKeyPath(name string, id string) vfs.Path {
// id is fingerprint with colons, but we store without colons
id = strings.Replace(id, ":", "", -1)
return c.basedir.Join("ssh", "public", name, id)
}
func (c *VFSCAStore) storeData(data []byte, p vfs.Path) error {
return p.WriteFile(data)
}
func (c *VFSCAStore) FindSSHPublicKeys(name string) ([]*KeystoreItem, error) {
p := c.basedir.Join("ssh", "public", name)
items, err := c.loadPath(p)
if err != nil {
return nil, err
}
for _, item := range items {
// Fill in the missing fields
item.Type = SecretTypeSSHPublicKey
item.Name = name
item.Id = insertFingerprintColons(item.Id)
}
return items, nil
}
func (c *VFSCAStore) loadPath(p vfs.Path) ([]*KeystoreItem, error) {
files, err := p.ReadDir()
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
var keystoreItems []*KeystoreItem
for _, f := range files {
data, err := f.ReadFile()
if err != nil {
if os.IsNotExist(err) {
glog.V(2).Infof("Ignoring not-found issue reading %q", f)
continue
}
return nil, fmt.Errorf("error loading keystore item %q: %v", f, err)
}
name := f.Base()
keystoreItem := &KeystoreItem{
Id: name,
Data: data,
}
keystoreItems = append(keystoreItems, keystoreItem)
}
return keystoreItems, nil
}
func (c *VFSCAStore) loadData(p vfs.Path) (*PrivateKey, error) {
data, err := p.ReadFile()
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
k, err := ParsePEMPrivateKey(data)
if err != nil {
return nil, fmt.Errorf("error parsing private key from %q: %v", p, err)
}
return k, err
}
func (c *VFSCAStore) DeleteSecret(item *KeystoreItem) error {
switch item.Type {
case SecretTypeSSHPublicKey:
p := c.buildSSHPublicKeyPath(item.Name, item.Id)
return p.Remove()
default:
// Primarily because we need to make sure users can recreate them!
return fmt.Errorf("deletion of keystore items of type %v not (yet) supported", item.Type)
}
}