-
Notifications
You must be signed in to change notification settings - Fork 5k
/
tlsmanager.go
284 lines (243 loc) · 8.41 KB
/
tlsmanager.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
package tls
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"sync"
"github.com/containous/traefik/v2/pkg/log"
"github.com/containous/traefik/v2/pkg/tls/generate"
"github.com/containous/traefik/v2/pkg/types"
"github.com/go-acme/lego/v3/challenge/tlsalpn01"
"github.com/sirupsen/logrus"
)
// DefaultTLSOptions the default TLS options.
var DefaultTLSOptions = Options{}
// Manager is the TLS option/store/configuration factory
type Manager struct {
storesConfig map[string]Store
stores map[string]*CertificateStore
configs map[string]Options
certs []*CertAndStores
TLSAlpnGetter func(string) (*tls.Certificate, error)
lock sync.RWMutex
}
// NewManager creates a new Manager
func NewManager() *Manager {
return &Manager{
stores: map[string]*CertificateStore{},
configs: map[string]Options{
"default": DefaultTLSOptions,
},
}
}
// UpdateConfigs updates the TLS* configuration options
func (m *Manager) UpdateConfigs(ctx context.Context, stores map[string]Store, configs map[string]Options, certs []*CertAndStores) {
m.lock.Lock()
defer m.lock.Unlock()
m.configs = configs
m.storesConfig = stores
m.certs = certs
m.stores = make(map[string]*CertificateStore)
for storeName, storeConfig := range m.storesConfig {
ctxStore := log.With(ctx, log.Str(log.TLSStoreName, storeName))
store, err := buildCertificateStore(ctxStore, storeConfig)
if err != nil {
log.FromContext(ctxStore).Errorf("Error while creating certificate store: %v", err)
continue
}
m.stores[storeName] = store
}
storesCertificates := make(map[string]map[string]*tls.Certificate)
for _, conf := range certs {
if len(conf.Stores) == 0 {
if log.GetLevel() >= logrus.DebugLevel {
log.FromContext(ctx).Debugf("No store is defined to add the certificate %s, it will be added to the default store.",
conf.Certificate.GetTruncatedCertificateName())
}
conf.Stores = []string{"default"}
}
for _, store := range conf.Stores {
ctxStore := log.With(ctx, log.Str(log.TLSStoreName, store))
if err := conf.Certificate.AppendCertificate(storesCertificates, store); err != nil {
log.FromContext(ctxStore).Errorf("Unable to append certificate %s to store: %v", conf.Certificate.GetTruncatedCertificateName(), err)
}
}
}
for storeName, certs := range storesCertificates {
m.getStore(storeName).DynamicCerts.Set(certs)
}
}
// Get gets the TLS configuration to use for a given store / configuration
func (m *Manager) Get(storeName string, configName string) (*tls.Config, error) {
m.lock.RLock()
defer m.lock.RUnlock()
var tlsConfig *tls.Config
var err error
config, ok := m.configs[configName]
if !ok {
err = fmt.Errorf("unknown TLS options: %s", configName)
tlsConfig = &tls.Config{}
}
store := m.getStore(storeName)
if err == nil {
tlsConfig, err = buildTLSConfig(config)
if err != nil {
tlsConfig = &tls.Config{}
}
}
tlsConfig.GetCertificate = func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
domainToCheck := types.CanonicalDomain(clientHello.ServerName)
if m.TLSAlpnGetter != nil {
cert, err := m.TLSAlpnGetter(domainToCheck)
if err != nil {
return nil, err
}
if cert != nil {
return cert, nil
}
}
bestCertificate := store.GetBestCertificate(clientHello)
if bestCertificate != nil {
return bestCertificate, nil
}
if m.configs[configName].SniStrict {
return nil, fmt.Errorf("strict SNI enabled - No certificate found for domain: %q, closing connection", domainToCheck)
}
log.WithoutContext().Debugf("Serving default certificate for request: %q", domainToCheck)
return store.DefaultCertificate, nil
}
return tlsConfig, err
}
func (m *Manager) getStore(storeName string) *CertificateStore {
_, ok := m.stores[storeName]
if !ok {
m.stores[storeName], _ = buildCertificateStore(context.Background(), Store{})
}
return m.stores[storeName]
}
// GetStore gets the certificate store of a given name
func (m *Manager) GetStore(storeName string) *CertificateStore {
m.lock.RLock()
defer m.lock.RUnlock()
return m.getStore(storeName)
}
func buildCertificateStore(ctx context.Context, tlsStore Store) (*CertificateStore, error) {
certificateStore := NewCertificateStore()
certificateStore.DynamicCerts.Set(make(map[string]*tls.Certificate))
if tlsStore.DefaultCertificate != nil {
cert, err := buildDefaultCertificate(tlsStore.DefaultCertificate)
if err != nil {
return certificateStore, err
}
certificateStore.DefaultCertificate = cert
} else {
log.FromContext(ctx).Debug("No default certificate, generating one")
cert, err := generate.DefaultCertificate()
if err != nil {
return certificateStore, err
}
certificateStore.DefaultCertificate = cert
}
return certificateStore, nil
}
// creates a TLS config that allows terminating HTTPS for multiple domains using SNI
func buildTLSConfig(tlsOption Options) (*tls.Config, error) {
conf := &tls.Config{}
// ensure http2 enabled
conf.NextProtos = []string{"h2", "http/1.1", tlsalpn01.ACMETLS1Protocol}
if len(tlsOption.ClientAuth.CAFiles) > 0 {
pool := x509.NewCertPool()
for _, caFile := range tlsOption.ClientAuth.CAFiles {
data, err := caFile.Read()
if err != nil {
return nil, err
}
ok := pool.AppendCertsFromPEM(data)
if !ok {
if caFile.IsPath() {
return nil, fmt.Errorf("invalid certificate(s) in %s", caFile)
}
return nil, errors.New("invalid certificate(s) content")
}
}
conf.ClientCAs = pool
conf.ClientAuth = tls.RequireAndVerifyClientCert
}
clientAuthType := tlsOption.ClientAuth.ClientAuthType
if len(clientAuthType) > 0 {
if conf.ClientCAs == nil && (clientAuthType == "VerifyClientCertIfGiven" ||
clientAuthType == "RequireAndVerifyClientCert") {
return nil, fmt.Errorf("invalid clientAuthType: %s, CAFiles is required", clientAuthType)
}
switch clientAuthType {
case "NoClientCert":
conf.ClientAuth = tls.NoClientCert
case "RequestClientCert":
conf.ClientAuth = tls.RequestClientCert
case "RequireAnyClientCert":
conf.ClientAuth = tls.RequireAnyClientCert
case "VerifyClientCertIfGiven":
conf.ClientAuth = tls.VerifyClientCertIfGiven
case "RequireAndVerifyClientCert":
conf.ClientAuth = tls.RequireAndVerifyClientCert
default:
return nil, fmt.Errorf("unknown client auth type %q", clientAuthType)
}
}
// Set PreferServerCipherSuites.
conf.PreferServerCipherSuites = tlsOption.PreferServerCipherSuites
// Set the minimum TLS version if set in the config
if minConst, exists := MinVersion[tlsOption.MinVersion]; exists {
conf.PreferServerCipherSuites = true
conf.MinVersion = minConst
}
// Set the maximum TLS version if set in the config TOML
if maxConst, exists := MaxVersion[tlsOption.MaxVersion]; exists {
conf.PreferServerCipherSuites = true
conf.MaxVersion = maxConst
}
// Set the list of CipherSuites if set in the config
if tlsOption.CipherSuites != nil {
// if our list of CipherSuites is defined in the entryPoint config, we can re-initialize the suites list as empty
conf.CipherSuites = make([]uint16, 0)
for _, cipher := range tlsOption.CipherSuites {
if cipherConst, exists := CipherSuites[cipher]; exists {
conf.CipherSuites = append(conf.CipherSuites, cipherConst)
} else {
// CipherSuite listed in the toml does not exist in our listed
return nil, fmt.Errorf("invalid CipherSuite: %s", cipher)
}
}
}
// Set the list of CurvePreferences/CurveIDs if set in the config
if tlsOption.CurvePreferences != nil {
conf.CurvePreferences = make([]tls.CurveID, 0)
// if our list of CurvePreferences/CurveIDs is defined in the config, we can re-initialize the list as empty
for _, curve := range tlsOption.CurvePreferences {
if curveID, exists := CurveIDs[curve]; exists {
conf.CurvePreferences = append(conf.CurvePreferences, curveID)
} else {
// CurveID listed in the toml does not exist in our listed
return nil, fmt.Errorf("invalid CurveID in curvePreferences: %s", curve)
}
}
}
return conf, nil
}
func buildDefaultCertificate(defaultCertificate *Certificate) (*tls.Certificate, error) {
certFile, err := defaultCertificate.CertFile.Read()
if err != nil {
return nil, fmt.Errorf("failed to get cert file content: %v", err)
}
keyFile, err := defaultCertificate.KeyFile.Read()
if err != nil {
return nil, fmt.Errorf("failed to get key file content: %v", err)
}
cert, err := tls.X509KeyPair(certFile, keyFile)
if err != nil {
return nil, fmt.Errorf("failed to load X509 key pair: %v", err)
}
return &cert, nil
}