/
certificate.go
310 lines (263 loc) · 10.2 KB
/
certificate.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
// Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// 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 secrets
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"math/big"
"net"
"os"
"path/filepath"
"time"
"github.com/gardener/gardener/pkg/utils"
)
// CertType is a string alias for certificate types.
type CertType string
const (
// CACert indicates that the certificate should be a certificate authority.
CACert CertType = "ca"
// ServerCert indicates that the certificate should have the ExtKeyUsageServerAuth usage.
ServerCert CertType = "server"
// ClientCert indicates that the certificate should have the ExtKeyUsageClientAuth usage.
ClientCert CertType = "client"
// ServerClientCert indicates that the certificate should have both the ExtKeyUsageServerAuth and ExtKeyUsageClientAuth usage.
ServerClientCert CertType = "both"
// DataKeyCertificate is the key in a secret data holding the certificate.
DataKeyCertificate = "tls.crt"
// DataKeyPrivateKey is the key in a secret data holding the private key.
DataKeyPrivateKey = "tls.key"
// DataKeyCertificateCA is the key in a secret data holding the CA certificate.
DataKeyCertificateCA = "ca.crt"
// DataKeyPrivateKeyCA is the key in a secret data holding the CA private key.
DataKeyPrivateKeyCA = "ca.key"
)
const (
// PKCS1 certificate format
PKCS1 = iota
// PKCS8 certificate format
PKCS8
)
// CertificateSecretConfig contains the specification a to-be-generated CA, server, or client certificate.
// It always contains a 2048-bit RSA private key.
type CertificateSecretConfig struct {
Name string
CommonName string
Organization []string
DNSNames []string
IPAddresses []net.IP
CertType CertType
SigningCA *Certificate
PKCS int
Validity *time.Duration
SkipPublishingCACertificate bool
}
// Certificate contains the private key, and the certificate. It does also contain the CA certificate
// in case it is no CA. Otherwise, the <CA> field is nil.
type Certificate struct {
Name string
CA *Certificate
SkipPublishingCACertificate bool
PrivateKey *rsa.PrivateKey
PrivateKeyPEM []byte
Certificate *x509.Certificate
CertificatePEM []byte
}
// GetName returns the name of the secret.
func (s *CertificateSecretConfig) GetName() string {
return s.Name
}
// Generate implements ConfigInterface.
func (s *CertificateSecretConfig) Generate() (DataInterface, error) {
return s.GenerateCertificate()
}
// GenerateCertificate is the same as Generate but returns a *Certificate instead of the DataInterface.
func (s *CertificateSecretConfig) GenerateCertificate() (*Certificate, error) {
certificateObj := &Certificate{
Name: s.Name,
CA: s.SigningCA,
SkipPublishingCACertificate: s.SkipPublishingCACertificate,
}
// If no cert type is given then we only return a certificate object that contains the CA.
if s.CertType != "" {
privateKey, err := GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, err
}
var (
certificate = s.generateCertificateTemplate()
certificateSigner = certificate
privateKeySigner = privateKey
)
if s.SigningCA != nil {
certificateSigner = s.SigningCA.Certificate
privateKeySigner = s.SigningCA.PrivateKey
}
certificatePEM, err := signCertificate(certificate, privateKey, certificateSigner, privateKeySigner)
if err != nil {
return nil, err
}
var pk []byte
if s.PKCS == PKCS1 {
pk = utils.EncodePrivateKey(privateKey)
} else if s.PKCS == PKCS8 {
pk, err = utils.EncodePrivateKeyInPKCS8(privateKey)
if err != nil {
return nil, err
}
}
certificateObj.PrivateKey = privateKey
certificateObj.PrivateKeyPEM = pk
certificateObj.Certificate = certificate
certificateObj.CertificatePEM = certificatePEM
}
return certificateObj, nil
}
// SecretData computes the data map which can be used in a Kubernetes secret.
func (c *Certificate) SecretData() map[string][]byte {
data := map[string][]byte{}
switch {
case c.CA == nil:
// The certificate is a CA certificate itself, so we use different keys in the secret data (for backwards-
// compatibility).
data[DataKeyCertificateCA] = c.CertificatePEM
data[DataKeyPrivateKeyCA] = c.PrivateKeyPEM
case c.CA != nil:
// The certificate is not a CA certificate, so we add the signing CA certificate to it and use different
// keys in the secret data.
data[DataKeyPrivateKey] = c.PrivateKeyPEM
data[DataKeyCertificate] = c.CertificatePEM
if !c.SkipPublishingCACertificate {
data[DataKeyCertificateCA] = c.CA.CertificatePEM
}
}
return data
}
// LoadCertificate takes a byte slice representation of a certificate and the corresponding private key, and returns its de-serialized private
// key, certificate template and PEM certificate which can be used to sign other x509 certificates.
func LoadCertificate(name string, privateKeyPEM, certificatePEM []byte) (*Certificate, error) {
privateKey, err := utils.DecodePrivateKey(privateKeyPEM)
if err != nil {
return nil, err
}
certificate, err := utils.DecodeCertificate(certificatePEM)
if err != nil {
return nil, err
}
return &Certificate{
Name: name,
PrivateKey: privateKey,
PrivateKeyPEM: privateKeyPEM,
Certificate: certificate,
CertificatePEM: certificatePEM,
}, nil
}
// generateCertificateTemplate creates a X509 Certificate object based on the provided information regarding
// common name, organization, SANs (DNS names and IP addresses). It can create a server or a client certificate
// or both, depending on the <certType> value. If <isCACert> is true, then a CA certificate is being created.
// The certificates a valid for 10 years.
func (s *CertificateSecretConfig) generateCertificateTemplate() *x509.Certificate {
now := Clock.Now()
expiration := now.AddDate(10, 0, 0) // + 10 years
if s.Validity != nil {
expiration = now.Add(*s.Validity)
}
var (
serialNumber, _ = rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
isCA = s.CertType == CACert
template = &x509.Certificate{
BasicConstraintsValid: true,
IsCA: isCA,
SerialNumber: serialNumber,
NotBefore: now,
NotAfter: expiration,
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
Subject: pkix.Name{
CommonName: s.CommonName,
Organization: s.Organization,
},
DNSNames: s.DNSNames,
IPAddresses: s.IPAddresses,
}
)
switch s.CertType {
case CACert:
template.KeyUsage |= x509.KeyUsageCertSign | x509.KeyUsageCRLSign
case ServerCert:
template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}
case ClientCert:
template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}
case ServerClientCert:
template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}
}
return template
}
// SignCertificate takes a <certificateTemplate> and a <certificateTemplateSigner> which is used to sign
// the first. It also requires the corresponding private keys of both certificates. The created certificate
// is returned as byte slice.
func signCertificate(certificateTemplate *x509.Certificate, privateKey *rsa.PrivateKey, certificateTemplateSigner *x509.Certificate, privateKeySigner *rsa.PrivateKey) ([]byte, error) {
certificate, err := x509.CreateCertificate(rand.Reader, certificateTemplate, certificateTemplateSigner, &privateKey.PublicKey, privateKeySigner)
if err != nil {
return nil, err
}
return utils.EncodeCertificate(certificate), nil
}
// TemporaryDirectoryForSelfGeneratedTLSCertificatesPattern is a constant for the pattern used when creating a temporary
// directory for self-generated certificates.
const TemporaryDirectoryForSelfGeneratedTLSCertificatesPattern = "self-generated-server-certificates-"
// SelfGenerateTLSServerCertificate generates a new CA certificate and signs a server certificate with it. It'll store
// the generated CA + server certificate bytes into a temporary directory with the default filenames, e.g. `DataKeyCertificateCA`.
// The function will return the *Certificate object as well as the path of the temporary directory where the
// certificates are stored.
func SelfGenerateTLSServerCertificate(name string, dnsNames []string, ips []net.IP) (cert *Certificate, ca *Certificate, dir string, rErr error) {
tempDir, err := os.MkdirTemp("", TemporaryDirectoryForSelfGeneratedTLSCertificatesPattern)
if err != nil {
return nil, nil, "", err
}
caCertificate, err := (&CertificateSecretConfig{
Name: name,
CommonName: name,
CertType: CACert,
}).GenerateCertificate()
if err != nil {
return nil, nil, "", err
}
caCertificateData := caCertificate.SecretData()
if err := os.WriteFile(filepath.Join(tempDir, DataKeyCertificateCA), caCertificateData[DataKeyCertificateCA], 0644); err != nil {
return nil, nil, "", err
}
if err := os.WriteFile(filepath.Join(tempDir, DataKeyPrivateKeyCA), caCertificateData[DataKeyPrivateKeyCA], 0644); err != nil {
return nil, nil, "", err
}
certificate, err := (&CertificateSecretConfig{
Name: name,
CommonName: name,
DNSNames: dnsNames,
IPAddresses: ips,
CertType: ServerCert,
SigningCA: caCertificate,
}).GenerateCertificate()
if err != nil {
return nil, nil, "", err
}
certificateData := certificate.SecretData()
if err := os.WriteFile(filepath.Join(tempDir, DataKeyCertificate), certificateData[DataKeyCertificate], 0644); err != nil {
return nil, nil, "", err
}
if err := os.WriteFile(filepath.Join(tempDir, DataKeyPrivateKey), certificateData[DataKeyPrivateKey], 0644); err != nil {
return nil, nil, "", err
}
return certificate, caCertificate, tempDir, nil
}