-
Notifications
You must be signed in to change notification settings - Fork 260
/
certs.go
468 lines (390 loc) · 12.4 KB
/
certs.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
/*
Copyright The CloudNativePG Contributors
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 certs handle the PKI infrastructure of the operator
package certs
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"net"
"strings"
"time"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
// This is the lifetime of the generated certificates
certificateDuration = 90 * 24 * time.Hour
// This is the PEM block type of elliptic courves private key
ecPrivateKeyPEMBlockType = "EC PRIVATE KEY"
// This is the PEM block type for certificates
certificatePEMBlockType = "CERTIFICATE"
// Threshold to consider a certificate as expiring
expiringCheckThreshold = 7 * 24 * time.Hour
// CACertKey is the key for certificates in a CA secret
CACertKey = "ca.crt"
// CAPrivateKeyKey is the key for the private key field in a CA secret
CAPrivateKeyKey = "ca.key"
// TLSCertKey is the key for certificates in a CA secret
TLSCertKey = "tls.crt"
// TLSPrivateKeyKey is the key for the private key field in a CA secret
TLSPrivateKeyKey = "tls.key"
)
// CertType represent a certificate type
type CertType string
const (
// CertTypeClient means a certificate for a client
CertTypeClient = "client"
// CertTypeServer means a certificate for a server
CertTypeServer = "server"
)
// KeyPair represent a pair of keys to be used for asymmetric encryption and a
// certificate declaring the intended usage of those keys
type KeyPair struct {
// The private key PEM block
Private []byte
// The certificate PEM block
Certificate []byte
}
// ParseECPrivateKey parse the ECDSA private key stored in the pair
func (pair KeyPair) ParseECPrivateKey() (*ecdsa.PrivateKey, error) {
block, _ := pem.Decode(pair.Private)
if block == nil || block.Type != ecPrivateKeyPEMBlockType {
return nil, fmt.Errorf("invalid private key PEM block type")
}
return x509.ParseECPrivateKey(block.Bytes)
}
// ParseCertificate parse certificate stored in the pair
func (pair KeyPair) ParseCertificate() (*x509.Certificate, error) {
block, _ := pem.Decode(pair.Certificate)
if block == nil || block.Type != certificatePEMBlockType {
return nil, fmt.Errorf("invalid public key PEM block type")
}
return x509.ParseCertificate(block.Bytes)
}
// IsValid checks if given CA and verify options match the server
func (pair KeyPair) IsValid(caPair *KeyPair, opts *x509.VerifyOptions) error {
if opts == nil {
opts = &x509.VerifyOptions{}
}
blockServer, intermediatesPEM := pem.Decode(pair.Certificate)
if blockServer == nil || blockServer.Type != certificatePEMBlockType {
return fmt.Errorf("invalid public key PEM block type")
}
serverCert, err := x509.ParseCertificate(blockServer.Bytes)
if err != nil {
return err
}
if opts.Intermediates == nil {
opts.Intermediates = x509.NewCertPool()
}
// We can ignore the returned bool, because it is perfectly fine
// not to have an intermediate certificate if the server certificate
// is directly signed by the CA
opts.Intermediates.AppendCertsFromPEM(intermediatesPEM)
if opts.Roots == nil {
opts.Roots = x509.NewCertPool()
}
if !opts.Roots.AppendCertsFromPEM(caPair.Certificate) {
return fmt.Errorf("invalid CA certificates")
}
if _, err = serverCert.Verify(*opts); err != nil {
return fmt.Errorf("failed to verify certificate: %w", err)
}
return nil
}
// CreateAndSignPair given a CA keypair, generate and sign a leaf keypair
func (pair KeyPair) CreateAndSignPair(host string, usage CertType, altDNSNames []string) (*KeyPair, error) {
notBefore := time.Now().Add(time.Minute * -5)
notAfter := notBefore.Add(certificateDuration)
return pair.createAndSignPairWithValidity(host, notBefore, notAfter, usage, altDNSNames)
}
func (pair KeyPair) createAndSignPairWithValidity(
host string,
notBefore,
notAfter time.Time,
usage CertType,
altDNSNames []string,
) (*KeyPair, error) {
caCertificate, err := pair.ParseCertificate()
if err != nil {
return nil, err
}
caPrivateKey, err := pair.ParseECPrivateKey()
if err != nil {
return nil, err
}
// Generate a new private key
leafKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, err
}
// Sign the public part of this key with the CA
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, fmt.Errorf("can't generate serial number: %w", err)
}
leafTemplate := x509.Certificate{
SerialNumber: serialNumber,
NotBefore: notBefore,
NotAfter: notAfter,
BasicConstraintsValid: true,
IsCA: false,
Subject: pkix.Name{
CommonName: host,
},
DNSNames: altDNSNames,
}
leafTemplate.KeyUsage = x509.KeyUsageDigitalSignature | x509.KeyUsageKeyAgreement
switch {
case usage == CertTypeClient:
leafTemplate.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}
case usage == CertTypeServer:
leafTemplate.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}
leafTemplate.KeyUsage |= x509.KeyUsageKeyEncipherment
hosts := strings.Split(host, ",")
for _, h := range hosts {
if ip := net.ParseIP(h); ip != nil {
leafTemplate.IPAddresses = append(leafTemplate.IPAddresses, ip)
} else {
leafTemplate.DNSNames = append(leafTemplate.DNSNames, h)
}
}
}
certificateBytes, err := x509.CreateCertificate(
rand.Reader, &leafTemplate, caCertificate, &leafKey.PublicKey, caPrivateKey)
if err != nil {
return nil, err
}
privateKey, err := x509.MarshalECPrivateKey(leafKey)
if err != nil {
return nil, err
}
return &KeyPair{
Private: encodePrivateKey(privateKey),
Certificate: encodeCertificate(certificateBytes),
}, nil
}
// GenerateCASecret create a k8s CA secret from a key pair
func (pair KeyPair) GenerateCASecret(namespace, name string) *v1.Secret {
return &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
},
Data: map[string][]byte{
CAPrivateKeyKey: pair.Private,
CACertKey: pair.Certificate,
},
Type: v1.SecretTypeOpaque,
}
}
// GenerateCertificateSecret creates a k8s server secret from a key pair
func (pair KeyPair) GenerateCertificateSecret(namespace, name string) *v1.Secret {
return &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
},
Data: map[string][]byte{
TLSPrivateKeyKey: pair.Private,
TLSCertKey: pair.Certificate,
},
Type: v1.SecretTypeTLS,
}
}
// RenewCertificate create a new certificate for the embedded private
// key, replacing the existing one. The certificate will be signed
// with the passed private key and will have as parent the specified
// parent certificate. If the parent certificate is nil the certificate
// will be self-signed
func (pair *KeyPair) RenewCertificate(caPrivateKey *ecdsa.PrivateKey, parentCertificate *x509.Certificate) error {
oldCertificate, err := pair.ParseCertificate()
if err != nil {
return err
}
notBefore := time.Now().Add(time.Minute * -5)
notAfter := notBefore.Add(certificateDuration)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return err
}
newCertificate := *oldCertificate
newCertificate.NotBefore = notBefore
newCertificate.NotAfter = notAfter
newCertificate.SerialNumber = serialNumber
if parentCertificate == nil {
parentCertificate = &newCertificate
}
tlsPrivateKey, err := pair.ParseECPrivateKey()
if err != nil {
return err
}
certificateBytes, err := x509.CreateCertificate(
rand.Reader,
&newCertificate,
parentCertificate,
&tlsPrivateKey.PublicKey,
caPrivateKey)
if err != nil {
return err
}
pair.Certificate = encodeCertificate(certificateBytes)
return nil
}
// IsExpiring check if the certificate will expire in the configured duration
func (pair *KeyPair) IsExpiring() (bool, *time.Time, error) {
cert, err := pair.ParseCertificate()
if err != nil {
return true, nil, err
}
if time.Now().Before(cert.NotBefore) {
return true, &cert.NotAfter, nil
}
if time.Now().Add(expiringCheckThreshold).After(cert.NotAfter) {
return true, &cert.NotAfter, nil
}
return false, &cert.NotAfter, nil
}
// CreateDerivedCA create a new CA derived from the certificate in the
// keypair
func (pair *KeyPair) CreateDerivedCA(commonName string, organizationalUnit string) (*KeyPair, error) {
certificate, err := pair.ParseCertificate()
if err != nil {
return nil, err
}
key, err := pair.ParseECPrivateKey()
if err != nil {
return nil, err
}
notBefore := time.Now().Add(time.Minute * -5)
notAfter := notBefore.Add(certificateDuration)
return createCAWithValidity(notBefore, notAfter, certificate, key, commonName, organizationalUnit)
}
// CreateRootCA generates a CA returning its keys
func CreateRootCA(commonName string, organizationalUnit string) (*KeyPair, error) {
notBefore := time.Now().Add(time.Minute * -5)
notAfter := notBefore.Add(certificateDuration)
return createCAWithValidity(notBefore, notAfter, nil, nil, commonName, organizationalUnit)
}
// ParseCASecret parse a CA secret to a key pair
func ParseCASecret(secret *v1.Secret) (*KeyPair, error) {
privateKey, ok := secret.Data[CAPrivateKeyKey]
if !ok {
return nil, fmt.Errorf("missing %s secret data", CAPrivateKeyKey)
}
publicKey, ok := secret.Data[CACertKey]
if !ok {
return nil, fmt.Errorf("missing %s secret data", CACertKey)
}
// Verify the key matches the certificate
_, err := tls.X509KeyPair(publicKey, privateKey)
if err != nil {
return nil, err
}
return &KeyPair{
Private: privateKey,
Certificate: publicKey,
}, nil
}
// ParseServerSecret parse a secret for a server to a key pair
func ParseServerSecret(secret *v1.Secret) (*KeyPair, error) {
privateKey, ok := secret.Data[TLSPrivateKeyKey]
if !ok {
return nil, fmt.Errorf("missing %v secret data", TLSPrivateKeyKey)
}
publicKey, ok := secret.Data[TLSCertKey]
if !ok {
return nil, fmt.Errorf("missing %s secret data", TLSCertKey)
}
// Verify the key matches the certificate
_, err := tls.X509KeyPair(publicKey, privateKey)
if err != nil {
return nil, err
}
return &KeyPair{
Private: privateKey,
Certificate: publicKey,
}, nil
}
// createCAWithValidity create a CA with a certain validity, with a parent certificate and signed by a certain
// private key. If the latest two parameters are nil, the CA will be a root one (self-signed)
func createCAWithValidity(
notBefore,
notAfter time.Time,
parentCertificate *x509.Certificate,
parentPrivateKey interface{},
commonName string,
organizationalUnit string,
) (*KeyPair, error) {
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, err
}
rootKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, err
}
rootTemplate := x509.Certificate{
SerialNumber: serialNumber,
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageCertSign,
BasicConstraintsValid: true,
IsCA: true,
Subject: pkix.Name{
CommonName: commonName,
OrganizationalUnit: []string{
organizationalUnit,
},
},
}
if parentCertificate == nil {
parentCertificate = &rootTemplate
}
if parentPrivateKey == nil {
parentPrivateKey = rootKey
}
certificateBytes, err := x509.CreateCertificate(
rand.Reader,
&rootTemplate,
parentCertificate,
&rootKey.PublicKey,
parentPrivateKey)
if err != nil {
return nil, err
}
privateKey, err := x509.MarshalECPrivateKey(rootKey)
if err != nil {
return nil, err
}
return &KeyPair{
Private: encodePrivateKey(privateKey),
Certificate: encodeCertificate(certificateBytes),
}, nil
}
func encodeCertificate(derBytes []byte) []byte {
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
}
func encodePrivateKey(derBytes []byte) []byte {
return pem.EncodeToMemory(&pem.Block{Type: ecPrivateKeyPEMBlockType, Bytes: derBytes})
}