/
secretfetcher.go
396 lines (352 loc) · 13.3 KB
/
secretfetcher.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
// Copyright 2018 Istio 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 secretfetcher
import (
"bytes"
"fmt"
"os"
"strings"
"sync"
"time"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/cache"
"istio.io/istio/pkg/kube"
"istio.io/istio/pkg/log"
ca "istio.io/istio/security/pkg/nodeagent/caclient"
caClientInterface "istio.io/istio/security/pkg/nodeagent/caclient/interface"
"istio.io/istio/security/pkg/nodeagent/model"
)
const (
// The ID/name for the certificate chain in kubernetes generic secret.
genericScrtCert = "cert"
// The ID/name for the private key in kubernetes generic secret.
genericScrtKey = "key"
// The ID/name for the CA certificate in kubernetes generic secret.
genericScrtCaCert = "cacert"
// The ID/name for the certificate chain in kubernetes tls secret.
tlsScrtCert = "tls.crt"
// The ID/name for the k8sKey in kubernetes tls secret.
tlsScrtKey = "tls.key"
// IngressSecretNameSpace the namespace of kubernetes secrets to watch.
ingressSecretNameSpace = "INGRESS_GATEWAY_NAMESPACE"
// IngressGatewaySdsCaSuffix is the suffix of the sds resource name for root CA. All resource
// names for ingress gateway root certs end with "-cacert".
IngressGatewaySdsCaSuffix = "-cacert"
// scrtTokenField is the token field in secret generated by istio.
scrtTokenField = "token"
// istioPrefix and prometheusPrefix are prefix in secrets generated by istio.
istioPrefix = "istio"
prometheusPrefix = "prometheus"
// TODO(JimmyCYJ): Configure these two env variables in Helm
// secretControllerResyncPeriod specifies the time period in seconds that secret controller
// resyncs to API server.
// example value format like "30s"
secretControllerResyncPeriod = "SECRET_WATCHER_RESYNC_PERIOD"
// ingressFallbackSecret specifies the name of fallback secret for ingress gateway.
ingressFallbackSecret = "INGRESS_GATEWAY_FALLBACK_SECRET"
// Default secret name for fallback secret.
defaultFallbackSecretName = "gateway-fallback"
)
// SecretFetcher fetches secret via watching k8s secrets or sending CSR to CA.
type SecretFetcher struct {
// If UseCaClient is true, use caClient to send CSR to CA.
UseCaClient bool
CaClient caClientInterface.Client
// Controller and store for secret objects.
scrtController cache.Controller
scrtStore cache.Store
// secrets maps k8sKey to secrets
secrets sync.Map
// Add all entries containing secretName in SecretCache. Called when K8S secret is added.
AddCache func(secretName string, ns model.SecretItem)
// Delete all entries containing secretName in SecretCache. Called when K8S secret is deleted.
DeleteCache func(secretName string)
// Update all entries containing secretName in SecretCache. Called when K8S secret is updated.
UpdateCache func(secretName string, ns model.SecretItem)
// FallbackSecretName stores the name of fallback secret which is set at env variable
// INGRESS_GATEWAY_FALLBACK_SECRET. If INGRESS_GATEWAY_FALLBACK_SECRET is empty, then use
// gateway-fallback as default name of fallback secret. If a fallback secret exists,
// FindIngressGatewaySecret returns this fallback secret when expected secret is not available.
FallbackSecretName string
}
func fatalf(template string, args ...interface{}) {
if len(args) > 0 {
log.Errorf(template, args...)
} else {
log.Errorf(template)
}
os.Exit(-1)
}
// NewSecretFetcher returns a pointer to a newly constructed SecretFetcher instance.
func NewSecretFetcher(ingressGatewayAgent bool, endpoint, CAProviderName string, tlsFlag bool,
tlsRootCert []byte, vaultAddr, vaultRole, vaultAuthPath, vaultSignCsrPath string) (*SecretFetcher, error) {
ret := &SecretFetcher{}
if ingressGatewayAgent {
ret.UseCaClient = false
cs, err := kube.CreateClientset("", "")
if err != nil {
fatalf("Could not create k8s clientset: %v", err)
}
ret.FallbackSecretName = defaultFallbackSecretName
// Check if a fallback secret env variable is set.
if secretName := os.Getenv(ingressFallbackSecret); secretName != "" {
ret.FallbackSecretName = secretName
}
log.Debugf("SecretFetcher set fallback secret name %s", ret.FallbackSecretName)
ret.Init(cs.CoreV1())
} else {
caClient, err := ca.NewCAClient(endpoint, CAProviderName, tlsFlag, tlsRootCert,
vaultAddr, vaultRole, vaultAuthPath, vaultSignCsrPath)
if err != nil {
log.Errorf("failed to create caClient: %v", err)
return ret, fmt.Errorf("failed to create caClient")
}
ret.UseCaClient = true
ret.CaClient = caClient
}
return ret, nil
}
// Run starts the SecretFetcher until a value is sent to ch.
// Only used when watching kubernetes gateway secrets.
func (sf *SecretFetcher) Run(ch chan struct{}) {
go sf.scrtController.Run(ch)
cache.WaitForCacheSync(ch, sf.scrtController.HasSynced)
}
// Init initializes SecretFetcher to watch kubernetes secrets.
func (sf *SecretFetcher) Init(core corev1.CoreV1Interface) { // nolint:interfacer
namespace := os.Getenv(ingressSecretNameSpace)
istioSecretSelector := fields.SelectorFromSet(nil).String()
scrtLW := &cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
options.FieldSelector = istioSecretSelector
return core.Secrets(namespace).List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
options.FieldSelector = istioSecretSelector
return core.Secrets(namespace).Watch(options)
},
}
resyncPeriod := 0 * time.Second
if env, err := time.ParseDuration(os.Getenv(secretControllerResyncPeriod)); err == nil {
resyncPeriod = env
}
sf.scrtStore, sf.scrtController =
cache.NewInformer(scrtLW, &v1.Secret{}, resyncPeriod, cache.ResourceEventHandlerFuncs{
AddFunc: sf.scrtAdded,
DeleteFunc: sf.scrtDeleted,
UpdateFunc: sf.scrtUpdated,
})
}
// isIngressGatewaySecret checks secret and decides whether this is a secret generated for ingress
// gateway. For secrets with prefix "istio" and "prometheus", they are generated by istio system and
// they are not gateway secrets. Other secrets generated by istio could have "token" field.
// isIngressGatewaySecret returns false if a secret has name prefix "istio", or "prometheus", or has
// "token" field.
func isIngressGatewaySecret(scrt *v1.Secret) bool {
secretName := scrt.GetName()
if strings.HasPrefix(secretName, istioPrefix) || strings.HasPrefix(secretName, prometheusPrefix) {
return false
}
if len(scrt.Data[scrtTokenField]) > 0 {
return false
}
return true
}
// extractCertAndKey extracts key, certificate and root certificate, and indicates whether
// these key and certificate are empty.
func extractCertAndKey(scrt *v1.Secret) (cert, key, root []byte, valid bool) {
certAndKeyExist := false
if len(scrt.Data[genericScrtCert]) > 0 {
cert = scrt.Data[genericScrtCert]
key = scrt.Data[genericScrtKey]
root = scrt.Data[genericScrtCaCert]
} else {
cert = scrt.Data[tlsScrtCert]
key = scrt.Data[tlsScrtKey]
root = []byte{}
}
// root could be empty if ingress gateway only accepts TLS.
if len(cert) > 0 && len(key) > 0 {
certAndKeyExist = true
}
return cert, key, root, certAndKeyExist
}
func (sf *SecretFetcher) scrtAdded(obj interface{}) {
scrt, ok := obj.(*v1.Secret)
if !ok {
log.Warnf("Failed to convert to secret object: %v", obj)
return
}
resourceName := scrt.GetName()
if !isIngressGatewaySecret(scrt) {
log.Debugf("secret %s is not an ingress gateway secret, skip adding secret", resourceName)
return
}
t := time.Now()
newCert, newKey, newRoot, valid := extractCertAndKey(scrt)
if !valid {
log.Warnf("Secret object: %v has empty field, skip adding secret", resourceName)
return
}
// If there is secret with the same resource name, delete that secret now.
sf.secrets.Delete(resourceName)
ns := &model.SecretItem{
ResourceName: resourceName,
CertificateChain: newCert,
PrivateKey: newKey,
CreatedTime: t,
Version: t.String(),
}
sf.secrets.Store(resourceName, *ns)
log.Debugf("secret %s is added", resourceName)
if sf.AddCache != nil {
sf.AddCache(resourceName, *ns)
}
rootCertResourceName := resourceName + IngressGatewaySdsCaSuffix
// If there is root cert secret with the same resource name, delete that secret now.
sf.secrets.Delete(rootCertResourceName)
if len(newRoot) > 0 {
nsRoot := &model.SecretItem{
ResourceName: rootCertResourceName,
RootCert: newRoot,
CreatedTime: t,
Version: t.String(),
}
sf.secrets.Store(rootCertResourceName, *nsRoot)
log.Debugf("secret %s is added", rootCertResourceName)
if sf.AddCache != nil {
sf.AddCache(rootCertResourceName, *nsRoot)
}
}
}
func (sf *SecretFetcher) scrtDeleted(obj interface{}) {
scrt, ok := obj.(*v1.Secret)
if !ok {
log.Warnf("Failed to convert to secret object: %v", obj)
return
}
key := scrt.GetName()
sf.secrets.Delete(key)
log.Infof("secret %s is deleted", key)
// Delete all cache entries that match the deleted key.
if sf.DeleteCache != nil {
sf.DeleteCache(key)
}
rootCertResourceName := key + IngressGatewaySdsCaSuffix
// If there is root cert secret with the same resource name, delete that secret now.
sf.secrets.Delete(rootCertResourceName)
log.Infof("secret %s is deleted", rootCertResourceName)
// Delete all cache entries that match the deleted key.
if sf.DeleteCache != nil {
sf.DeleteCache(rootCertResourceName)
}
}
func (sf *SecretFetcher) scrtUpdated(oldObj, newObj interface{}) {
oscrt, ok := oldObj.(*v1.Secret)
if !ok {
log.Warnf("Failed to convert to old secret object: %v", oldObj)
return
}
nscrt, ok := newObj.(*v1.Secret)
if !ok {
log.Warnf("Failed to convert to new secret object: %v", newObj)
return
}
oldScrtName := oscrt.GetName()
newScrtName := nscrt.GetName()
if oldScrtName != newScrtName {
log.Warnf("Failed to update secret: name does not match (%s vs %s).", oldScrtName, newScrtName)
return
}
if !isIngressGatewaySecret(nscrt) {
log.Debugf("secret %s is not an ingress gateway secret, skip update", newScrtName)
return
}
oldCert, oldKey, oldRoot, _ := extractCertAndKey(oscrt)
newCert, newKey, newRoot, valid := extractCertAndKey(nscrt)
if !valid {
log.Warnf("Secret object: %v has empty field, skip update", newScrtName)
return
}
if bytes.Equal(oldCert, newCert) && bytes.Equal(oldKey, newKey) && bytes.Equal(oldRoot, newRoot) {
log.Debugf("secret %s does not change, skip update", oldScrtName)
return
}
sf.secrets.Delete(oldScrtName)
t := time.Now()
ns := &model.SecretItem{
ResourceName: newScrtName,
CertificateChain: newCert,
PrivateKey: newKey,
CreatedTime: t,
Version: t.String(),
}
sf.secrets.Store(newScrtName, *ns)
log.Infof("secret %s is updated", newScrtName)
if sf.UpdateCache != nil {
sf.UpdateCache(newScrtName, *ns)
}
rootCertResourceName := newScrtName + IngressGatewaySdsCaSuffix
// If there is root cert secret with the same resource name, delete that secret now.
sf.secrets.Delete(rootCertResourceName)
if len(newRoot) > 0 {
nsRoot := &model.SecretItem{
ResourceName: rootCertResourceName,
RootCert: newRoot,
CreatedTime: t,
Version: t.String(),
}
sf.secrets.Store(rootCertResourceName, *nsRoot)
log.Infof("secret %s is updated", rootCertResourceName)
if sf.UpdateCache != nil {
sf.UpdateCache(rootCertResourceName, *nsRoot)
}
}
}
// FindIngressGatewaySecret returns the secret whose name matches the key, or empty secret if no
// secret is present. The ok result indicates whether secret was found.
// If there is a fallback secret named FallbackSecretName, return the fall back secret.
func (sf *SecretFetcher) FindIngressGatewaySecret(key string) (secret model.SecretItem, ok bool) {
log.Debugf("SecretFetcher search for secret %s", key)
val, exist := sf.secrets.Load(key)
log.Debugf("load secret %s from secret fetcher: %v", key, exist)
if !exist {
// Expected secret does not exist, try to find the fallback secret.
// TODO(JimmyCYJ): Add metrics to node agent to imply usage of fallback secret
log.Warnf("Cannot find secret %s, searching for fallback secret %s", key, sf.FallbackSecretName)
fallbackVal, fallbackExist := sf.secrets.Load(sf.FallbackSecretName)
if fallbackExist {
log.Debugf("Return fallback secret %s for gateway secret %s", sf.FallbackSecretName, key)
return fallbackVal.(model.SecretItem), true
}
log.Errorf("cannot find secret %s and cannot find fallback secret %s", key, sf.FallbackSecretName)
return model.SecretItem{}, false
}
e := val.(model.SecretItem)
log.Debugf("SecretFetcher return secret %s", key)
return e, true
}
// AddSecret adds obj into local store. Only used for testing.
func (sf *SecretFetcher) AddSecret(obj interface{}) {
sf.scrtAdded(obj)
}
// DeleteSecret deletes obj from local store. Only used for testing.
func (sf *SecretFetcher) DeleteSecret(obj interface{}) {
sf.scrtDeleted(obj)
}