-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
security.go
76 lines (64 loc) · 1.98 KB
/
security.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
package security
import (
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"os"
diag "github.com/dapr/dapr/pkg/diagnostics"
"github.com/dapr/dapr/pkg/logger"
"github.com/dapr/dapr/pkg/sentry/certs"
)
const (
ecPKType = "EC PRIVATE KEY"
)
var log = logger.NewLogger("dapr.runtime.security")
func getTrustAnchors() (*x509.CertPool, error) {
trustAnchors := os.Getenv(certs.TrustAnchorsEnvVar)
if trustAnchors == "" {
return nil, fmt.Errorf("couldn't find trust anchors in environment variable %s", certs.TrustAnchorsEnvVar)
}
cp := x509.NewCertPool()
ok := cp.AppendCertsFromPEM([]byte(trustAnchors))
if !ok {
return nil, errors.New("failed to append PEM root cert to x509 CertPool")
}
return cp, nil
}
// GetSidecarAuthenticator returns a new authenticator with the extracted trust anchors
func GetSidecarAuthenticator(id, sentryAddress string) (Authenticator, error) {
trustAnchors, err := getTrustAnchors()
if err != nil {
return nil, err
}
log.Info("trust anchors extracted successfully")
return newAuthenticator(sentryAddress, trustAnchors, generateCSRAndPrivateKey), nil
}
func generateCSRAndPrivateKey(id string) ([]byte, []byte, error) {
if id == "" {
return nil, nil, errors.New("id must not be empty")
}
key, err := certs.GenerateECPrivateKey()
if err != nil {
diag.DefaultMonitoring.MTLSInitFailed("prikeygen")
return nil, nil, fmt.Errorf("failed to generate private key: %s", err)
}
encodedKey, err := x509.MarshalECPrivateKey(key)
if err != nil {
diag.DefaultMonitoring.MTLSInitFailed("prikeyenc")
return nil, nil, err
}
keyPem := pem.EncodeToMemory(&pem.Block{Type: ecPKType, Bytes: encodedKey})
csr := x509.CertificateRequest{
Subject: pkix.Name{CommonName: id},
DNSNames: []string{id},
}
csrb, err := x509.CreateCertificateRequest(rand.Reader, &csr, key)
if err != nil {
diag.DefaultMonitoring.MTLSInitFailed("csr")
return nil, nil, fmt.Errorf("failed to create sidecar csr: %s", err)
}
return csrb, keyPem, nil
}