-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
auth.go
169 lines (145 loc) · 4.98 KB
/
auth.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
package security
import (
"context"
"crypto/x509"
"encoding/pem"
"io/ioutil"
"os"
"sync"
"time"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_retry "github.com/grpc-ecosystem/go-grpc-middleware/retry"
"github.com/pkg/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
dapr_credentials "github.com/dapr/dapr/pkg/credentials"
diag "github.com/dapr/dapr/pkg/diagnostics"
sentryv1pb "github.com/dapr/dapr/pkg/proto/sentry/v1"
)
const (
TLSServerName = "cluster.local"
sentrySignTimeout = time.Second * 5
certType = "CERTIFICATE"
kubeTknPath = "/var/run/secrets/kubernetes.io/serviceaccount/token"
sentryMaxRetries = 100
)
type Authenticator interface {
GetTrustAnchors() *x509.CertPool
GetCurrentSignedCert() *SignedCertificate
CreateSignedWorkloadCert(id, namespace, trustDomain string) (*SignedCertificate, error)
}
type authenticator struct {
trustAnchors *x509.CertPool
certChainPem []byte
keyPem []byte
genCSRFunc func(id string) ([]byte, []byte, error)
sentryAddress string
currentSignedCert *SignedCertificate
certMutex *sync.RWMutex
}
type SignedCertificate struct {
WorkloadCert []byte
PrivateKeyPem []byte
Expiry time.Time
TrustChain *x509.CertPool
}
func newAuthenticator(sentryAddress string, trustAnchors *x509.CertPool, certChainPem, keyPem []byte, genCSRFunc func(id string) ([]byte, []byte, error)) Authenticator {
return &authenticator{
trustAnchors: trustAnchors,
certChainPem: certChainPem,
keyPem: keyPem,
genCSRFunc: genCSRFunc,
sentryAddress: sentryAddress,
certMutex: &sync.RWMutex{},
}
}
// GetTrustAnchors returns the extracted root cert that serves as the trust anchor.
func (a *authenticator) GetTrustAnchors() *x509.CertPool {
return a.trustAnchors
}
// GetCurrentSignedCert returns the current and latest signed certificate.
func (a *authenticator) GetCurrentSignedCert() *SignedCertificate {
a.certMutex.RLock()
defer a.certMutex.RUnlock()
return a.currentSignedCert
}
// CreateSignedWorkloadCert returns a signed workload certificate, the PEM encoded private key
// And the duration of the signed cert.
func (a *authenticator) CreateSignedWorkloadCert(id, namespace, trustDomain string) (*SignedCertificate, error) {
csrb, pkPem, err := a.genCSRFunc(id)
if err != nil {
return nil, err
}
certPem := pem.EncodeToMemory(&pem.Block{Type: certType, Bytes: csrb})
config, err := dapr_credentials.TLSConfigFromCertAndKey(a.certChainPem, a.keyPem, TLSServerName, a.trustAnchors)
if err != nil {
return nil, errors.Wrap(err, "failed to create tls config from cert and key")
}
unaryClientInterceptor := grpc_retry.UnaryClientInterceptor()
if diag.DefaultGRPCMonitoring.IsEnabled() {
unaryClientInterceptor = grpc_middleware.ChainUnaryClient(
unaryClientInterceptor,
diag.DefaultGRPCMonitoring.UnaryClientInterceptor(),
)
}
conn, err := grpc.Dial(
a.sentryAddress,
grpc.WithTransportCredentials(credentials.NewTLS(config)),
grpc.WithUnaryInterceptor(unaryClientInterceptor))
if err != nil {
diag.DefaultMonitoring.MTLSWorkLoadCertRotationFailed("sentry_conn")
return nil, errors.Wrap(err, "error establishing connection to sentry")
}
defer conn.Close()
c := sentryv1pb.NewCAClient(conn)
resp, err := c.SignCertificate(context.Background(),
&sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: certPem,
Id: getSentryIdentifier(id),
Token: getToken(),
TrustDomain: trustDomain,
Namespace: namespace,
}, grpc_retry.WithMax(sentryMaxRetries), grpc_retry.WithPerRetryTimeout(sentrySignTimeout))
if err != nil {
diag.DefaultMonitoring.MTLSWorkLoadCertRotationFailed("sign")
return nil, errors.Wrap(err, "error from sentry SignCertificate")
}
workloadCert := resp.GetWorkloadCertificate()
validTimestamp := resp.GetValidUntil()
if err = validTimestamp.CheckValid(); err != nil {
diag.DefaultMonitoring.MTLSWorkLoadCertRotationFailed("invalid_ts")
return nil, errors.Wrap(err, "error parsing ValidUntil")
}
expiry := validTimestamp.AsTime()
trustChain := x509.NewCertPool()
for _, c := range resp.GetTrustChainCertificates() {
ok := trustChain.AppendCertsFromPEM(c)
if !ok {
diag.DefaultMonitoring.MTLSWorkLoadCertRotationFailed("chaining")
return nil, errors.Wrap(err, "failed adding trust chain cert to x509 CertPool")
}
}
signedCert := &SignedCertificate{
WorkloadCert: workloadCert,
PrivateKeyPem: pkPem,
Expiry: expiry,
TrustChain: trustChain,
}
a.certMutex.Lock()
defer a.certMutex.Unlock()
a.currentSignedCert = signedCert
return signedCert, nil
}
// currently we support Kubernetes identities.
func getToken() string {
b, _ := ioutil.ReadFile(kubeTknPath)
return string(b)
}
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
}