-
Notifications
You must be signed in to change notification settings - Fork 13
/
main.go
352 lines (291 loc) · 9.62 KB
/
main.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
/*
Copyright 2021 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 main
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"flag"
"fmt"
"net"
"net/url"
"strings"
"time"
cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1"
cmmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1"
cmclient "github.com/cert-manager/cert-manager/pkg/client/clientset/versioned"
"github.com/cert-manager/cert-manager/pkg/util/pki"
"k8s.io/client-go/rest"
"k8s.io/klog/v2/klogr"
"k8s.io/utils/clock"
"github.com/cert-manager/csi-lib/driver"
"github.com/cert-manager/csi-lib/manager"
"github.com/cert-manager/csi-lib/metadata"
"github.com/cert-manager/csi-lib/storage"
)
const (
IssuerNameKey string = "csi.cert-manager.io/issuer-name"
IssuerKindKey string = "csi.cert-manager.io/issuer-kind"
IssuerGroupKey string = "csi.cert-manager.io/issuer-group"
CommonNameKey string = "csi.cert-manager.io/common-name"
DNSNamesKey string = "csi.cert-manager.io/dns-names"
IPSANsKey string = "csi.cert-manager.io/ip-sans"
URISANsKey string = "csi.cert-manager.io/uri-sans"
DurationKey string = "csi.cert-manager.io/duration"
IsCAKey string = "csi.cert-manager.io/is-ca"
KeyUsagesKey string = "csi.cert-manager.io/key-usages"
CAFileKey string = "csi.cert-manager.io/ca-file"
CertFileKey string = "csi.cert-manager.io/certificate-file"
KeyFileKey string = "csi.cert-manager.io/privatekey-file"
RenewBeforeKey string = "csi.cert-manager.io/renew-before"
ReusePrivateKey string = "csi.cert-manager.io/reuse-private-key"
// fs-group is used to optionally set the GID ownership of the volume's
// files. Useful when running containers with a specified user and group.
FsGroupKey string = "csi.cert-manager.io/fs-group"
)
var (
nodeID = flag.String("node-id", "", "Name of the node the driver is running on")
endpoint = flag.String("endpoint", "", "Path to the unix socket used to listen for gRPC requests")
dataRoot = flag.String("data-root", "", "Path to the in-memory data directory used to store data")
)
func main() {
flag.Parse()
if *nodeID == "" {
panic("-node-id must be set")
}
if *endpoint == "" {
panic("-endpoint must be set")
}
if *dataRoot == "" {
panic("-data-root must be set")
}
log := klogr.New()
restConfig, err := rest.InClusterConfig()
if err != nil {
panic("cannot load in-cluster config")
}
store, err := storage.NewFilesystem(log, *dataRoot)
if err != nil {
panic("failed to setup filesystem: " + err.Error())
}
store.FSGroupVolumeAttributeKey = FsGroupKey
d, err := driver.New(*endpoint, log, driver.Options{
DriverName: "csi.cert-manager.io",
DriverVersion: "v0.0.1",
NodeID: *nodeID,
Store: store,
Manager: manager.NewManagerOrDie(manager.Options{
Client: cmclient.NewForConfigOrDie(restConfig),
MetadataReader: store,
Clock: clock.RealClock{},
Log: &log,
NodeID: *nodeID,
GeneratePrivateKey: (&keygen{store: store}).generatePrivateKey,
GenerateRequest: generateRequest,
SignRequest: signRequest,
WriteKeypair: (&writer{store: store}).writeKeypair,
}),
})
if err != nil {
panic("failed to setup driver: " + err.Error())
}
if err := d.Run(); err != nil {
panic("failed running driver: " + err.Error())
}
}
// keygen wraps the storage backend to allow for re-using private keys when
// re-issuing a certificate.
type keygen struct {
store *storage.Filesystem
}
// generatePrivateKey generates a 2048-bit RSA private key
func (k *keygen) generatePrivateKey(meta metadata.Metadata) (crypto.PrivateKey, error) {
// Currently no options are exposed for customising the kind of key generated
genPrivateKey := func() (crypto.PrivateKey, error) { return rsa.GenerateKey(rand.Reader, 2048) }
// By default, generate a new private key each time.
if meta.VolumeContext[ReusePrivateKey] != "true" {
return genPrivateKey()
}
bytes, err := k.store.ReadFile(meta.VolumeID, "tls.key")
if errors.Is(err, storage.ErrNotFound) {
// Generate a new key if one is not found on disk
return genPrivateKey()
}
pk, err := pki.DecodePrivateKeyBytes(bytes)
if err != nil {
// Generate a new key if the existing one cannot be decoded
return genPrivateKey()
}
return pk, nil
}
func generateRequest(meta metadata.Metadata) (*manager.CertificateRequestBundle, error) {
namespace := meta.VolumeContext["csi.storage.k8s.io/pod.namespace"]
uris, err := parseURIs(meta.VolumeContext[URISANsKey])
if err != nil {
return nil, fmt.Errorf("invalid URI provided in %q attribute: %w", URISANsKey, err)
}
ips := parseIPAddresses(meta.VolumeContext[IPSANsKey])
dnsNames := strings.Split(meta.VolumeContext[DNSNamesKey], ",")
commonName := meta.VolumeContext[CommonNameKey]
duration := cmapi.DefaultCertificateDuration
if durStr, ok := meta.VolumeContext[DurationKey]; ok {
duration, err = time.ParseDuration(durStr)
if err != nil {
return nil, fmt.Errorf("invalid %q attribute: %w", DurationKey, err)
}
}
isCA := false
if isCAStr, ok := meta.VolumeContext[IsCAKey]; ok {
switch strings.ToLower(isCAStr) {
case "true":
isCA = true
case "false":
isCA = false
}
}
return &manager.CertificateRequestBundle{
Request: &x509.CertificateRequest{
Subject: pkix.Name{
CommonName: commonName,
},
DNSNames: dnsNames,
IPAddresses: ips,
URIs: uris,
},
IsCA: isCA,
Namespace: namespace,
Duration: duration,
Usages: keyUsagesFromAttributes(meta.VolumeContext[KeyUsagesKey]),
IssuerRef: cmmeta.ObjectReference{
Name: meta.VolumeContext[IssuerNameKey],
Kind: meta.VolumeContext[IssuerKindKey],
Group: meta.VolumeContext[IssuerGroupKey],
},
Annotations: nil,
}, nil
}
func signRequest(_ metadata.Metadata, key crypto.PrivateKey, request *x509.CertificateRequest) ([]byte, error) {
csrDer, err := x509.CreateCertificateRequest(rand.Reader, request, key)
if err != nil {
return nil, err
}
return pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE REQUEST",
Bytes: csrDer,
}), nil
}
// writer wraps the storage backend to allow access for writing data
type writer struct {
store storage.Interface
}
func (w *writer) writeKeypair(meta metadata.Metadata, key crypto.PrivateKey, chain []byte, ca []byte) error {
keyPEM := pem.EncodeToMemory(
&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key.(*rsa.PrivateKey)),
},
)
pkFile := "tls.key"
if meta.VolumeContext[KeyFileKey] != "" {
pkFile = meta.VolumeContext[KeyFileKey]
}
crtFile := "tls.crt"
if meta.VolumeContext[CertFileKey] != "" {
crtFile = meta.VolumeContext[CertFileKey]
}
caFile := "ca.crt"
if meta.VolumeContext[CAFileKey] != "" {
caFile = meta.VolumeContext[CAFileKey]
}
nextIssuanceTime, err := calculateNextIssuanceTime(meta, chain)
if err != nil {
return fmt.Errorf("calculating next issuance time: %w", err)
}
if err := w.store.WriteFiles(meta, map[string][]byte{
pkFile: keyPEM,
crtFile: chain,
caFile: ca,
}); err != nil {
return fmt.Errorf("writing data: %w", err)
}
meta.NextIssuanceTime = &nextIssuanceTime
if err := w.store.WriteMetadata(meta.VolumeID, meta); err != nil {
return fmt.Errorf("writing metadata: %w", err)
}
return nil
}
func calculateNextIssuanceTime(meta metadata.Metadata, chain []byte) (time.Time, error) {
block, _ := pem.Decode(chain)
crt, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return time.Time{}, fmt.Errorf("parsing issued certificate: %w", err)
}
actualDuration := crt.NotAfter.Sub(crt.NotBefore)
// if not explicitly set, renew once a certificate is 2/3rds of the way through its lifetime
renewBeforeNotAfter := actualDuration / 3
if meta.VolumeContext[RenewBeforeKey] != "" {
renewBeforeDuration, err := time.ParseDuration(meta.VolumeContext[RenewBeforeKey])
if err != nil {
return time.Time{}, fmt.Errorf("parsing requested renew-before duration: %w", err)
}
// If the requested renewBefore would cause the certificate to be immediately re-issued,
// ignore the requested renew before and renew 2/3rds of the way through its lifetime.
if crt.NotBefore.Add(renewBeforeDuration).Before(crt.NotAfter) {
renewBeforeNotAfter = renewBeforeDuration
}
}
return crt.NotAfter.Add(-renewBeforeNotAfter), nil
}
func parseIPAddresses(ips string) []net.IP {
if len(ips) == 0 {
return nil
}
ipsS := strings.Split(ips, ",")
var ipAddresses []net.IP
for _, ipName := range ipsS {
ip := net.ParseIP(ipName)
if ip != nil {
ipAddresses = append(ipAddresses, ip)
}
}
return ipAddresses
}
func parseURIs(uris string) ([]*url.URL, error) {
if len(uris) == 0 {
return nil, nil
}
urisS := strings.Split(uris, ",")
var urisURL []*url.URL
for _, uriS := range urisS {
uri, err := url.Parse(uriS)
if err != nil {
return nil, err
}
urisURL = append(urisURL, uri)
}
return urisURL, nil
}
func keyUsagesFromAttributes(usagesCSV string) []cmapi.KeyUsage {
if len(usagesCSV) == 0 {
return nil
}
var keyUsages []cmapi.KeyUsage
for _, usage := range strings.Split(usagesCSV, ",") {
keyUsages = append(keyUsages, cmapi.KeyUsage(strings.TrimSpace(usage)))
}
return keyUsages
}