-
Notifications
You must be signed in to change notification settings - Fork 107
/
certs.go
225 lines (187 loc) · 6.17 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
package keptnwebhookcontroller
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"time"
"github.com/keptn/lifecycle-toolkit/keptn-cert-manager/kubeutils"
)
var serialNumberLimit = new(big.Int).Lsh(big.NewInt(1), 128)
const (
renewalThreshold = 12 * time.Hour
RootKey = "ca.key"
RootCert = "ca.crt"
RootCertOld = "ca.crt.old"
ServerKey = "tls.key"
ServerCert = "tls.crt"
)
// Certs handles creation and renewal of CA and SSL/TLS server certificates.
type Certs struct {
Domain string
SrcData map[string][]byte
Data map[string][]byte
Now time.Time
rootPrivateKey *ecdsa.PrivateKey
rootPublicCert *x509.Certificate
}
// Validate checks for certificates and keys on cs.SrcData and renews them if needed. The existing (or new)
// certificates will be stored on cs.Data.
func (cs *Certs) Validate() error {
cs.Data = map[string][]byte{}
if cs.SrcData != nil {
for k, v := range cs.SrcData {
cs.Data[k] = v
}
}
now := cs.Now
if now.IsZero() {
now = time.Now().UTC()
}
renewRootCerts := cs.validateRootCerts(now)
if renewRootCerts {
if err := cs.generateRootCerts(cs.Domain, now); err != nil {
return err
}
}
if renewRootCerts || cs.validateServerCerts(now) {
return cs.generateServerCerts(cs.Domain, now)
}
return nil
}
func (cs *Certs) validateRootCerts(now time.Time) bool {
if cs.Data[RootKey] == nil || cs.Data[RootCert] == nil {
////log.Info("no root certificates found, creating")
return true
}
var err error
if block, _ := pem.Decode(cs.Data[RootCert]); block == nil {
//log.Info("failed to parse root certificates, renewing", "error", "can't decode PEM file")
return true
} else if cs.rootPublicCert, err = x509.ParseCertificate(block.Bytes); err != nil {
//log.Info("failed to parse root certificates, renewing", "error", err)
return true
} else if now.After(cs.rootPublicCert.NotAfter.Add(-renewalThreshold)) {
//log.Info("root certificates are about to expire, renewing", "current", now, "expiration", cs.rootPublicCert.NotAfter)
return true
}
if block, _ := pem.Decode(cs.Data[RootKey]); block == nil {
//log.Info("failed to parse root key, renewing", "error", "can't decode PEM file")
return true
} else if cs.rootPrivateKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil {
//log.Info("failed to parse root key, renewing", "error", err)
return true
}
return false
}
func (cs *Certs) validateServerCerts(now time.Time) bool {
if cs.Data[ServerKey] == nil || cs.Data[ServerCert] == nil {
//log.Info("no server certificates found, creating")
return true
}
isValid, err := kubeutils.ValidateCertificateExpiration(cs.Data[ServerCert], renewalThreshold, now)
if err != nil || !isValid {
//log.Info("server certificate failed to parse or is outdated")
return true
}
return false
}
func (cs *Certs) generateRootCerts(domain string, now time.Time) error {
// Generate CA root keys
//log.Info("generating root certificate")
privateKey, err := cs.generatePrivateKey(RootKey)
if err != nil {
return err
}
cs.rootPrivateKey = privateKey
// Generate CA root certificate
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return fmt.Errorf("failed to generate serial number for root certificate: %w", err)
}
cs.rootPublicCert = &x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Country: []string{"AT"},
Province: []string{"KL"},
Locality: []string{"Klagenfurt"},
Organization: []string{"Keptn"},
OrganizationalUnit: []string{"LifecycleToolkit"},
CommonName: domain,
},
IsCA: true,
NotBefore: now,
NotAfter: now.Add(365 * 24 * time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
rootPublicCertDER, err := x509.CreateCertificate(
rand.Reader,
cs.rootPublicCert,
cs.rootPublicCert,
cs.rootPrivateKey.Public(),
cs.rootPrivateKey)
if err != nil {
return fmt.Errorf("failed to generate root certificate: %w", err)
}
cs.Data[RootCertOld] = cs.Data[RootCert]
cs.Data[RootCert] = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: rootPublicCertDER})
//log.Info("root certificate generated")
return nil
}
func (cs *Certs) generateServerCerts(domain string, now time.Time) error {
// Generate server keys
privateKey, err := cs.generatePrivateKey(ServerKey)
if err != nil {
return err
}
// Generate server certificate
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return fmt.Errorf("failed to generate serial number for server certificate: %w", err)
}
tpl := &x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Country: []string{"AT"},
Province: []string{"KL"},
Locality: []string{"Klagenfurt"},
Organization: []string{"Keptn"},
OrganizationalUnit: []string{"LifecycleToolkit"},
CommonName: domain,
},
DNSNames: []string{domain},
NotBefore: now,
NotAfter: now.Add(7 * 24 * time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
serverPublicCertDER, err := x509.CreateCertificate(rand.Reader, tpl, cs.rootPublicCert, privateKey.Public(), cs.rootPrivateKey)
if err != nil {
return fmt.Errorf("failed to generate server certificate: %w", err)
}
cs.Data[ServerCert] = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: serverPublicCertDER})
//log.Info("server certificate generated")
return nil
}
func (cs *Certs) generatePrivateKey(dataKey string) (*ecdsa.PrivateKey, error) {
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, fmt.Errorf("failed to generate server private key: %w", err)
}
x509Encoded, err := x509.MarshalECPrivateKey(privateKey)
if err != nil {
return nil, err
}
cs.Data[dataKey] = pem.EncodeToMemory(&pem.Block{
Type: "PRIVATE KEY",
Bytes: x509Encoded,
})
return privateKey, nil
}