/
generate_istio_mtls_cert.go
214 lines (189 loc) · 5.89 KB
/
generate_istio_mtls_cert.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
/*
Copyright 2022 Flant JSC
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 hooks
import (
"crypto/x509"
"encoding/pem"
"fmt"
"time"
"github.com/flant/addon-operator/pkg/module_manager/go_hook"
"github.com/flant/addon-operator/sdk"
"github.com/flant/shell-operator/pkg/kube_events_manager/types"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"github.com/deckhouse/deckhouse/go_lib/certificate"
)
const (
mTLSCrtPath = "prometheus.internal.prometheusScraperIstioMTLS.certificate"
mTLSKeyPath = "prometheus.internal.prometheusScraperIstioMTLS.key"
)
var _ = sdk.RegisterFunc(&go_hook.HookConfig{
Queue: "/modules/prometheus/generate_istio_mtls_cert",
Kubernetes: []go_hook.KubernetesConfig{
{
Name: "istio_secret_ca",
ApiVersion: "v1",
Kind: "Secret",
FilterFunc: applySecertIstioCAFilter,
NamespaceSelector: &types.NamespaceSelector{
NameSelector: &types.NameSelector{
MatchNames: []string{"d8-istio"},
},
},
NameSelector: &types.NameSelector{
MatchNames: []string{"cacerts"},
},
},
{
Name: "secret_istio_mtls",
ApiVersion: "v1",
Kind: "Secret",
FilterFunc: applySecertIstioMTLSFilter,
NamespaceSelector: &types.NamespaceSelector{
NameSelector: &types.NameSelector{
MatchNames: []string{"d8-monitoring"},
},
},
NameSelector: &types.NameSelector{
MatchNames: []string{"prometheus-scraper-istio-mtls"},
},
},
},
Schedule: []go_hook.ScheduleConfig{
{Name: "cron", Crontab: "42 4 * * *"}, // every day at 04:42 am
},
}, generateMTLSCertHook)
func applySecertIstioMTLSFilter(obj *unstructured.Unstructured) (go_hook.FilterResult, error) {
secret := &v1.Secret{}
err := sdk.FromUnstructured(obj, secret)
if err != nil {
return nil, fmt.Errorf("can't convert ca secret to secret struct: %v", err)
}
var cert certificate.Certificate
var certBytes, keyBytes []byte
var ok bool
if certBytes, ok = secret.Data["tls.crt"]; ok {
cert.Cert = string(certBytes)
} else {
return nil, fmt.Errorf("can't get certificate from secert %v", secret.Name)
}
if keyBytes, ok = secret.Data["tls.key"]; ok {
cert.Key = string(keyBytes)
} else {
return nil, fmt.Errorf("can't get key from secert %v", secret.Name)
}
return cert, nil
}
func applySecertIstioCAFilter(obj *unstructured.Unstructured) (go_hook.FilterResult, error) {
secret := &v1.Secret{}
err := sdk.FromUnstructured(obj, secret)
if err != nil {
return nil, fmt.Errorf("can't convert ca secret to secret struct: %v", err)
}
var cert certificate.Authority
var certBytes, keyBytes []byte
var ok bool
if certBytes, ok = secret.Data["ca-cert.pem"]; ok {
cert.Cert = string(certBytes)
} else {
return nil, fmt.Errorf("can't get certificate from secert %v", secret.Name)
}
if keyBytes, ok = secret.Data["ca-key.pem"]; ok {
cert.Key = string(keyBytes)
} else {
return nil, fmt.Errorf("can't get key from secert %v", secret.Name)
}
return cert, nil
}
func isCertValid(cert certificate.Certificate, ca certificate.Authority) (bool, error) {
// create CA pool to validate certificate chain
certPool := x509.NewCertPool()
ok := certPool.AppendCertsFromPEM([]byte(ca.Cert))
if !ok {
return false, fmt.Errorf("certificate validation check: can't add CA certificate to pool")
}
opts := x509.VerifyOptions{
Roots: certPool,
KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
CurrentTime: time.Now().Add(time.Hour * 8030), // 8030 Hours ~ 11 Months.
}
block, _ := pem.Decode([]byte(cert.Cert))
// If the block is nil, it means there is garbage in it, or it is just empty.
if block == nil {
return false, nil
}
x509cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return false, nil
}
_, err = x509cert.Verify(opts)
if err != nil {
return false, nil
}
// Everything is ok.
return true, nil
}
func generateMTLSCertHook(input *go_hook.HookInput) error {
var ok bool
var err error
var istioCA certificate.Authority
var mTLSCert certificate.Certificate
// Get istio CA keypair.
istioCASnap := input.Snapshots["istio_secret_ca"]
if len(istioCASnap) == 0 {
input.Values.Remove(mTLSCrtPath)
input.Values.Remove(mTLSKeyPath)
return nil
}
istioCA, ok = istioCASnap[0].(certificate.Authority)
if !ok {
return fmt.Errorf("can't convert certificate to certificate struct")
}
clusterDomain := input.Values.Get("global.discovery.clusterDomain").String()
mTLSCertSAN := fmt.Sprintf("spiffe://%s/ns/d8-monitoring/sa/prometheus", clusterDomain)
// Get prometheus scraper mTLS keypair.
mTLSCertSnap := input.Snapshots["secret_istio_mtls"]
if len(mTLSCertSnap) == 1 {
mTLSCert, ok = mTLSCertSnap[0].(certificate.Certificate)
if !ok {
return fmt.Errorf("can't convert certificate to certificate struct")
}
}
ok, err = isCertValid(mTLSCert, istioCA)
if err != nil {
return err
}
if !ok {
mTLSCert, err = certificate.GenerateSelfSignedCert(input.LogEntry,
"prometheus-scraper-istio-mtls",
istioCA,
certificate.WithKeyAlgo("ecdsa"),
certificate.WithKeySize(256),
certificate.WithSigningDefaultUsage([]string{
"signing",
"key encipherment",
"client auth",
}),
certificate.WithSigningDefaultExpiry(8766*time.Hour), // 8766 hours = 1 Year
certificate.WithSANs(
mTLSCertSAN,
),
)
if err != nil {
return fmt.Errorf("can't generate certificate: %v", err)
}
}
input.Values.Set(mTLSCrtPath, mTLSCert.Cert)
input.Values.Set(mTLSKeyPath, mTLSCert.Key)
return nil
}