/
certs.go
554 lines (549 loc) · 16.1 KB
/
certs.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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
package auth
import (
"crypto/tls"
"crypto/x509"
"net/url"
"strings"
)
//
//import (
// "context"
// "crypto/tls"
// "crypto/x509"
// "encoding/pem"
// "errors"
// "fmt"
// "io/ioutil"
// "log"
// "net/url"
// "os"
// "path/filepath"
// "strings"
// "time"
//)
//
//// This handles the ideal mesh case - platform managed workload certificates.
//// Also handles pilot-agent managing the certs.
//
//// MeshAuth represents a workload identity and associated info required for minimal Mesh-compatible security.
//type MeshAuth struct {
// // Will attempt to load certificates from this directory, defaults to
// // "./var/run/secrets/istio.io/"
// CertDir string
//
// // Current certificate, after calling GetCertificate("")
// Cert *tls.Certificate
//
// // MeshTLSConfig is a tls.Config that requires mTLS with a spiffee identity,
// // using the configured roots, trustdomains.
// //
// // By default only same namespace or istio-system are allowed - can be changed by
// // setting AllowedNamespaces. A "*" will allow all.
// MeshTLSConfig *tls.Config
//
// // TrustDomain is extracted from the cert or set by user, used to verify
// // peer certificates.
// TrustDomain string
//
// // Namespace and SA are extracted from the certificate or set by user.
// // Namespace is used to verify peer certificates
// Namespace string
// SA string
//
// // Additional namespaces to allow access from. By default 'same namespace' and 'istio-system' are allowed.
// AllowedNamespaces []string
//
// // Trusted roots
// // TODO: copy Istiod multiple trust domains code. This will be a map[trustDomain]roots and a
// // list of TrustDomains. XDS will return the info via ProxyConfig.
// // This can also be done by krun - loading a config map with same info.
// TrustedCertPool *x509.CertPool
//
// // GetCertificateHook allows plugging in an alternative certificate provider. By default files are used.
// GetCertificateHook func(host string) (*tls.Certificate, error)
//}
//
//func (a *MeshAuth) GenerateTLSConfigServer() *tls.Config {
// return a.MeshTLSConfig
//}
//
//func (a *MeshAuth) GenerateTLSConfigClient(name string) *tls.Config {
// return a.MeshTLSConfig.Clone()
//}
//
//// NewMeshAuth creates the auth object. No keys are set.
////
//// Private key, roots, config must be initialized and loaded. Use NewAuth(...) for automated loading
//// from environment/filesystem.
//func NewMeshAuth() *Auth {
// a := &Auth{
// TrustedCertPool: x509.NewCertPool(),
// }
// return a
//}
//
//// mesh certificates - new style
//const (
// WorkloadCertDir = "/var/run/secrets/workload-spiffe-credentials"
//
// // Different from typical Istio and CertManager key.pem - we can check both
// privateKey = "private_key.pem"
//
// // Also different, we'll check all. CertManager uses cert.pem
// cert = "certificates.pem"
//
// // This is derived from CA certs plus all TrustAnchors.
// // In GKE, it is expected that Citadel roots will be configure using TrustConfig - so they are visible
// // to all workloads including TD proxyless GRPC.
// //
// // Outside of GKE, this is loaded from the mesh.env - the mesh gate is responsible to keep it up to date.
// WorkloadRootCAs = "ca_certificates.pem"
//)
//
//// CSRSigner is the provider interface for signing certs, defined in Istio.
//// CSR is generated by Auth.
//type CSRSigner interface {
// CSRSign(ctx context.Context, csrPEM []byte, certValidTTLInSec int64) ([]string, error)
// GetRootCertBundle() ([]string, error)
//}
//
//// Will load the credentials and create an Auth object.
////
//// This uses pilot-agent or some other platform tool creating ./var/run/secrets/istio.io/{key,cert-chain}.pem
////
////
//// TODO: ./etc/certs support: krun should copy the files, for consistency (simper code for frameworks).
//// TODO: periodic reload
//func (a *Auth) SetKeysDir(dir string) error {
// a.CertDir = dir
// err := a.waitAndInitFromDir()
// if err != nil {
// return err
// }
// return nil
//}
//
//func (a *Auth) SetKeysPEM(privatePEM []byte, chainPEM []string) error {
// chainPEMCat := strings.Join(chainPEM, "\n")
// tlsCert, err := tls.X509KeyPair([]byte(chainPEMCat), privatePEM)
// if err != nil {
// return err
// }
// if tlsCert.Certificate == nil || len(tlsCert.Certificate) == 0 {
// return errors.New("missing certificate")
// }
//
// return a.SetTLSCertificate(&tlsCert)
//}
//
func (a *Auth) SetTLSCertificate(cert *tls.Certificate) error {
a.Cert = cert
a.initTLS()
return nil
}
//
//// GetCertificate is typically called during handshake, both server and client.
//// "sni" will be empty for client certificates, and set for server certificates - if not set, workload id is returned.
////
//// ctx is the handshake context - may include additional metadata about the operation.
//func (a *Auth) GetCertificate(ctx context.Context, sni string) (*tls.Certificate, error) {
// // TODO: if host != "", allow returning DNS certs for the host.
// // Default (and currently only impl) is to return the spiffe cert
// // May refresh.
// c, ok := a.CertMap[sni]
// if ok {
// return c, nil
// }
//
// // Have cert, not expired
// if a.Cert != nil {
// if !a.leaf().NotAfter.Before(time.Now()) {
// return a.Cert, nil
// }
// }
//
// if a.CertDir != "" {
// c, err := a.loadCertFromDir(a.CertDir)
// if err == nil {
// if !c.Leaf.NotAfter.Before(time.Now()) {
// a.Cert = c
// }
// } else {
// log.Println("Cert from dir failed", err)
// }
// }
//
// if a.GetCertificateHook != nil {
// c, err := a.GetCertificateHook(sni)
// if err != nil {
// return nil, err
// }
// a.Cert = c
// }
//
// return a.Cert, nil
//}
//
//func (a *Auth) loadCertFromDir(dir string) (*tls.Certificate, error) {
// // Load cert from file
// keyFile := filepath.Join(dir, "key.pem")
// keyBytes, err := ioutil.ReadFile(keyFile)
// if err != nil {
// return nil, err
// }
// certBytes, err := ioutil.ReadFile(filepath.Join(dir, "cert-chain.pem"))
// if err != nil {
// return nil, err
// }
//
// tlsCert, err := tls.X509KeyPair(certBytes, keyBytes)
// if err != nil {
// return nil, err
// }
// if tlsCert.Certificate == nil || len(tlsCert.Certificate) == 0 {
// return nil, errors.New("missing certificate")
// }
// tlsCert.Leaf, _ = x509.ParseCertificate(tlsCert.Certificate[0])
//
// return &tlsCert, nil
//}
//
//func (a *Auth) waitAndInitFromDir() error {
// if a.CertDir == "" {
// a.CertDir = "./var/run/secrets/istio.io/"
// }
// keyFile := filepath.Join(a.CertDir, "key.pem")
// err := waitFile(keyFile, 5*time.Second)
// if err != nil {
// return err
// }
//
// err = a.initFromDir()
// if err != nil {
// return err
// }
//
// time.AfterFunc(30*time.Minute, a.initFromDirPeriodic)
// return nil
//}
//
//func (a *Auth) initFromDirPeriodic() {
// err := a.initFromDir()
// if err != nil {
// log.Println("certRefresh", err)
// }
// time.AfterFunc(30*time.Minute, a.initFromDirPeriodic)
//}
//
//func (a *Auth) initFromDir() error {
//
// if a.Cert == nil {
// _, err := a.GetCertificate(context.Background(), "")
// if err != nil {
// return err
// }
// }
//
// rootCert, _ := ioutil.ReadFile(filepath.Join(a.CertDir, "root-cert.pem"))
// if rootCert != nil {
// err2 := a.AddRoots(rootCert)
// if err2 != nil {
// return err2
// }
// }
//
// istioCert, _ := ioutil.ReadFile("./var/run/secrets/istio/root-cert.pem")
// if istioCert != nil {
// err2 := a.AddRoots(istioCert)
// if err2 != nil {
// return err2
// }
// }
//
// // Similar with /etc/ssl/certs/ca-certificates.crt - the concatenated list of PEM certs.
// rootCertExtra, _ := ioutil.ReadFile(filepath.Join(a.CertDir, "ca-certificates.crt"))
// if rootCertExtra != nil {
// err2 := a.AddRoots(rootCertExtra)
// if err2 != nil {
// return err2
// }
// }
// // If the certificate has a chain, use the last cert - similar with Istio
// if len(a.Cert.Certificate) > 1 {
// last := a.Cert.Certificate[len(a.Cert.Certificate)-1]
//
// rootCAs, err := x509.ParseCertificates(last)
// if err == nil {
// for _, c := range rootCAs {
// log.Println("Adding root CA from cert chain: ", c.Subject)
// a.TrustedCertPool.AddCert(c)
// }
// }
// }
//
// a.initTLS()
// return nil
//}
//
//// InitRoots will find the mesh roots.
////
//// - if Zatar or another CSI provider are enabled, we do nothing - Zatar config is the root of trust for everything
//// - otherwise the roots are expected to be part of mesh-env. The mesh connector or other tools will
//// populate it - ideally from the CSI/Zatar or TrustConfig CRD.
//func (kr *Auth) InitRoots(ctx context.Context, outDir string) error {
// if outDir != "" {
// rootFile := filepath.Join(outDir, WorkloadRootCAs)
// rootCertPEM, err := ioutil.ReadFile(rootFile)
// if err == nil {
// block, rest := pem.Decode(rootCertPEM)
//
// var blockBytes []byte
// for block != nil {
// blockBytes = append(blockBytes, block.Bytes...)
// block, rest = pem.Decode(rest)
// }
//
// rootCAs, err := x509.ParseCertificates(blockBytes)
// if err != nil {
// return err
// }
// for _, c := range rootCAs {
// kr.TrustedCertPool.AddCert(c)
// }
// return nil
// }
// }
//
// // File not found - extract it from mesh env, and save it.
// // This includes Citadel root (if active in the mesh) or other roots.
// roots := ""
// block, rest := pem.Decode([]byte(roots))
// var blockBytes []byte
// for block != nil {
// blockBytes = append(blockBytes, block.Bytes...)
// block, rest = pem.Decode(rest)
// }
//
// rootCAs, err := x509.ParseCertificates(blockBytes)
// if err != nil {
// return err
// }
// for _, c := range rootCAs {
// kr.TrustedCertPool.AddCert(c)
// }
//
// return nil
//}
//
//// TODO: save last cert in the chain to roots
//
//// Common setup for cert management.
//// After the 'mesh-env' is loaded (from env, k8s, URL) the next step is to init the workload identity.
//// This must happen before connecting to XDS - since certs is one of the possible auth methods.
////
//// The logic is:
//// - (best case) certificates already provisioned by platform. Detects GKE paths (CAS), old Istio, CertManager style
//// If workload certs are platform-provisioned: extract trust domain, namespace, name, pod id from cert.
////
//// - Detect the WORKLOAD_SERVICE_ACCOUNT, trust domain from JWT or mesh-env
//// - Use WORKLOAD_CERT json to load the config for the CSR, create a CSR
//// - Call CSRSigner.
//// - Save the certificates if running as root or an output dir is set. This will use CAS naming convention.
////
//// If envoy + pilot-agent are used, they should be configured to use the cert files.
//// This is done by setting "CA_PROVIDER=GoogleGkeWorkloadCertificate" when starting pilot-agent
//func (kr *Auth) InitCertificates(ctx context.Context, certDir string) error {
// if certDir == "" {
// certDir = WorkloadCertDir
// }
// var err error
// keyFile := filepath.Join(certDir, privateKey)
// chainFile := filepath.Join(certDir, cert)
// kr.privPEM, err = ioutil.ReadFile(keyFile)
// kr.certPEM, err = ioutil.ReadFile(chainFile)
//
// kp, err := tls.X509KeyPair(kr.certPEM, kr.privPEM)
// if err == nil && len(kp.Certificate) > 0 {
// kr.CertDir = certDir
//
// kp.Leaf, _ = x509.ParseCertificate(kp.Certificate[0])
//
// exp := kp.Leaf.NotAfter.Sub(time.Now())
// if exp > -5*time.Minute {
// kr.Cert = &kp
// log.Println("Existing Cert", "expires", exp)
// return nil
// }
// }
// return nil
//}
//
// Extract the trustDomain, namespace and Name from a spiffee certificate
func (a *Auth) Spiffee() (*url.URL, string, string, string) {
cert, err := x509.ParseCertificate(a.Cert.Certificate[0])
if err != nil {
return nil, "", "", ""
}
if len(cert.URIs) > 0 {
c0 := cert.URIs[0]
pathComponetns := strings.Split(c0.Path, "/")
if c0.Scheme == "spiffe" && pathComponetns[1] == "ns" && pathComponetns[3] == "sa" {
return c0, c0.Host, pathComponetns[2], pathComponetns[4]
}
}
return nil, "", "", ""
}
//
//func (a *Auth) SpiffeeID() string {
// su, _, _, _ := a.Spiffee()
// return su.String()
//}
//
//func (a *Auth) String() string {
// cert, err := x509.ParseCertificate(a.Cert.Certificate[0])
// if err != nil {
// return ""
// }
// id := ""
// if len(cert.URIs) > 0 {
// id = cert.URIs[0].String()
// }
// return fmt.Sprintf("ID=%s,iss=%s,exp=%v,org=%s", id, cert.Issuer,
// cert.NotAfter, cert.Subject.Organization)
//}
//
//func (a *Auth) AddRoots(rootCertPEM []byte) error {
// block, rest := pem.Decode(rootCertPEM)
// var blockBytes []byte
// for block != nil {
// blockBytes = append(blockBytes, block.Bytes...)
// block, rest = pem.Decode(rest)
// }
//
// rootCAs, err := x509.ParseCertificates(blockBytes)
// if err != nil {
// return err
// }
// for _, c := range rootCAs {
// a.TrustedCertPool.AddCert(c)
// }
// return nil
//}
//
// initTLS initializes the MeshTLSConfig with the workload certificate
func (a *Auth) initTLS() {
_, a.TrustDomain, a.Namespace, a.Name = a.Spiffee()
}
//
//// MeshTLSConfig is a tls.Config that requires mTLS with a spiffee identity,
//// using the configured roots, trustdomains.
////
//// By default only same namespace or istio-system are allowed - can be changed by
//// setting AllowedNamespaces. A "*" will allow all.
//func (a *Auth) GenerateTLSConfigServer() *tls.Config {
// return &tls.Config{
// //MinVersion: tls.VersionTLS13,
// //PreferServerCipherSuites: ugate.preferServerCipherSuites(),
// InsecureSkipVerify: true, // This is not insecure here. We will verify the cert chain ourselves.
// ClientAuth: tls.RequestClientCert, // not require - we'll fallback to JWT
//
// GetCertificate: func(ch *tls.ClientHelloInfo) (*tls.Certificate, error) {
// return a.GetCertificate(ch.Context(), ch.ServerName)
// },
//
// GetClientCertificate: func(cri *tls.CertificateRequestInfo) (*tls.Certificate, error) {
// //log.Printf("Server/NewConn/CH %v", cri.AcceptableCAs)
// return a.GetCertificate(cri.Context(), "")
// },
//
// // Will check the peer certificate, using the trust roots.
// VerifyPeerCertificate: func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
// if len(rawCerts) == 0 {
// log.Println("MTLS: missing client cert")
// return errors.New("client certificate required")
// }
// var peerCert *x509.Certificate
// intCertPool := x509.NewCertPool()
//
// for id, rawCert := range rawCerts {
// cert, err := x509.ParseCertificate(rawCert)
// if err != nil {
// return err
// }
// if id == 0 {
// peerCert = cert
// } else {
// intCertPool.AddCert(cert)
// }
// }
// if peerCert == nil || len(peerCert.URIs) == 0 {
// log.Println("MTLS: missing URIs in Istio cert", peerCert)
// return errors.New("peer certificate does not contain URI type SAN")
// }
// c0 := peerCert.URIs[0]
// trustDomain := c0.Host
// if trustDomain != a.TrustDomain {
// log.Println("MTLS: invalid trust domain", trustDomain, peerCert.URIs)
// return errors.New("invalid trust domain " + trustDomain + " " + a.TrustDomain)
// }
//
// _, err := peerCert.Verify(x509.VerifyOptions{
// Roots: a.TrustedCertPool,
// Intermediates: intCertPool,
// })
// if err != nil {
// return err
// }
//
// parts := strings.Split(c0.Path, "/")
// if len(parts) < 4 {
// log.Println("MTLS: invalid path", peerCert.URIs)
// return errors.New("invalid path " + c0.String())
// }
//
// ns := parts[2]
// if ns == "istio-system" || ns == a.Namespace {
// return nil
// }
//
// // TODO: also validate namespace is same with this workload or in list of namespaces ?
// if len(a.AllowedNamespaces) == 0 {
// log.Println("MTLS: namespace not allowed", peerCert.URIs)
// return errors.New("Namespace not allowed")
// }
//
// if a.AllowedNamespaces[0] == "*" {
// return nil
// }
//
// for _, ans := range a.AllowedNamespaces {
// if ns == ans {
// return nil
// }
// }
//
// log.Println("MTLS: namespace not allowed", peerCert.URIs)
// return errors.New("Namespace not allowed")
// },
// NextProtos: []string{"istio", "h2"},
// }
//}
//
//// waitFile will check for the file to show up - the agent is running in a separate process.
//func waitFile(keyFile string, d time.Duration) error {
// t0 := time.Now()
// var err error
// for {
// // Wait for key file to show up - pilot agent creates it.
// if _, err := os.Stat(keyFile); os.IsNotExist(err) {
// if time.Since(t0) > d {
// return err
// }
// time.Sleep(50 * time.Millisecond)
// continue
// }
// return nil
// }
//
// return err
//}