/
authority.go
406 lines (358 loc) · 11.6 KB
/
authority.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
/*
Copyright 2020 The cert-manager 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 authority
import (
"bytes"
"context"
"crypto"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"fmt"
"math/big"
"sync"
"time"
"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
coreclientset "k8s.io/client-go/kubernetes/typed/core/v1"
corelisters "k8s.io/client-go/listers/core/v1"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"github.com/cert-manager/webhook-lib/internal/pki"
)
const tlsCAKey = "ca.crt"
// DynamicAuthority manages a certificate authority stored in a Secret resource
// and provides methods to obtain signed leaf certificates.
// The private key and certificate will be automatically generated, and when
// nearing expiry, the private key and root certificate will be rotated.
type DynamicAuthority struct {
// Namespace and Name of the Secret resource used to store the authority.
SecretNamespace, SecretName string
// RESTConfig used to connect to the apiserver.
RESTConfig *rest.Config
// The amount of time the root CA certificate will be valid for.
// This must be greater than LeafDuration.
// Defaults to 365d.
CADuration time.Duration
// The amount of time leaf certificates signed by this authority will be
// valid for.
// This must be less than CADuration.
// Defaults to 7d.
LeafDuration time.Duration
// Logger to write messages to.
log logr.Logger
lister corelisters.SecretNamespaceLister
client coreclientset.SecretInterface
// PEM-encoded CA certificate and private key bytes
currentCertData, currentPrivateKeyData []byte
// signMutex gates access to the certificate and private key data
signMutex sync.Mutex
// ensureMutex gates the 'ensureCA' method
ensureMutex sync.Mutex
// watchMutex gates access to the slice of watch channels
watchMutex sync.Mutex
watches []chan struct{}
}
type SignFunc func(template *x509.Certificate) (*x509.Certificate, error)
var _ SignFunc = (&DynamicAuthority{}).Sign
func (d *DynamicAuthority) Run(ctx context.Context) error {
d.log = logr.FromContextOrDiscard(ctx)
if d.SecretNamespace == "" {
return fmt.Errorf("SecretNamespace must be set")
}
if d.SecretName == "" {
return fmt.Errorf("SecretName must be set")
}
if d.CADuration == 0 {
d.CADuration = time.Hour * 24 * 365 // 365d
}
if d.LeafDuration == 0 {
d.LeafDuration = time.Hour * 24 * 7 // 7d
}
cl, err := kubernetes.NewForConfig(d.RESTConfig)
if err != nil {
return err
}
escapedName := fields.EscapeValue(d.SecretName)
factory := informers.NewSharedInformerFactoryWithOptions(cl, time.Minute,
informers.WithNamespace(d.SecretNamespace),
informers.WithTweakListOptions(func(opts *metav1.ListOptions) {
opts.FieldSelector = "metadata.name=" + escapedName
}),
)
informer := factory.Core().V1().Secrets().Informer()
informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: d.handleAdd,
UpdateFunc: d.handleUpdate,
DeleteFunc: d.handleDelete,
})
d.lister = factory.Core().V1().Secrets().Lister().Secrets(d.SecretNamespace)
d.client = cl.CoreV1().Secrets(d.SecretNamespace)
// start the informers and wait for the cache to sync
factory.Start(ctx.Done())
if !cache.WaitForCacheSync(ctx.Done(), informer.HasSynced) {
return fmt.Errorf("failed waiting for informer caches to sync")
}
// continuously check the secret resource every 10s in case any events have
// been missed that could cause us to get into an idle state where the
// Secret resource does not exist and so the informers handler functions
// are not triggered.
if err = wait.PollImmediateUntil(time.Second*10, func() (done bool, err error) {
if err := d.ensureCA(ctx); err != nil {
d.log.Error(err, "error ensuring CA")
}
// never return 'done'.
// this poll only ends when stopCh is closed.
return false, nil
}, ctx.Done()); err != nil {
// If error cause was context, return that error instead
if ctx.Err() != nil {
return ctx.Err()
}
return err
}
return nil
}
// Sign will sign the given certificate template using the current version of
// the managed CA.
// It will automatically set the NotBefore and NotAfter times appropriately.
func (d *DynamicAuthority) Sign(template *x509.Certificate) (*x509.Certificate, error) {
d.signMutex.Lock()
defer d.signMutex.Unlock()
// tls.X509KeyPair performs a number of verification checks against the
// keypair, so we run it to verify the certificate and private key are
// valid.
_, err := tls.X509KeyPair(d.currentCertData, d.currentPrivateKeyData)
if err != nil {
return nil, fmt.Errorf("failed verifying CA keypair: %v", err)
}
caCert, err := pki.DecodeX509CertificateBytes(d.currentCertData)
if err != nil {
return nil, fmt.Errorf("failed decoding CA certificate: %v", err)
}
caPk, err := pki.DecodePrivateKeyBytes(d.currentPrivateKeyData)
if err != nil {
return nil, fmt.Errorf("failed decoding CA private key: %v", err)
}
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, err
}
template.Version = 3
template.SerialNumber = serialNumber
template.BasicConstraintsValid = true
template.NotBefore = time.Now()
template.NotAfter = template.NotBefore.Add(d.LeafDuration)
// explicitly handle the case of the root CA certificate being expired
if caCert.NotAfter.Before(template.NotBefore) {
return nil, fmt.Errorf("internal error: CA certificate has expired, try again later")
}
// don't allow leaf certificates to be valid longer than their parents
if caCert.NotAfter.Before(template.NotAfter) {
template.NotAfter = caCert.NotAfter
}
_, cert, err := pki.SignCertificate(template, caCert, template.PublicKey.(crypto.PublicKey), caPk)
if err != nil {
return nil, err
}
return cert, nil
}
// WatchRotation will returns a channel that fires notifications if the CA
// certificate is rotated/updated.
// This can be used to automatically trigger rotation of leaf certificates
// when the root CA changes.
func (d *DynamicAuthority) WatchRotation(stopCh <-chan struct{}) <-chan struct{} {
d.watchMutex.Lock()
defer d.watchMutex.Unlock()
ch := make(chan struct{}, 1)
d.watches = append(d.watches, ch)
go func() {
defer close(ch)
<-stopCh
d.watchMutex.Lock()
defer d.watchMutex.Unlock()
for i, c := range d.watches {
if c == ch {
d.watches = append(d.watches[:i], d.watches[i+1:]...)
return
}
}
}()
return ch
}
func (d *DynamicAuthority) ensureCA(ctx context.Context) error {
d.ensureMutex.Lock()
defer d.ensureMutex.Unlock()
s, err := d.lister.Get(d.SecretName)
if apierrors.IsNotFound(err) {
return d.regenerateCA(ctx, nil)
}
if err != nil {
return err
}
if d.caRequiresRegeneration(s) {
return d.regenerateCA(ctx, s.DeepCopy())
}
d.notifyWatches(s.Data[corev1.TLSCertKey], s.Data[corev1.TLSPrivateKeyKey])
return nil
}
func (d *DynamicAuthority) notifyWatches(newCertData, newPrivateKeyData []byte) {
if bytes.Equal(d.currentCertData, newCertData) && bytes.Equal(d.currentPrivateKeyData, newPrivateKeyData) {
// do nothing if the data has not changed
return
}
d.watchMutex.Lock()
defer d.watchMutex.Unlock()
for _, ch := range d.watches {
// the watch channels have a buffer of 1 - drop events to slow
// consumers
select {
case ch <- struct{}{}:
default:
}
}
d.signMutex.Lock()
defer d.signMutex.Unlock()
d.currentCertData = newCertData
d.currentPrivateKeyData = newPrivateKeyData
}
// caRequiresRegeneration will check data in a Secret resource and return true
// if the CA needs to be regenerated for any reason.
func (d *DynamicAuthority) caRequiresRegeneration(s *corev1.Secret) bool {
if s.Data == nil {
return true
}
caData := s.Data[tlsCAKey]
pkData := s.Data[corev1.TLSPrivateKeyKey]
certData := s.Data[corev1.TLSCertKey]
if len(caData) == 0 || len(pkData) == 0 || len(certData) == 0 {
d.log.Info("Missing data in CA secret. Regenerating")
return true
}
// ensure that the ca.crt and tls.crt keys are equal
if !bytes.Equal(caData, certData) {
return true
}
cert, err := tls.X509KeyPair(certData, pkData)
if err != nil {
d.log.Error(err, "Failed to parse data in CA secret. Regenerating")
return true
}
x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
if err != nil {
d.log.Error(err, "internal error parsing x509 certificate")
return true
}
if !x509Cert.IsCA {
d.log.Info("Stored certificate is not marked as a CA. Regenerating...")
return true
}
// renew the root CA when the current one is 2/3 of the way through its life
if x509Cert.NotAfter.Sub(time.Now()) < (d.CADuration / 3) {
d.log.Info("Root CA certificate is nearing expiry. Regenerating...")
return true
}
return false
}
var serialNumberLimit = new(big.Int).Lsh(big.NewInt(1), 128)
// regenerateCA will regenerate and store a new CA.
// If the provided Secret is nil, a new secret resource will be Created.
// Otherwise, the provided resource will be modified and Updated.
func (d *DynamicAuthority) regenerateCA(ctx context.Context, s *corev1.Secret) error {
pk, err := pki.GenerateECPrivateKey(384)
if err != nil {
return err
}
pkBytes, err := pki.EncodePKCS8PrivateKey(pk)
if err != nil {
return err
}
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return err
}
cert := &x509.Certificate{
Version: 2,
BasicConstraintsValid: true,
SerialNumber: serialNumber,
PublicKeyAlgorithm: x509.ECDSA,
Subject: pkix.Name{
CommonName: "webhook-ca",
},
IsCA: true,
NotBefore: time.Now(),
NotAfter: time.Now().Add(d.CADuration),
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageCertSign,
}
// self sign the root CA
_, cert, err = pki.SignCertificate(cert, cert, pk.Public(), pk)
if err != nil {
return err
}
certBytes, err := pki.EncodeX509(cert)
if err != nil {
return err
}
if s == nil {
_, err := d.client.Create(ctx, &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: d.SecretName,
Namespace: d.SecretNamespace,
Annotations: map[string]string{
"cert-manager.io/allow-direct-injection": "true",
},
},
Data: map[string][]byte{
corev1.TLSCertKey: certBytes,
corev1.TLSPrivateKeyKey: pkBytes,
tlsCAKey: certBytes,
},
}, metav1.CreateOptions{})
return err
}
if s.Data == nil {
s.Data = make(map[string][]byte)
}
s.Data[corev1.TLSCertKey] = certBytes
s.Data[corev1.TLSPrivateKeyKey] = pkBytes
s.Data[tlsCAKey] = certBytes
if _, err := d.client.Update(ctx, s, metav1.UpdateOptions{}); err != nil {
return err
}
return nil
}
func (d *DynamicAuthority) handleAdd(obj interface{}) {
ctx := context.Background()
if err := d.ensureCA(ctx); err != nil {
d.log.Error(err, "error ensuring CA")
}
}
func (d *DynamicAuthority) handleUpdate(_, obj interface{}) {
ctx := context.Background()
if err := d.ensureCA(ctx); err != nil {
d.log.Error(err, "error ensuring CA")
}
}
func (d *DynamicAuthority) handleDelete(obj interface{}) {
ctx := context.Background()
if err := d.ensureCA(ctx); err != nil {
d.log.Error(err, "error ensuring CA")
}
}