-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
vfs_castore.go
985 lines (813 loc) · 23.9 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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
/*
Copyright 2019 The Kubernetes 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 fi
import (
"bytes"
"crypto/x509"
"fmt"
"math/big"
"os"
"strings"
"sync"
"time"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/klog"
"k8s.io/kops/pkg/acls"
"k8s.io/kops/pkg/apis/kops"
"k8s.io/kops/pkg/apis/kops/v1alpha2"
"k8s.io/kops/pkg/kopscodecs"
"k8s.io/kops/pkg/pki"
"k8s.io/kops/pkg/sshcredentials"
"k8s.io/kops/util/pkg/vfs"
)
type VFSCAStore struct {
basedir vfs.Path
cluster *kops.Cluster
mutex sync.Mutex
cachedCAs map[string]*cachedEntry
// SerialGenerator is the function for generating certificate serial numbers
// It can be replaced for testing purposes.
SerialGenerator func() *big.Int
}
type cachedEntry struct {
certificates *keyset
privateKeys *keyset
}
var _ CAStore = &VFSCAStore{}
var _ SSHCredentialStore = &VFSCAStore{}
func NewVFSCAStore(cluster *kops.Cluster, basedir vfs.Path) *VFSCAStore {
c := &VFSCAStore{
basedir: basedir,
cluster: cluster,
cachedCAs: make(map[string]*cachedEntry),
}
c.SerialGenerator = func() *big.Int {
t := time.Now().UnixNano()
return pki.BuildPKISerial(t)
}
return c
}
// NewVFSSSHCredentialStore creates a SSHCredentialStore backed by VFS
func NewVFSSSHCredentialStore(cluster *kops.Cluster, basedir vfs.Path) SSHCredentialStore {
// Note currently identical to NewVFSCAStore
c := &VFSCAStore{
basedir: basedir,
cluster: cluster,
cachedCAs: make(map[string]*cachedEntry),
}
return c
}
func (s *VFSCAStore) VFSPath() vfs.Path {
return s.basedir
}
// Retrieves the CA keypair. No longer generates keypairs if not found.
func (s *VFSCAStore) readCAKeypairs(id string) (*keyset, *keyset, error) {
s.mutex.Lock()
defer s.mutex.Unlock()
cached := s.cachedCAs[id]
if cached != nil {
return cached.certificates, cached.privateKeys, nil
}
caCertificates, err := s.loadCertificates(s.buildCertificatePoolPath(id))
if err != nil {
return nil, nil, err
}
var caPrivateKeys *keyset
if caCertificates != nil {
caPrivateKeys, err = s.loadPrivateKeys(s.buildPrivateKeyPoolPath(id))
if err != nil {
return nil, nil, err
}
if caPrivateKeys == nil {
klog.Warningf("CA private key was not found")
//return nil, fmt.Errorf("error loading CA private key - key not found")
}
}
if caPrivateKeys == nil {
// We no longer generate CA certificates automatically - too race-prone
return caCertificates, caPrivateKeys, nil
}
cached = &cachedEntry{certificates: caCertificates, privateKeys: caPrivateKeys}
s.cachedCAs[id] = cached
return cached.certificates, cached.privateKeys, nil
}
func (c *VFSCAStore) buildCertificatePoolPath(name string) vfs.Path {
return c.basedir.Join("issued", name)
}
func (c *VFSCAStore) buildCertificatePath(name string, id string) vfs.Path {
return c.basedir.Join("issued", name, id+".crt")
}
func (c *VFSCAStore) buildPrivateKeyPoolPath(name string) vfs.Path {
return c.basedir.Join("private", name)
}
func (c *VFSCAStore) buildPrivateKeyPath(name string, id string) vfs.Path {
return c.basedir.Join("private", name, id+".key")
}
func (c *VFSCAStore) parseKeysetYaml(data []byte) (*kops.Keyset, bool, error) {
defaultReadVersion := v1alpha2.SchemeGroupVersion.WithKind("Keyset")
object, gvk, err := kopscodecs.Decode(data, &defaultReadVersion)
if err != nil {
return nil, false, fmt.Errorf("error parsing keyset: %v", err)
}
keyset, ok := object.(*kops.Keyset)
if !ok {
return nil, false, fmt.Errorf("object was not a keyset, was a %T", object)
}
if gvk == nil {
return nil, false, fmt.Errorf("object did not have GroupVersionKind: %q", keyset.Name)
}
return keyset, gvk.Version != keysetFormatLatest, nil
}
// loadCertificatesBundle loads a keyset from the path
// Returns (nil, nil) if the file is not found
// Bundles avoid the need for a list-files permission, which can be tricky on e.g. GCE
func (c *VFSCAStore) loadKeysetBundle(p vfs.Path) (*keyset, error) {
data, err := p.ReadFile()
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, fmt.Errorf("unable to read bundle %q: %v", p, err)
}
o, legacyFormat, err := c.parseKeysetYaml(data)
if err != nil {
return nil, fmt.Errorf("error parsing bundle %q: %v", p, err)
}
keyset, err := parseKeyset(o)
if err != nil {
return nil, fmt.Errorf("error mapping bundle %q: %v", p, err)
}
keyset.legacyFormat = legacyFormat
return keyset, nil
}
func (k *keyset) ToAPIObject(name string, includePrivateKeyMaterial bool) (*kops.Keyset, error) {
o := &kops.Keyset{}
o.Name = name
o.Spec.Type = kops.SecretTypeKeypair
for _, ki := range k.items {
oki := kops.KeysetItem{
Id: ki.id,
}
if ki.certificate != nil {
var publicMaterial bytes.Buffer
if _, err := ki.certificate.WriteTo(&publicMaterial); err != nil {
return nil, err
}
oki.PublicMaterial = publicMaterial.Bytes()
}
if includePrivateKeyMaterial && ki.privateKey != nil {
var privateMaterial bytes.Buffer
if _, err := ki.privateKey.WriteTo(&privateMaterial); err != nil {
return nil, err
}
oki.PrivateMaterial = privateMaterial.Bytes()
}
o.Spec.Keys = append(o.Spec.Keys, oki)
}
return o, nil
}
// writeKeysetBundle writes a keyset bundle to VFS
func (c *VFSCAStore) writeKeysetBundle(p vfs.Path, name string, keyset *keyset, includePrivateKeyMaterial bool) error {
p = p.Join("keyset.yaml")
o, err := keyset.ToAPIObject(name, includePrivateKeyMaterial)
if err != nil {
return err
}
objectData, err := serializeKeysetBundle(o)
if err != nil {
return err
}
acl, err := acls.GetACL(p, c.cluster)
if err != nil {
return err
}
return p.WriteFile(bytes.NewReader(objectData), acl)
}
// serializeKeysetBundle converts a keyset bundle to yaml, for writing to VFS
func serializeKeysetBundle(o *kops.Keyset) ([]byte, error) {
var objectData bytes.Buffer
codecs := kopscodecs.Codecs
yaml, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), "application/yaml")
if !ok {
klog.Fatalf("no YAML serializer registered")
}
encoder := codecs.EncoderForVersion(yaml.Serializer, v1alpha2.SchemeGroupVersion)
if err := encoder.Encode(o, &objectData); err != nil {
return nil, fmt.Errorf("error serializing keyset: %v", err)
}
return objectData.Bytes(), nil
}
// removePrivateKeyMaterial returns a copy of the Keyset with the private key data removed
func removePrivateKeyMaterial(o *kops.Keyset) *kops.Keyset {
copy := o.DeepCopy()
for i := range copy.Spec.Keys {
copy.Spec.Keys[i].PrivateMaterial = nil
}
return copy
}
func SerializeKeyset(o *kops.Keyset) ([]byte, error) {
var objectData bytes.Buffer
{
codecs := kopscodecs.Codecs
yaml, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), "application/yaml")
if !ok {
klog.Fatalf("no YAML serializer registered")
}
encoder := codecs.EncoderForVersion(yaml.Serializer, v1alpha2.SchemeGroupVersion)
if err := encoder.Encode(o, &objectData); err != nil {
return nil, fmt.Errorf("error serializing keyset: %v", err)
}
}
return objectData.Bytes(), nil
}
func (c *VFSCAStore) loadCertificates(p vfs.Path) (*keyset, error) {
bundlePath := p.Join("keyset.yaml")
bundle, err := c.loadKeysetBundle(bundlePath)
return bundle, err
}
func (c *VFSCAStore) loadOneCertificate(p vfs.Path) (*pki.Certificate, error) {
data, err := p.ReadFile()
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
cert, err := pki.ParsePEMCertificate(data)
if err != nil {
return nil, err
}
if cert == nil {
return nil, nil
}
return cert, nil
}
func (c *VFSCAStore) FindKeypair(id string) (*pki.Certificate, *pki.PrivateKey, bool, error) {
cert, legacyFormat, err := c.findCert(id)
if err != nil {
return nil, nil, false, err
}
key, err := c.FindPrivateKey(id)
if err != nil {
return nil, nil, false, err
}
return cert, key, legacyFormat, nil
}
func (c *VFSCAStore) findCert(name string) (*pki.Certificate, bool, error) {
p := c.buildCertificatePoolPath(name)
certs, err := c.loadCertificates(p)
if err != nil {
return nil, false, fmt.Errorf("error in 'FindCert' attempting to load cert %q: %v", name, err)
}
if certs != nil && certs.primary != nil {
return certs.primary.certificate, certs.legacyFormat, nil
}
return nil, false, nil
}
func (c *VFSCAStore) FindCert(name string) (*pki.Certificate, error) {
cert, _, err := c.findCert(name)
return cert, err
}
func (c *VFSCAStore) FindCertificatePool(name string) (*CertificatePool, error) {
var certs *keyset
var err error
p := c.buildCertificatePoolPath(name)
certs, err = c.loadCertificates(p)
if err != nil {
return nil, fmt.Errorf("error in 'FindCertificatePool' attempting to load cert %q: %v", name, err)
}
pool := &CertificatePool{}
if certs != nil {
if certs.primary != nil {
pool.Primary = certs.primary.certificate
}
for k, cert := range certs.items {
if certs.primary != nil && k == certs.primary.id {
continue
}
if cert.certificate == nil {
continue
}
pool.Secondary = append(pool.Secondary, cert.certificate)
}
}
return pool, nil
}
func (c *VFSCAStore) FindCertificateKeyset(name string) (*kops.Keyset, error) {
p := c.buildCertificatePoolPath(name)
certs, err := c.loadCertificates(p)
if err != nil {
return nil, fmt.Errorf("error in 'FindCertificatePool' attempting to load cert %q: %v", name, err)
}
if certs == nil {
return nil, nil
}
o, err := certs.ToAPIObject(name, false)
if err != nil {
return nil, err
}
return o, nil
}
// ListKeysets implements CAStore::ListKeysets
func (c *VFSCAStore) ListKeysets() ([]*kops.Keyset, error) {
keysets := make(map[string]*kops.Keyset)
{
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 {
klog.V(2).Infof("ignoring unexpected file in keystore: %q", f)
continue
}
name := tokens[0]
keyset := keysets[name]
if keyset == nil {
keyset = &kops.Keyset{}
keyset.Name = tokens[0]
keyset.Spec.Type = kops.SecretTypeKeypair
keysets[name] = keyset
}
if tokens[1] == "keyset.yaml" {
// TODO: Should we load the keyset to get the actual ids?
} else {
keyset.Spec.Keys = append(keyset.Spec.Keys, kops.KeysetItem{
Id: strings.TrimSuffix(tokens[1], ".crt"),
})
}
}
}
var items []*kops.Keyset
for _, v := range keysets {
items = append(items, v)
}
return items, nil
}
// ListSSHCredentials implements SSHCredentialStore::ListSSHCredentials
func (c *VFSCAStore) ListSSHCredentials() ([]*kops.SSHCredential, error) {
var items []*kops.SSHCredential
{
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 {
klog.V(2).Infof("ignoring unexpected file in keystore: %q", f)
continue
}
pubkey, err := f.ReadFile()
if err != nil {
return nil, fmt.Errorf("error reading SSH credential %q: %v", f, err)
}
item := &kops.SSHCredential{}
item.Name = tokens[0]
item.Spec.PublicKey = string(pubkey)
items = append(items, item)
}
}
return items, nil
}
// MirrorTo will copy keys to a vfs.Path, which is often easier for a machine to read
func (c *VFSCAStore) MirrorTo(basedir vfs.Path) error {
if basedir.Path() == c.basedir.Path() {
klog.V(2).Infof("Skipping key store mirror from %q to %q (same paths)", c.basedir, basedir)
return nil
}
klog.V(2).Infof("Mirroring key store from %q to %q", c.basedir, basedir)
keysets, err := c.ListKeysets()
if err != nil {
return err
}
for _, keyset := range keysets {
if err := mirrorKeyset(c.cluster, basedir, keyset); err != nil {
return err
}
}
sshCredentials, err := c.ListSSHCredentials()
if err != nil {
return fmt.Errorf("error listing SSHCredentials: %v", err)
}
for _, sshCredential := range sshCredentials {
if err := mirrorSSHCredential(c.cluster, basedir, sshCredential); err != nil {
return err
}
}
return nil
}
// mirrorKeyset writes keyset bundles for the certificates & privatekeys
func mirrorKeyset(cluster *kops.Cluster, basedir vfs.Path, keyset *kops.Keyset) error {
primary := FindPrimary(keyset)
if primary == nil {
return fmt.Errorf("found keyset with no primary data: %s", keyset.Name)
}
switch keyset.Spec.Type {
case kops.SecretTypeKeypair:
{
data, err := serializeKeysetBundle(removePrivateKeyMaterial(keyset))
if err != nil {
return err
}
p := basedir.Join("issued", keyset.Name, "keyset.yaml")
acl, err := acls.GetACL(p, cluster)
if err != nil {
return err
}
err = p.WriteFile(bytes.NewReader(data), acl)
if err != nil {
return fmt.Errorf("error writing %q: %v", p, err)
}
}
{
data, err := serializeKeysetBundle(keyset)
if err != nil {
return err
}
p := basedir.Join("private", keyset.Name, "keyset.yaml")
acl, err := acls.GetACL(p, cluster)
if err != nil {
return err
}
err = p.WriteFile(bytes.NewReader(data), acl)
if err != nil {
return fmt.Errorf("error writing %q: %v", p, err)
}
}
default:
return fmt.Errorf("unknown secret type: %q", keyset.Spec.Type)
}
return nil
}
// mirrorSSHCredential writes the SSH credential file to the mirror location
func mirrorSSHCredential(cluster *kops.Cluster, basedir vfs.Path, sshCredential *kops.SSHCredential) error {
id, err := sshcredentials.Fingerprint(sshCredential.Spec.PublicKey)
if err != nil {
return fmt.Errorf("error fingerprinting SSH public key %q: %v", sshCredential.Name, err)
}
p := basedir.Join("ssh", "public", sshCredential.Name, id)
acl, err := acls.GetACL(p, cluster)
if err != nil {
return err
}
err = p.WriteFile(bytes.NewReader([]byte(sshCredential.Spec.PublicKey)), acl)
if err != nil {
return fmt.Errorf("error writing %q: %v", p, err)
}
return nil
}
func (c *VFSCAStore) issueCert(signer string, id string, serial *big.Int, privateKey *pki.PrivateKey, template *x509.Certificate) (*pki.Certificate, error) {
klog.Infof("Issuing new certificate: %q", id)
template.SerialNumber = serial
var cert *pki.Certificate
if template.IsCA {
var err error
cert, err = pki.SignNewCertificate(privateKey, template, nil, nil)
if err != nil {
return nil, err
}
} else {
caCertificates, caPrivateKeys, err := c.readCAKeypairs(signer)
if err != nil {
return nil, err
}
if caPrivateKeys == nil || caPrivateKeys.primary == nil || caPrivateKeys.primary.privateKey == nil {
return nil, fmt.Errorf("ca key for %q was not found; cannot issue certificates", signer)
}
if caCertificates == nil || caCertificates.primary == nil || caCertificates.primary.certificate == nil {
return nil, fmt.Errorf("ca certificate for %q was not found; cannot issue certificates", signer)
}
cert, err = pki.SignNewCertificate(privateKey, template, caCertificates.primary.certificate.Certificate, caPrivateKeys.primary.privateKey)
if err != nil {
return nil, err
}
}
err := c.StoreKeypair(id, cert, privateKey)
if err != nil {
return nil, err
}
// Make double-sure it round-trips
p := c.buildCertificatePath(id, serial.String())
return c.loadOneCertificate(p)
}
func (c *VFSCAStore) StoreKeypair(name string, cert *pki.Certificate, privateKey *pki.PrivateKey) error {
serial := cert.Certificate.SerialNumber.String()
ki := &keysetItem{
id: serial,
certificate: cert,
privateKey: privateKey,
}
{
err := c.storePrivateKey(name, ki)
if err != nil {
return err
}
}
{
err := c.storeCertificate(name, ki)
if err != nil {
// TODO: Delete private key?
return err
}
}
return nil
}
func (c *VFSCAStore) AddCert(name string, cert *pki.Certificate) error {
klog.Infof("Adding TLS certificate: %q", name)
// We add with a timestamp of zero so this will never be the newest cert
serial := pki.BuildPKISerial(0).String()
p := c.buildCertificatePath(name, serial)
ki := &keysetItem{
id: serial,
certificate: cert,
}
err := c.storeCertificate(name, ki)
if err != nil {
return err
}
// Make double-sure it round-trips
_, err = c.loadOneCertificate(p)
return err
}
func (c *VFSCAStore) loadPrivateKeys(p vfs.Path) (*keyset, error) {
bundlePath := p.Join("keyset.yaml")
bundle, err := c.loadKeysetBundle(bundlePath)
return bundle, err
}
func (c *VFSCAStore) findPrivateKeyset(id string) (*keyset, error) {
var keys *keyset
if id == CertificateId_CA {
_, caPrivateKeys, err := c.readCAKeypairs(id)
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
}
}
return keys, nil
}
func (c *VFSCAStore) FindPrivateKey(id string) (*pki.PrivateKey, error) {
keys, err := c.findPrivateKeyset(id)
if err != nil {
return nil, err
}
var key *pki.PrivateKey
if keys != nil && keys.primary != nil {
key = keys.primary.privateKey
}
return key, nil
}
func (c *VFSCAStore) FindPrivateKeyset(name string) (*kops.Keyset, error) {
keys, err := c.findPrivateKeyset(name)
if err != nil {
return nil, err
}
o, err := keys.ToAPIObject(name, true)
if err != nil {
return nil, err
}
return o, nil
}
func (c *VFSCAStore) CreateKeypair(signer string, id string, template *x509.Certificate, privateKey *pki.PrivateKey) (*pki.Certificate, error) {
serial := c.SerialGenerator()
cert, err := c.issueCert(signer, id, serial, privateKey, template)
if err != nil {
return nil, err
}
return cert, nil
}
func (c *VFSCAStore) storePrivateKey(name string, ki *keysetItem) error {
if ki.privateKey == nil {
return fmt.Errorf("privateKey not provided to storeCertificate")
}
// Write the bundle
{
p := c.buildPrivateKeyPoolPath(name)
ks, err := c.loadPrivateKeys(p)
if err != nil {
return err
}
if ks == nil {
ks = &keyset{}
}
if ks.items == nil {
ks.items = make(map[string]*keysetItem)
}
ks.items[ki.id] = ki
if err := c.writeKeysetBundle(p, name, ks, true); err != nil {
return fmt.Errorf("error writing bundle: %v", err)
}
}
// TODO stop writing and remove legacy format files after rollback to pre-kops 1.18 not needed
// Write the data
{
var data bytes.Buffer
if _, err := ki.privateKey.WriteTo(&data); err != nil {
return err
}
p := c.buildPrivateKeyPath(name, ki.id)
acl, err := acls.GetACL(p, c.cluster)
if err != nil {
return err
}
return p.WriteFile(bytes.NewReader(data.Bytes()), acl)
}
}
func (c *VFSCAStore) storeCertificate(name string, ki *keysetItem) error {
if ki.certificate == nil {
return fmt.Errorf("certificate not provided to storeCertificate")
}
// Write the bundle
{
p := c.buildCertificatePoolPath(name)
ks, err := c.loadCertificates(p)
if err != nil {
return err
}
if ks == nil {
ks = &keyset{}
}
if ks.items == nil {
ks.items = make(map[string]*keysetItem)
}
ks.items[ki.id] = ki
if err := c.writeKeysetBundle(p, name, ks, false); err != nil {
return fmt.Errorf("error writing bundle: %v", err)
}
}
// TODO stop writing and remove legacy format files after rollback to pre-kops 1.18 not needed
// Write the data
{
var data bytes.Buffer
if _, err := ki.certificate.WriteTo(&data); err != nil {
return err
}
p := c.buildCertificatePath(name, ki.id)
acl, err := acls.GetACL(p, c.cluster)
if err != nil {
return err
}
return p.WriteFile(bytes.NewReader(data.Bytes()), acl)
}
}
func (c *VFSCAStore) deletePrivateKey(name string, id string) (bool, error) {
// Delete the file itself
{
p := c.buildPrivateKeyPath(name, id)
if err := p.Remove(); err != nil && !os.IsNotExist(err) {
return false, err
}
}
// Update the bundle
{
p := c.buildPrivateKeyPoolPath(name)
ks, err := c.loadPrivateKeys(p)
if err != nil {
return false, err
}
if ks == nil || ks.items[id] == nil {
return false, nil
}
delete(ks.items, id)
if err := c.writeKeysetBundle(p, name, ks, true); err != nil {
return false, fmt.Errorf("error writing bundle: %v", err)
}
}
return true, nil
}
func (c *VFSCAStore) deleteCertificate(name string, id string) (bool, error) {
// Delete the file itself
{
p := c.buildCertificatePath(name, id)
if err := p.Remove(); err != nil && !os.IsNotExist(err) {
return false, err
}
}
// Update the bundle
{
p := c.buildCertificatePoolPath(name)
ks, err := c.loadCertificates(p)
if err != nil {
return false, err
}
if ks == nil || ks.items[id] == nil {
return false, nil
}
delete(ks.items, id)
if err := c.writeKeysetBundle(p, name, ks, false); err != nil {
return false, fmt.Errorf("error writing bundle: %v", err)
}
}
return true, nil
}
// AddSSHPublicKey stores an SSH public key
func (c *VFSCAStore) AddSSHPublicKey(name string, pubkey []byte) error {
id, err := sshcredentials.Fingerprint(string(pubkey))
if err != nil {
return fmt.Errorf("error fingerprinting SSH public key %q: %v", name, err)
}
p := c.buildSSHPublicKeyPath(name, id)
acl, err := acls.GetACL(p, c.cluster)
if err != nil {
return err
}
return p.WriteFile(bytes.NewReader(pubkey), acl)
}
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) FindSSHPublicKeys(name string) ([]*kops.SSHCredential, error) {
p := c.basedir.Join("ssh", "public", name)
files, err := p.ReadDir()
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
var items []*kops.SSHCredential
for _, f := range files {
data, err := f.ReadFile()
if err != nil {
if os.IsNotExist(err) {
klog.V(2).Infof("Ignoring not-found issue reading %q", f)
continue
}
return nil, fmt.Errorf("error loading SSH item %q: %v", f, err)
}
item := &kops.SSHCredential{}
item.Name = name
item.Spec.PublicKey = string(data)
items = append(items, item)
}
return items, nil
}
// DeleteKeysetItem implements CAStore::DeleteKeysetItem
func (c *VFSCAStore) DeleteKeysetItem(item *kops.Keyset, id string) error {
switch item.Spec.Type {
case kops.SecretTypeKeypair:
_, ok := big.NewInt(0).SetString(id, 10)
if !ok {
return fmt.Errorf("keypair had non-integer version: %q", id)
}
removed, err := c.deleteCertificate(item.Name, id)
if err != nil {
return fmt.Errorf("error deleting certificate: %v", err)
}
if !removed {
klog.Warningf("certificate %s:%s was not found", item.Name, id)
}
removed, err = c.deletePrivateKey(item.Name, id)
if err != nil {
return fmt.Errorf("error deleting private key: %v", err)
}
if !removed {
klog.Warningf("private key %s:%s was not found", item.Name, id)
}
return nil
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.Spec.Type)
}
}
func (c *VFSCAStore) DeleteSSHCredential(item *kops.SSHCredential) error {
if item.Spec.PublicKey == "" {
return fmt.Errorf("must specific public key to delete SSHCredential")
}
id, err := sshcredentials.Fingerprint(item.Spec.PublicKey)
if err != nil {
return fmt.Errorf("invalid PublicKey when deleting SSHCredential: %v", err)
}
p := c.buildSSHPublicKeyPath(item.Name, id)
return p.Remove()
}