forked from fabiolb/fabio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
source.go
107 lines (92 loc) · 2.59 KB
/
source.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
package cert
import (
"crypto/tls"
"crypto/x509"
"fmt"
"os"
"github.com/eBay/fabio/config"
)
// Source provides the interface for dynamic certificate sources.
type Source interface {
// Certificates() loads certificates for TLS connections.
// The first certificate is used as the default certificate
// if the client does not support SNI or no matching certificate
// could be found. TLS certificates can be updated at runtime.
Certificates() chan []tls.Certificate
// LoadClientCAs() provides certificates for client certificate
// authentication.
LoadClientCAs() (*x509.CertPool, error)
}
// NewSource generates a cert source from the config options.
func NewSource(cfg config.CertSource) (Source, error) {
switch cfg.Type {
case "file":
return FileSource{
CertFile: cfg.CertPath,
KeyFile: cfg.KeyPath,
ClientAuthFile: cfg.ClientCAPath,
CAUpgradeCN: cfg.CAUpgradeCN,
}, nil
case "path":
return PathSource{
CertPath: cfg.CertPath,
ClientCAPath: cfg.ClientCAPath,
CAUpgradeCN: cfg.CAUpgradeCN,
Refresh: cfg.Refresh,
}, nil
case "http":
return HTTPSource{
CertURL: cfg.CertPath,
ClientCAURL: cfg.ClientCAPath,
CAUpgradeCN: cfg.CAUpgradeCN,
Refresh: cfg.Refresh,
}, nil
case "consul":
return ConsulSource{
CertURL: cfg.CertPath,
ClientCAURL: cfg.ClientCAPath,
CAUpgradeCN: cfg.CAUpgradeCN,
}, nil
case "vault":
return &VaultSource{
Addr: os.Getenv("VAULT_ADDR"),
CertPath: cfg.CertPath,
ClientCAPath: cfg.ClientCAPath,
CAUpgradeCN: cfg.CAUpgradeCN,
Refresh: cfg.Refresh,
vaultToken: os.Getenv("VAULT_TOKEN"),
}, nil
default:
return nil, fmt.Errorf("invalid certificate source %q", cfg.Type)
}
}
// TLSConfig creates a tls.Config which sets the
// GetCertificate field to a certificate store
// which uses the given source to update the
// the certificates on demand.
//
// It also sets the ClientCAs field if
// src.LoadClientCAs returns a non-nil value
// and sets ClientAuth to RequireAndVerifyClientCert.
func TLSConfig(src Source, strictMatch bool) (*tls.Config, error) {
clientCAs, err := src.LoadClientCAs()
if err != nil {
return nil, err
}
store := NewStore()
x := &tls.Config{
GetCertificate: func(clientHello *tls.ClientHelloInfo) (cert *tls.Certificate, err error) {
return getCertificate(store.certstore(), clientHello, strictMatch)
},
}
if clientCAs != nil {
x.ClientCAs = clientCAs
x.ClientAuth = tls.RequireAndVerifyClientCert
}
go func() {
for certs := range src.Certificates() {
store.SetCertificates(certs)
}
}()
return x, nil
}