-
Notifications
You must be signed in to change notification settings - Fork 50
/
marble.go
79 lines (65 loc) · 2.42 KB
/
marble.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
// Copyright (c) Edgeless Systems GmbH.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// Package marble provides commonly used functionalities for MarbleRun Marbles.
package marble
import (
"crypto/tls"
"crypto/x509"
"fmt"
"os"
)
// MarbleEnvironmentCertificateChain contains the name of the environment variable holding a marble-specifc PEM encoded certificate
const MarbleEnvironmentCertificateChain = "MARBLE_PREDEFINED_MARBLE_CERTIFICATE_CHAIN"
// MarbleEnvironmentRootCA contains the name of the environment variable holding a PEM encoded root certificate
const MarbleEnvironmentRootCA = "MARBLE_PREDEFINED_ROOT_CA"
// MarbleEnvironmentPrivateKey contains the name of the environment variable holding a PEM encoded private key belonging to the marble-specific certificate
const MarbleEnvironmentPrivateKey = "MARBLE_PREDEFINED_PRIVATE_KEY"
// GetTLSConfig provides a preconfigured TLS config for marbles, using the MarbleRun Coordinator as trust anchor
func GetTLSConfig(verifyClientCerts bool) (*tls.Config, error) {
tlsCert, roots, err := generateFromEnv()
if err != nil {
return nil, err
}
tlsConfig := &tls.Config{
RootCAs: roots,
Certificates: []tls.Certificate{tlsCert},
}
if verifyClientCerts {
tlsConfig.ClientCAs = roots
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
}
return tlsConfig, nil
}
func getByteEnv(name string) ([]byte, error) {
value := os.Getenv(name)
if len(value) == 0 {
return nil, fmt.Errorf("environment variable not set: %s", name)
}
return []byte(value), nil
}
func generateFromEnv() (tls.Certificate, *x509.CertPool, error) {
certChain, err := getByteEnv(MarbleEnvironmentCertificateChain)
if err != nil {
return tls.Certificate{}, nil, err
}
marbleRootCA, err := getByteEnv(MarbleEnvironmentRootCA)
if err != nil {
return tls.Certificate{}, nil, err
}
leafPrivk, err := getByteEnv(MarbleEnvironmentPrivateKey)
if err != nil {
return tls.Certificate{}, nil, err
}
roots := x509.NewCertPool()
if !roots.AppendCertsFromPEM(marbleRootCA) {
return tls.Certificate{}, nil, fmt.Errorf("cannot append marbleRootCA to CertPool")
}
tlsCert, err := tls.X509KeyPair(certChain, leafPrivk)
if err != nil {
return tls.Certificate{}, nil, fmt.Errorf("cannot create TLS cert: %v", err)
}
return tlsCert, roots, nil
}