-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
443 lines (407 loc) · 12.8 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
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
package main
import (
"context"
"crypto/x509"
"encoding/pem"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"time"
"github.com/GalleyBytes/terraform-operator-mutator/internal/webhook"
"github.com/isaaguilar/selfsigned"
addmissionregistrationv1 "k8s.io/api/admissionregistration/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
var (
// MutationWebhookConfiguration Setup
namespace string
caKeyFilename string
caCertFilename string
tlsKeyFilename string
tlsCertFilename string
mutatingWebhookConfigurationName string
serviceName string
secretName string
webhookURI string
)
func getFlags() {
flag.StringVar(&caKeyFilename, "ca-key", "/etc/certs/ca.key", "Path to the CA key")
flag.StringVar(&caCertFilename, "ca-cert", "/etc/certs/ca.crt", "Path to the CA certificate")
flag.StringVar(&tlsKeyFilename, "tls-key", "/etc/certs/tls.key", "Path to the TLS key")
flag.StringVar(&tlsCertFilename, "tls-cert", "/etc/certs/tls.crt", "Path to the TLS certificate")
flag.StringVar(&secretName, "secret-name", "terraform-mutator-certs", "Name of the secret used to mount certs")
flag.StringVar(&namespace, "namespace", "tf-system", "Namespace the service is deployed into")
flag.StringVar(&mutatingWebhookConfigurationName, "mutating-webhook-configuration-name", "terraform-mutator", "Name of webhook resource")
flag.StringVar(&webhookURI, "webhook-uri", "/terraform", "Name of webhook uri")
flag.StringVar(&serviceName, "service-name", "terraform-mutator", "Name of the service to back up mutating webhook configuration")
flag.Parse()
}
func kubernetesConfig(kubeconfigPath string) *rest.Config {
config, err := clientcmd.BuildConfigFromFlags("", kubeconfigPath)
if err != nil {
log.Fatal("Failed to get config for clientset")
}
return config
}
type Manager struct {
ctx context.Context
clientset kubernetes.Interface
caKeyFilename string
caCertFilename string
tlsKeyFilename string
tlsCertFilename string
namespace string
secretName string
serviceName string
webhookURI string
dnsNames []string
mutatingWebhookConfigurationName string
isReadyCh chan (bool)
started bool
}
func (m Manager) getOrCreateSecret() *corev1.Secret {
secretClient := m.clientset.CoreV1().Secrets(m.namespace)
secret, err := secretClient.Get(m.ctx, m.secretName, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
selfSignedCert := selfsigned.NewSelfSignedCertOrDie(m.dnsNames)
secret, err = secretClient.Create(
m.ctx,
&corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: m.secretName,
Namespace: m.namespace,
},
Type: corev1.SecretTypeTLS,
Data: map[string][]byte{
"ca.key": selfSignedCert.CAKey,
"ca.crt": selfSignedCert.CACert,
"tls.crt": selfSignedCert.TLSCert,
"tls.key": selfSignedCert.TLSKey,
},
},
metav1.CreateOptions{},
)
if err != nil {
log.Panic(err)
}
log.Printf("Created TLS certs in secret/%s\n", secret.Name)
} else {
log.Panic(err)
}
}
return secret
}
func (m Manager) updateSecret(selfSignedCert *selfsigned.SelfSignedCert) *corev1.Secret {
err := selfSignedCert.UpdateTLS()
if err != nil {
log.Panic(err)
}
secretClient := m.clientset.CoreV1().Secrets(m.namespace)
secret, err := secretClient.Get(m.ctx, m.secretName, metav1.GetOptions{})
if err != nil && errors.IsNotFound(err) {
log.Panicf("Expected secret '%s' to exist but was not found", m.secretName)
}
secret.Data = map[string][]byte{
"ca.key": selfSignedCert.CAKey,
"ca.crt": selfSignedCert.CACert,
"tls.crt": selfSignedCert.TLSCert,
"tls.key": selfSignedCert.TLSKey,
}
secret, err = secretClient.Update(m.ctx, secret, metav1.UpdateOptions{})
if err != nil {
log.Panic(err)
}
return secret
}
func x509Cert(certData []byte) (*x509.Certificate, error) {
block, _ := pem.Decode(certData)
if block == nil {
return nil, fmt.Errorf("failed to parse certificate PEM")
}
cert, xerr := x509.ParseCertificate(block.Bytes)
if xerr != nil {
return nil, fmt.Errorf("failed to parse certificate: " + xerr.Error())
}
return cert, nil
}
// isCertValid checks cert expiration and cert dns names
func isCertValid(caCertData, tlsCertData []byte, dnsNames []string) bool {
roots := x509.NewCertPool()
ok := roots.AppendCertsFromPEM(caCertData)
if !ok {
log.Println("failed to parse root certificate")
return false
}
cert, err := x509Cert(tlsCertData)
if err != nil {
log.Println(err.Error())
return false
}
t := time.Now()
opts := x509.VerifyOptions{
CurrentTime: t.Add(24 * 30 * time.Hour), // 30 days
DNSName: dnsNames[0],
Roots: roots,
}
if _, err := cert.Verify(opts); err != nil {
log.Println("failed to verify certificate: " + err.Error())
return false
}
return true
}
func fileExistAndIsNotEmpty(filename string) bool {
file, err := os.Stat(filename)
if err != nil {
return false
}
if os.IsNotExist(err) {
return false
}
if file.Size() == 0 {
return false
}
return true
}
func isX509Format(b []byte) bool {
block, _ := pem.Decode(b)
if block == nil {
return false
}
isKey := false
isCert := false
if _, err := x509.ParsePKCS1PrivateKey(block.Bytes); err == nil {
isKey = true
}
if _, err := x509.ParseCertificate(block.Bytes); err == nil {
isCert = true
}
if !isKey && !isCert {
return false
}
return true
}
// int32p returns an int32 pointer to the int32 value passed in
func int32p(x int32) *int32 {
return &x
}
// stringp returns an string pointer to the string value passed in
func stringp(s string) *string {
return &s
}
func (m Manager) createOrUpdateMutatingWebhookConfiguration() {
mutatingWebhookConfigurationClient := m.clientset.AdmissionregistrationV1().MutatingWebhookConfigurations()
_, err := mutatingWebhookConfigurationClient.Get(m.ctx, m.mutatingWebhookConfigurationName, metav1.GetOptions{})
if err != nil {
if !errors.IsNotFound(err) {
log.Panic(err)
}
// Create it
caBundle, err := m.caBundle()
if err != nil {
log.Panic(err)
}
fail := addmissionregistrationv1.Fail
none := addmissionregistrationv1.SideEffectClassNone
mutatingWebhook := addmissionregistrationv1.MutatingWebhook{
NamespaceSelector: &metav1.LabelSelector{
MatchExpressions: []metav1.LabelSelectorRequirement{
{
Key: mutatingWebhookConfigurationName + "-exempt",
Operator: metav1.LabelSelectorOpNotIn,
Values: []string{
"1",
},
},
},
},
ObjectSelector: &metav1.LabelSelector{
MatchExpressions: []metav1.LabelSelectorRequirement{
{
Key: mutatingWebhookConfigurationName + "-exempt",
Operator: metav1.LabelSelectorOpNotIn,
Values: []string{
"1",
},
},
},
},
Name: fmt.Sprintf("%s.galleybytes.com", m.mutatingWebhookConfigurationName),
ClientConfig: addmissionregistrationv1.WebhookClientConfig{
CABundle: caBundle,
Service: &addmissionregistrationv1.ServiceReference{
Namespace: m.namespace,
Name: m.serviceName,
Port: int32p(443),
Path: &m.webhookURI,
},
},
AdmissionReviewVersions: []string{"v1"},
TimeoutSeconds: int32p(30),
Rules: []addmissionregistrationv1.RuleWithOperations{
{
Operations: []addmissionregistrationv1.OperationType{addmissionregistrationv1.Create},
Rule: addmissionregistrationv1.Rule{
APIGroups: []string{"tf.isaaguilar.com"},
APIVersions: []string{"v1alpha2"},
Resources: []string{"terraforms"},
},
},
},
FailurePolicy: &fail,
SideEffects: &none,
}
mutatingWebhookConfiguration := addmissionregistrationv1.MutatingWebhookConfiguration{
ObjectMeta: metav1.ObjectMeta{
Name: m.mutatingWebhookConfigurationName,
},
Webhooks: []addmissionregistrationv1.MutatingWebhook{
mutatingWebhook,
},
}
_, err = mutatingWebhookConfigurationClient.Create(m.ctx, &mutatingWebhookConfiguration, metav1.CreateOptions{})
if err != nil {
log.Panic(err)
}
log.Println("Created new mutating webhook configuration")
}
}
func (m Manager) caBundle() ([]byte, error) {
foundCACert := fileExistAndIsNotEmpty(m.caCertFilename)
if !foundCACert {
return []byte{}, fmt.Errorf("could not find '%s'", m.caCertFilename)
}
caCert, err := ioutil.ReadFile(m.caCertFilename)
if err != nil {
return []byte{}, err
}
return caCert, nil
}
func (m Manager) certMgmt() {
recheckAfter := time.Duration(10 * time.Second)
for {
secret := m.getOrCreateSecret()
foundCAKey := fileExistAndIsNotEmpty(m.caKeyFilename)
foundCACert := fileExistAndIsNotEmpty(m.caCertFilename)
foundTLSKey := fileExistAndIsNotEmpty(m.tlsKeyFilename)
foundTLSCert := fileExistAndIsNotEmpty(m.tlsCertFilename)
if !foundCAKey || !foundCACert || !foundTLSKey || !foundTLSCert {
log.Println("Waiting for certs to be mounted")
recheckAfter = time.Duration(10 * time.Second)
time.Sleep(recheckAfter)
continue
}
caKey, err := ioutil.ReadFile(m.caKeyFilename)
if err != nil {
log.Panic(err)
}
caCert, err := ioutil.ReadFile(m.caCertFilename)
if err != nil {
log.Panic(err)
}
tlsCert, err := ioutil.ReadFile(m.tlsCertFilename)
if err != nil {
log.Panic(err)
}
tlsKey, err := ioutil.ReadFile(m.tlsKeyFilename)
if err != nil {
log.Panic(err)
}
if !isX509Format(caKey) {
log.Printf("Failed to parse '%s'", m.caKeyFilename)
recheckAfter = time.Duration(10 * time.Second)
time.Sleep(recheckAfter)
continue
}
if !isX509Format(caCert) {
log.Printf("Failed to parse '%s'", m.caCertFilename)
recheckAfter = time.Duration(10 * time.Second)
time.Sleep(recheckAfter)
continue
}
if !isX509Format(tlsKey) {
log.Printf("Failed to parse '%s'", m.tlsKeyFilename)
recheckAfter = time.Duration(10 * time.Second)
time.Sleep(recheckAfter)
continue
}
if !isX509Format(tlsCert) {
log.Printf("Failed to parse '%s'", m.tlsCertFilename)
recheckAfter = time.Duration(10 * time.Second)
time.Sleep(recheckAfter)
continue
}
selfSignedCert := &selfsigned.SelfSignedCert{
Signer: selfsigned.Signer{
CAKey: caKey,
CACert: caCert,
},
TLSCert: tlsCert,
TLSKey: tlsKey,
}
if string(secret.Data["ca.key"]) == string(caKey) &&
string(secret.Data["ca.crt"]) == string(caCert) &&
string(secret.Data["tls.key"]) == string(tlsKey) &&
string(secret.Data["tls.crt"]) == string(tlsCert) {
if isCertValid(caCert, tlsCert, m.dnsNames) {
recheckAfter = time.Duration(24 * time.Hour)
// recheckAfter = time.Duration(3 * time.Second)
log.Printf("Cert validation passed. Will re-check in %s", recheckAfter.String())
// Create or update the mutating webhook before starting the service
m.createOrUpdateMutatingWebhookConfiguration()
if !m.started {
m.isReadyCh <- true
m.started = true
}
} else {
log.Printf("Certs are no longer valid. Updating secret '%s' with new certs\n", m.secretName)
m.updateSecret(selfSignedCert)
recheckAfter = time.Duration(10 * time.Second)
}
} else {
log.Printf("Mounted certs do not match certs in 'secret/%s'. If this error continues, the pod may be misconfigured.\n", m.secretName)
recheckAfter = time.Duration(10 * time.Second)
}
time.Sleep(recheckAfter)
}
}
func genDNSNames(svc, ns string) []string {
return []string{
svc,
fmt.Sprintf("%s.%s", svc, ns),
fmt.Sprintf("%s.%s.svc", svc, ns),
fmt.Sprintf("%s.%s.svc.cluster.local", svc, ns),
}
}
func main() {
getFlags()
// Setup Dynamic rest client to access v1alpha2
config := kubernetesConfig(os.Getenv("KUBECONFIG"))
// kubeclient
clientset := kubernetes.NewForConfigOrDie(config)
mgr := Manager{
ctx: context.TODO(),
clientset: clientset,
caKeyFilename: caKeyFilename,
caCertFilename: caCertFilename,
tlsKeyFilename: tlsKeyFilename,
tlsCertFilename: tlsCertFilename,
namespace: namespace,
serviceName: serviceName,
secretName: secretName,
webhookURI: webhookURI,
mutatingWebhookConfigurationName: mutatingWebhookConfigurationName,
dnsNames: genDNSNames(serviceName, namespace),
isReadyCh: make(chan bool),
}
go mgr.certMgmt()
<-mgr.isReadyCh
webhook.StartWebhook(tlsCertFilename, tlsKeyFilename, webhookURI, serviceName)
}