-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
x509source.go
498 lines (421 loc) · 14.1 KB
/
x509source.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
/*
Copyright 2023 The Dapr 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 security
import (
"context"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"sync"
"time"
middleware "github.com/grpc-ecosystem/go-grpc-middleware"
retry "github.com/grpc-ecosystem/go-grpc-middleware/retry"
"github.com/spiffe/go-spiffe/v2/bundle/x509bundle"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/spiffe/go-spiffe/v2/spiffetls/tlsconfig"
"github.com/spiffe/go-spiffe/v2/svid/x509svid"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"k8s.io/utils/clock"
"github.com/dapr/dapr/pkg/diagnostics"
"github.com/dapr/dapr/pkg/modes"
sentryv1pb "github.com/dapr/dapr/pkg/proto/sentry/v1"
"github.com/dapr/dapr/pkg/security/legacy"
secpem "github.com/dapr/dapr/pkg/security/pem"
sentryToken "github.com/dapr/dapr/pkg/security/token"
)
const (
sentrySignTimeout = time.Second * 3
sentryMaxRetries = 5
)
type renewFn func(context.Context) (*x509.Certificate, error)
// x509source implements the go-spiffe x509 source interface.
// We use a custom source as our SPIFFE ID's come from the Sentry API and not
// the SPIFFE Workload API (SPIRE).
type x509source struct {
currentSVID *x509svid.SVID
// sentryAddress is the network address of the sentry server.
sentryAddress string
// sentryID is the SPIFFE ID of the sentry server which is validated when
// request the identity document.
sentryID spiffeid.ID
// trustAnchors is the set of trusted root certificates of the dapr cluster.
trustAnchors *x509bundle.Bundle
// appID is the self selected APP ID of this Dapr instance.
appID string
// appNamespace is the dapr namespace this app belongs to.
appNamespace string
// kubernetesMode is true if Dapr is running in Kubernetes mode.
kubernetesMode bool
// requestFn is the function used to request the identity document from a
// remote server. Used for overriding requesting from Sentry.
requestFn RequestFn
// writeToDiskDir is the directory to write the identity document to.
writeToDiskDir *string
// trustAnchorSubscribers is a list of channels to notify when the trust
// anchors are updated.
trustAnchorSubscribers []chan<- struct{}
// trustDomain is the optional trust domain which will be set when requesting
// the identity certificate. Used by control plane services to request for
// the control plane trust domain.
trustDomain *string
lock sync.RWMutex
clock clock.Clock
}
func newX509Source(ctx context.Context, clock clock.Clock, cptd spiffeid.TrustDomain, opts Options) (*x509source, error) {
rootPEMs := opts.TrustAnchors
if len(rootPEMs) == 0 {
for {
_, err := os.Stat(opts.TrustAnchorsFile)
if err == nil {
break
}
if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
// Trust anchors file not be provided yet, wait.
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-clock.After(time.Second):
log.Warnf("Trust anchors file '%s' not found, waiting...", opts.TrustAnchorsFile)
}
}
log.Infof("Trust anchors file '%s' found", opts.TrustAnchorsFile)
var err error
rootPEMs, err = os.ReadFile(opts.TrustAnchorsFile)
if err != nil {
return nil, fmt.Errorf("failed to read trust anchors file '%s': %w", opts.TrustAnchorsFile, err)
}
}
trustAnchorCerts, err := secpem.DecodePEMCertificates(rootPEMs)
if err != nil {
return nil, fmt.Errorf("failed to decode trust anchors: %w", err)
}
sentryID, err := SentryID(cptd, opts.ControlPlaneNamespace)
if err != nil {
return nil, err
}
var trustDomain *string
ns := CurrentNamespace()
// If the service is a control plane service, set the trust domain to the
// control plane trust domain.
if isControlPlaneService(opts.AppID) && opts.ControlPlaneNamespace == ns {
trustDomain = &opts.ControlPlaneTrustDomain
}
return &x509source{
sentryAddress: opts.SentryAddress,
sentryID: sentryID,
trustAnchors: x509bundle.FromX509Authorities(sentryID.TrustDomain(), trustAnchorCerts),
appID: opts.AppID,
appNamespace: ns,
trustDomain: trustDomain,
kubernetesMode: opts.Mode == modes.KubernetesMode,
requestFn: opts.OverrideCertRequestSource,
writeToDiskDir: opts.WriteSVIDToDir,
clock: clock,
}, nil
}
// GetX509SVID returns the current X.509 certificate identity as a SPIFFE SVID.
// Implements the go-spiffe x509 source interface.
func (x *x509source) GetX509SVID() (*x509svid.SVID, error) {
x.lock.RLock()
defer x.lock.RUnlock()
return x.currentSVID, nil
}
// GetX509BundleForTrustDomain returns the static Trust Bundle for the Dapr
// cluster.
// Dapr does not support trust bundles for multiple trust domains.
// Implements the go-spiffe x509 bundle source interface.
func (x *x509source) GetX509BundleForTrustDomain(_ spiffeid.TrustDomain) (*x509bundle.Bundle, error) {
x.lock.RLock()
defer x.lock.RUnlock()
return x.trustAnchors, nil
}
// startRotation starts up the manager responsible for renewing the workload
// certificate. Receives the initial certificate to calculate the next
// rotation time.
func (x *x509source) startRotation(ctx context.Context, fn renewFn, cert *x509.Certificate) {
defer log.Debug("stopping workload cert expiry watcher")
renewTime := renewalTime(cert.NotBefore, cert.NotAfter)
log.Infof("Starting workload cert expiry watcher; current cert expires on: %s, renewing at %s",
cert.NotAfter.String(), renewTime.String())
for {
select {
case <-x.clock.After(renewTime.Sub(x.clock.Now())):
log.Infof("Renewing workload cert; current cert expires on: %s", cert.NotAfter.String())
newCert, err := fn(ctx)
if err != nil {
log.Errorf("Error renewing identity certificate, trying again in 10 seconds: %v", err)
select {
case <-x.clock.After(10 * time.Second):
continue
case <-ctx.Done():
return
}
}
cert = newCert
renewTime = renewalTime(cert.NotBefore, cert.NotAfter)
log.Infof("Successfully renewed workload cert; new cert expires on: %s", cert.NotAfter.String())
case <-ctx.Done():
return
}
}
}
// renewIdentityCertificate renews the identity certificate for the workload.
func (x *x509source) renewIdentityCertificate(ctx context.Context) (*x509.Certificate, error) {
csrDER, pk, err := generateCSRAndPrivateKey(x.appID)
if err != nil {
return nil, err
}
workloadcert, err := x.requestFn(ctx, csrDER)
if err != nil {
return nil, err
}
if len(workloadcert) == 0 {
return nil, errors.New("no certificates received from sentry")
}
spiffeID, err := x509svid.IDFromCert(workloadcert[0])
if err != nil {
return nil, fmt.Errorf("error parsing spiffe id from newly signed certificate: %w", err)
}
x.lock.Lock()
defer x.lock.Unlock()
x.currentSVID = &x509svid.SVID{
ID: spiffeID,
Certificates: workloadcert,
PrivateKey: pk,
}
return workloadcert[0], x.maybeWriteSVIDToDir()
}
func generateCSRAndPrivateKey(id string) ([]byte, crypto.Signer, error) {
if id == "" {
return nil, nil, errors.New("id must not be empty")
}
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
diagnostics.DefaultMonitoring.MTLSInitFailed("prikeygen")
return nil, nil, fmt.Errorf("failed to generate private key: %w", err)
}
csrDER, err := x509.CreateCertificateRequest(rand.Reader,
&x509.CertificateRequest{
Subject: pkix.Name{CommonName: id},
DNSNames: []string{id},
}, key)
if err != nil {
diagnostics.DefaultMonitoring.MTLSInitFailed("csr")
return nil, nil, fmt.Errorf("failed to create sidecar csr: %w", err)
}
return csrDER, key, nil
}
func (x *x509source) requestFromSentry(ctx context.Context, csrDER []byte) ([]*x509.Certificate, error) {
unaryClientInterceptor := retry.UnaryClientInterceptor(
retry.WithMax(sentryMaxRetries),
retry.WithPerRetryTimeout(sentrySignTimeout),
)
if diagnostics.DefaultGRPCMonitoring.IsEnabled() {
unaryClientInterceptor = middleware.ChainUnaryClient(
unaryClientInterceptor,
diagnostics.DefaultGRPCMonitoring.UnaryClientInterceptor(),
)
}
tlsConfig, err := legacy.NewDialClientOptionalClientAuth(x, x, tlsconfig.AuthorizeID(x.sentryID))
if err != nil {
return nil, fmt.Errorf("error creating tls config: %w", err)
}
conn, err := grpc.DialContext(ctx,
x.sentryAddress,
grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)),
grpc.WithUnaryInterceptor(unaryClientInterceptor),
grpc.WithReturnConnectionError(),
)
if err != nil {
diagnostics.DefaultMonitoring.MTLSWorkLoadCertRotationFailed("sentry_conn")
return nil, fmt.Errorf("error establishing connection to sentry: %w", err)
}
defer conn.Close()
token, tokenValidator, err := sentryToken.GetSentryToken(x.kubernetesMode)
if err != nil {
diagnostics.DefaultMonitoring.MTLSWorkLoadCertRotationFailed("sentry_token")
return nil, fmt.Errorf("error obtaining token: %w", err)
}
req := &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE REQUEST", Bytes: csrDER,
}),
Id: getSentryIdentifier(x.appID),
Token: token,
Namespace: x.appNamespace,
TokenValidator: tokenValidator,
}
if x.trustDomain != nil {
req.TrustDomain = *x.trustDomain
} else {
// For v1.11 sentry, if the trust domain is empty in the request then it
// will return an empty certificate so we default to `public` here to
// ensure we get an identity certificate back.
// This request field is ignored for non control-plane requests in v1.12.
// TODO: @joshvanl: Remove in v1.13.
req.TrustDomain = "public"
}
resp, err := sentryv1pb.NewCAClient(conn).SignCertificate(ctx, req)
if err != nil {
diagnostics.DefaultMonitoring.MTLSWorkLoadCertRotationFailed("sign")
return nil, fmt.Errorf("error from sentry SignCertificate: %w", err)
}
if err = resp.GetValidUntil().CheckValid(); err != nil {
diagnostics.DefaultMonitoring.MTLSWorkLoadCertRotationFailed("invalid_ts")
return nil, fmt.Errorf("error parsing ValidUntil: %w", err)
}
workloadcert, err := secpem.DecodePEMCertificates(resp.GetWorkloadCertificate())
if err != nil {
return nil, fmt.Errorf("error parsing newly signed certificate: %w", err)
}
return workloadcert, nil
}
// maybeWriteSVIDToDir writes the current SVID to the configured directory if
// configured. Does this atomically using unix symlinks.
func (x *x509source) maybeWriteSVIDToDir() error {
if x.writeToDiskDir == nil || x.currentSVID == nil || x.trustAnchors == nil {
return nil
}
certs, pk, err := x.currentSVID.Marshal()
if err != nil {
return err
}
ta, err := x.trustAnchors.Marshal()
if err != nil {
return err
}
if err := atomicWrite(x.clock, *x.writeToDiskDir, map[string][]byte{
"tls.crt": certs,
"tls.key": pk,
"ca.crt": ta,
}); err != nil {
return fmt.Errorf("unable to write SVID to disk: %w", err)
}
log.Infof("Wrote SVID to '%s'", *x.writeToDiskDir)
return nil
}
func (x *x509source) updateTrustAnchorFromFile(ctx context.Context, filepath string) error {
x.lock.RLock()
defer x.lock.RUnlock()
rootPEMs, err := os.ReadFile(filepath)
if err != nil {
return fmt.Errorf("failed to read trust anchors file '%s': %w", filepath, err)
}
trustAnchorCerts, err := secpem.DecodePEMCertificates(rootPEMs)
if err != nil {
return fmt.Errorf("failed to decode trust anchors: %w", err)
}
x.trustAnchors.SetX509Authorities(trustAnchorCerts)
if err := x.maybeWriteSVIDToDir(); err != nil {
return err
}
var wg sync.WaitGroup
defer wg.Wait()
wg.Add(len(x.trustAnchorSubscribers))
for _, ch := range x.trustAnchorSubscribers {
go func(chi chan<- struct{}) {
defer wg.Done()
select {
case chi <- struct{}{}:
case <-ctx.Done():
}
}(ch)
}
return nil
}
func atomicWrite(clock clock.Clock, dir string, data map[string][]byte) error {
dir = filepath.Clean(dir)
if err := os.MkdirAll(filepath.Dir(dir), 0o700); err != nil {
return err
}
newDir := dir + "-" + clock.Now().Format("20060102-150405")
if err := os.MkdirAll(newDir, 0o700); err != nil {
return err
}
for file, contents := range data {
if err := os.WriteFile(filepath.Join(newDir, file), contents, 0o600); err != nil {
return err
}
}
// Symlinks are typically not available on Windows containers, so we use a
// copy and rename instead.
if runtime.GOOS == "windows" {
os.RemoveAll(dir + "-new")
if err := os.MkdirAll(dir+"-new", 0o700); err != nil {
return err
}
entries, err := os.ReadDir(newDir)
if err != nil {
return err
}
for _, entry := range entries {
b, err := os.ReadFile(filepath.Join(newDir, entry.Name()))
if err != nil {
return err
}
if err := os.WriteFile(filepath.Join(dir+"-new", entry.Name()), b, 0o600); err != nil {
return err
}
}
// You can't rename a directory over an existing directory.
os.RemoveAll(dir)
if err := os.Rename(dir+"-new", dir); err != nil {
return fmt.Errorf("failed to rename %s to %s: %w", dir+"-new", dir, err)
}
} else {
if err := os.Symlink(newDir, dir+"-new"); err != nil {
return err
}
if err := os.Rename(dir+"-new", dir); err != nil {
return err
}
}
return nil
}
// renewalTime is 70% through the certificate validity period.
func renewalTime(notBefore, notAfter time.Time) time.Time {
return notBefore.Add(notAfter.Sub(notBefore) * 7 / 10)
}
// isControlPlaneService returns true if the app ID corresponds to a Dapr
// control plane service.
func isControlPlaneService(id string) bool {
switch id {
case "dapr-operator",
"dapr-placement",
"dapr-injector",
"dapr-sentry":
return true
default:
return false
}
}
func getSentryIdentifier(appID string) string {
// return injected identity, default id if not present
localID := os.Getenv("SENTRY_LOCAL_IDENTITY")
if localID != "" {
return localID
}
return appID
}