-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
clientset_castore.go
552 lines (470 loc) · 15 KB
/
clientset_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
/*
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"
"context"
"fmt"
"math/big"
"golang.org/x/crypto/ssh"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/klog/v2"
"k8s.io/kops/pkg/apis/kops"
kopsinternalversion "k8s.io/kops/pkg/client/clientset_generated/clientset/typed/kops/internalversion"
"k8s.io/kops/pkg/pki"
"k8s.io/kops/util/pkg/vfs"
)
// ClientsetCAStore is a CAStore implementation that stores keypairs in Keyset on a API server
type ClientsetCAStore struct {
cluster *kops.Cluster
namespace string
clientset kopsinternalversion.KopsInterface
}
var _ CAStore = &ClientsetCAStore{}
var _ SSHCredentialStore = &ClientsetCAStore{}
// NewClientsetCAStore is the constructor for ClientsetCAStore
func NewClientsetCAStore(cluster *kops.Cluster, clientset kopsinternalversion.KopsInterface, namespace string) CAStore {
c := &ClientsetCAStore{
cluster: cluster,
clientset: clientset,
namespace: namespace,
}
return c
}
// NewClientsetSSHCredentialStore creates an SSHCredentialStore backed by an API client
func NewClientsetSSHCredentialStore(cluster *kops.Cluster, clientset kopsinternalversion.KopsInterface, namespace string) SSHCredentialStore {
// Note: currently identical to NewClientsetCAStore
c := &ClientsetCAStore{
cluster: cluster,
clientset: clientset,
namespace: namespace,
}
return c
}
// keyset is a parsed Keyset
type keyset struct {
legacyFormat bool
items map[string]*keysetItem
primary *keysetItem
}
// keysetItem is a parsed KeysetItem
type keysetItem struct {
id string
certificate *pki.Certificate
privateKey *pki.PrivateKey
}
func parseKeyset(o *kops.Keyset) (*keyset, error) {
name := o.Name
keyset := &keyset{
items: make(map[string]*keysetItem),
}
for _, key := range o.Spec.Keys {
ki := &keysetItem{
id: key.Id,
}
if len(key.PublicMaterial) != 0 {
cert, err := pki.ParsePEMCertificate(key.PublicMaterial)
if err != nil {
klog.Warningf("key public material was %s", key.PublicMaterial)
return nil, fmt.Errorf("error loading certificate %s/%s: %v", name, key.Id, err)
}
ki.certificate = cert
}
if len(key.PrivateMaterial) != 0 {
privateKey, err := pki.ParsePEMPrivateKey(key.PrivateMaterial)
if err != nil {
return nil, fmt.Errorf("error loading private key %s/%s: %v", name, key.Id, err)
}
ki.privateKey = privateKey
}
keyset.items[key.Id] = ki
}
keyset.primary = keyset.findPrimary()
return keyset, nil
}
// loadKeyset gets the named keyset and the format of the Keyset.
func (c *ClientsetCAStore) loadKeyset(ctx context.Context, name string) (*keyset, error) {
o, err := c.clientset.Keysets(c.namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
return nil, nil
}
return nil, fmt.Errorf("error reading keyset %q: %v", name, err)
}
keyset, err := parseKeyset(o)
if err != nil {
return nil, err
}
return keyset, nil
}
// findPrimary returns the primary keysetItem in the keyset
func (k *keyset) findPrimary() *keysetItem {
var primary *keysetItem
var primaryVersion *big.Int
for _, item := range k.items {
version, ok := big.NewInt(0).SetString(item.id, 10)
if !ok {
klog.Warningf("Ignoring key item with non-integer version: %q", item.id)
continue
}
if primaryVersion == nil || version.Cmp(primaryVersion) > 0 {
primary = item
primaryVersion = version
}
}
return primary
}
// FindPrimary returns the primary KeysetItem in the Keyset
func FindPrimary(keyset *kops.Keyset) *kops.KeysetItem {
var primary *kops.KeysetItem
var primaryVersion *big.Int
for i := range keyset.Spec.Keys {
item := &keyset.Spec.Keys[i]
version, ok := big.NewInt(0).SetString(item.Id, 10)
if !ok {
klog.Warningf("Ignoring key item with non-integer version: %q", item.Id)
continue
}
if primaryVersion == nil || version.Cmp(primaryVersion) > 0 {
primary = item
primaryVersion = version
}
}
return primary
}
// FindKeypair implements CAStore::FindKeypair
func (c *ClientsetCAStore) FindKeypair(name string) (*pki.Certificate, *pki.PrivateKey, bool, error) {
ctx := context.TODO()
keyset, err := c.loadKeyset(ctx, name)
if err != nil {
return nil, nil, false, err
}
if keyset != nil && keyset.primary != nil {
return keyset.primary.certificate, keyset.primary.privateKey, keyset.legacyFormat, nil
}
return nil, nil, false, nil
}
// FindCert implements CAStore::FindCert
func (c *ClientsetCAStore) FindCert(name string) (*pki.Certificate, error) {
ctx := context.TODO()
keyset, err := c.loadKeyset(ctx, name)
if err != nil {
return nil, err
}
if keyset != nil && keyset.primary != nil {
return keyset.primary.certificate, nil
}
return nil, nil
}
// FindCertificatePool implements CAStore::FindCertificatePool
func (c *ClientsetCAStore) FindCertificatePool(name string) (*CertificatePool, error) {
ctx := context.TODO()
keyset, err := c.loadKeyset(ctx, name)
if err != nil {
return nil, err
}
pool := &CertificatePool{}
if keyset != nil {
if keyset.primary != nil {
pool.Primary = keyset.primary.certificate
}
for id, item := range keyset.items {
if id == keyset.primary.id {
continue
}
pool.Secondary = append(pool.Secondary, item.certificate)
}
}
return pool, nil
}
// FindCertificateKeyset implements CAStore::FindCertificateKeyset
func (c *ClientsetCAStore) FindCertificateKeyset(name string) (*kops.Keyset, error) {
ctx := context.TODO()
o, err := c.clientset.Keysets(c.namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
return nil, nil
}
return nil, fmt.Errorf("error reading keyset %q: %v", name, err)
}
return o, nil
}
// ListKeysets implements CAStore::ListKeysets
func (c *ClientsetCAStore) ListKeysets() ([]*kops.Keyset, error) {
ctx := context.TODO()
var items []*kops.Keyset
{
list, err := c.clientset.Keysets(c.namespace).List(ctx, metav1.ListOptions{})
if err != nil {
return nil, fmt.Errorf("error listing Keysets: %v", err)
}
for i := range list.Items {
keyset := &list.Items[i]
switch keyset.Spec.Type {
case kops.SecretTypeKeypair:
items = append(items, &list.Items[i])
case kops.SecretTypeSecret:
continue // Ignore - this is handled by ClientsetSecretStore
default:
return nil, fmt.Errorf("unhandled secret type %q: %v", keyset.Spec.Type, err)
}
}
}
return items, nil
}
// ListSSHCredentials implements SSHCredentialStore::ListSSHCredentials
func (c *ClientsetCAStore) ListSSHCredentials() ([]*kops.SSHCredential, error) {
ctx := context.TODO()
var items []*kops.SSHCredential
{
list, err := c.clientset.SSHCredentials(c.namespace).List(ctx, metav1.ListOptions{})
if err != nil {
return nil, fmt.Errorf("error listing SSHCredentials: %v", err)
}
for i := range list.Items {
items = append(items, &list.Items[i])
}
}
return items, nil
}
// StoreKeypair implements CAStore::StoreKeypair
func (c *ClientsetCAStore) StoreKeypair(name string, cert *pki.Certificate, privateKey *pki.PrivateKey) error {
ctx := context.TODO()
return c.storeKeypair(ctx, name, cert.Certificate.SerialNumber.String(), cert, privateKey)
}
// AddCert implements CAStore::AddCert
func (c *ClientsetCAStore) AddCert(name string, cert *pki.Certificate) error {
ctx := context.TODO()
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)
err := c.storeKeypair(ctx, name, serial.String(), cert, nil)
if err != nil {
return err
}
return nil
}
// FindPrivateKey implements CAStore::FindPrivateKey
func (c *ClientsetCAStore) FindPrivateKey(name string) (*pki.PrivateKey, error) {
ctx := context.TODO()
keyset, err := c.loadKeyset(ctx, name)
if err != nil {
return nil, err
}
if keyset != nil && keyset.primary != nil {
return keyset.primary.privateKey, nil
}
return nil, nil
}
// FindPrivateKeyset implements CAStore::FindPrivateKeyset
func (c *ClientsetCAStore) FindPrivateKeyset(name string) (*kops.Keyset, error) {
ctx := context.TODO()
o, err := c.clientset.Keysets(c.namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
return nil, nil
}
return nil, fmt.Errorf("error reading keyset %q: %v", name, err)
}
return o, nil
}
// addKey saves the specified key to the registry
func (c *ClientsetCAStore) addKey(ctx context.Context, name string, keysetType kops.KeysetType, item *kops.KeysetItem) error {
create := false
client := c.clientset.Keysets(c.namespace)
keyset, err := client.Get(ctx, name, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
keyset = nil
} else {
return fmt.Errorf("error reading keyset %q: %v", name, err)
}
}
if keyset == nil {
keyset = &kops.Keyset{}
keyset.Name = name
keyset.Spec.Type = keysetType
create = true
}
keyset.Spec.Keys = append(keyset.Spec.Keys, *item)
if create {
if _, err := client.Create(ctx, keyset, metav1.CreateOptions{}); err != nil {
return fmt.Errorf("error creating keyset %q: %v", name, err)
}
} else {
if _, err := client.Update(ctx, keyset, metav1.UpdateOptions{}); err != nil {
return fmt.Errorf("error updating keyset %q: %v", name, err)
}
}
return nil
}
// deleteKeysetItem deletes the specified key from the registry; deleting the whole keyset if it was the last one
func deleteKeysetItem(client kopsinternalversion.KeysetInterface, name string, keysetType kops.KeysetType, id string) error {
ctx := context.TODO()
keyset, err := client.Get(ctx, name, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
return nil
}
return fmt.Errorf("error reading Keyset %q: %v", name, err)
}
if keyset.Spec.Type != keysetType {
return fmt.Errorf("mismatch on Keyset type on %q", name)
}
var newKeys []kops.KeysetItem
found := false
for _, ki := range keyset.Spec.Keys {
if ki.Id == id {
found = true
} else {
newKeys = append(newKeys, ki)
}
}
if !found {
return fmt.Errorf("KeysetItem %q not found in Keyset %q", id, name)
}
if len(newKeys) == 0 {
if err := client.Delete(ctx, name, metav1.DeleteOptions{}); err != nil {
return fmt.Errorf("error deleting Keyset %q: %v", name, err)
}
} else {
keyset.Spec.Keys = newKeys
if _, err := client.Update(ctx, keyset, metav1.UpdateOptions{}); err != nil {
return fmt.Errorf("error updating Keyset %q: %v", name, err)
}
}
return nil
}
// addSSHCredential saves the specified SSH Credential to the registry, doing an update or insert
func (c *ClientsetCAStore) addSSHCredential(ctx context.Context, name string, publicKey string) error {
create := false
client := c.clientset.SSHCredentials(c.namespace)
sshCredential, err := client.Get(ctx, name, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
sshCredential = nil
} else {
return fmt.Errorf("error reading SSHCredential %q: %v", name, err)
}
}
if sshCredential == nil {
sshCredential = &kops.SSHCredential{}
sshCredential.Name = name
create = true
}
sshCredential.Spec.PublicKey = publicKey
if create {
if _, err := client.Create(ctx, sshCredential, metav1.CreateOptions{}); err != nil {
return fmt.Errorf("error creating SSHCredential %q: %v", name, err)
}
} else {
if _, err := client.Update(ctx, sshCredential, metav1.UpdateOptions{}); err != nil {
return fmt.Errorf("error updating SSHCredential %q: %v", name, err)
}
}
return nil
}
// deleteSSHCredential deletes the specified SSHCredential from the registry
func (c *ClientsetCAStore) deleteSSHCredential(ctx context.Context, name string) error {
client := c.clientset.SSHCredentials(c.namespace)
err := client.Delete(ctx, name, metav1.DeleteOptions{})
if err != nil {
return fmt.Errorf("error deleting SSHCredential %q: %v", name, err)
}
return nil
}
// addKey saves the specified keypair to the registry
func (c *ClientsetCAStore) storeKeypair(ctx context.Context, name string, id string, cert *pki.Certificate, privateKey *pki.PrivateKey) error {
var publicMaterial bytes.Buffer
if _, err := cert.WriteTo(&publicMaterial); err != nil {
return err
}
var privateMaterial bytes.Buffer
if _, err := privateKey.WriteTo(&privateMaterial); err != nil {
return err
}
item := &kops.KeysetItem{
Id: id,
PublicMaterial: publicMaterial.Bytes(),
PrivateMaterial: privateMaterial.Bytes(),
}
return c.addKey(ctx, name, kops.SecretTypeKeypair, item)
}
// AddSSHPublicKey implements CAStore::AddSSHPublicKey
func (c *ClientsetCAStore) AddSSHPublicKey(name string, pubkey []byte) error {
ctx := context.TODO()
_, _, _, _, err := ssh.ParseAuthorizedKey(pubkey)
if err != nil {
return fmt.Errorf("error parsing SSH public key: %v", err)
}
// TODO: Reintroduce or remove
//// compute fingerprint to serve as id
//h := md5.New()
//_, err = h.Write(sshPublicKey.Marshal())
//if err != nil {
// return err
//}
//id = formatFingerprint(h.Sum(nil))
return c.addSSHCredential(ctx, name, string(pubkey))
}
// FindSSHPublicKeys implements CAStore::FindSSHPublicKeys
func (c *ClientsetCAStore) FindSSHPublicKeys(name string) ([]*kops.SSHCredential, error) {
ctx := context.TODO()
o, err := c.clientset.SSHCredentials(c.namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
return nil, nil
}
return nil, fmt.Errorf("error reading SSHCredential %q: %v", name, err)
}
items := []*kops.SSHCredential{o}
return items, nil
}
// DeleteKeysetItem implements CAStore::DeleteKeysetItem
func (c *ClientsetCAStore) DeleteKeysetItem(item *kops.Keyset, id string) error {
switch item.Spec.Type {
case kops.SecretTypeKeypair:
client := c.clientset.Keysets(c.namespace)
return deleteKeysetItem(client, item.Name, kops.SecretTypeKeypair, id)
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)
}
}
// DeleteSSHCredential implements SSHCredentialStore::DeleteSSHCredential
func (c *ClientsetCAStore) DeleteSSHCredential(item *kops.SSHCredential) error {
ctx := context.TODO()
return c.deleteSSHCredential(ctx, item.Name)
}
func (c *ClientsetCAStore) MirrorTo(basedir vfs.Path) error {
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
}