forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 4
/
tls.go
310 lines (257 loc) · 8.8 KB
/
tls.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package outputs
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"github.com/elastic/beats/libbeat/logp"
"github.com/elastic/beats/libbeat/outputs/transport"
"github.com/joeshaw/multierror"
)
var (
// ErrNotACertificate indicates a PEM file to be loaded not being a valid
// PEM file or certificate.
ErrNotACertificate = errors.New("file is not a certificate")
// ErrCertificateNoKey indicate a configuration error with missing key file
ErrCertificateNoKey = errors.New("key file not configured")
// ErrKeyNoCertificate indicate a configuration error with missing certificate file
ErrKeyNoCertificate = errors.New("certificate file not configured")
)
// TLSConfig defines config file options for TLS clients.
type TLSConfig struct {
Enabled *bool `config:"enabled"`
VerificationMode transport.TLSVerificationMode `config:"verification_mode"` // one of 'none', 'full'
Versions []transport.TLSVersion `config:"supported_protocols"`
CipherSuites []tlsCipherSuite `config:"cipher_suites"`
CAs []string `config:"certificate_authorities"`
Certificate CertificateConfig `config:",inline"`
CurveTypes []tlsCurveType `config:"curve_types"`
Renegotiation tlsRenegotiationSupport `config:"renegotiation"`
}
type CertificateConfig struct {
Certificate string `config:"certificate"`
Key string `config:"key"`
Passphrase string `config:"key_passphrase"`
}
type tlsCipherSuite uint16
type tlsCurveType tls.CurveID
type tlsRenegotiationSupport tls.RenegotiationSupport
var tlsCipherSuites = map[string]tlsCipherSuite{
"ECDHE-ECDSA-AES-128-CBC-SHA": tlsCipherSuite(tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA),
"ECDHE-ECDSA-AES-128-GCM-SHA256": tlsCipherSuite(tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256),
"ECDHE-ECDSA-AES-256-CBC-SHA": tlsCipherSuite(tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA),
"ECDHE-ECDSA-AES-256-GCM-SHA384": tlsCipherSuite(tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384),
"ECDHE-ECDSA-RC4-128-SHA": tlsCipherSuite(tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA),
"ECDHE-RSA-3DES-CBC3-SHA": tlsCipherSuite(tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA),
"ECDHE-RSA-AES-128-CBC-SHA": tlsCipherSuite(tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA),
"ECDHE-RSA-AES-128-GCM-SHA256": tlsCipherSuite(tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256),
"ECDHE-RSA-AES-256-CBC-SHA": tlsCipherSuite(tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA),
"ECDHE-RSA-AES-256-GCM-SHA384": tlsCipherSuite(tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384),
"ECDHE-RSA-RC4-128-SHA": tlsCipherSuite(tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA),
"RSA-3DES-CBC3-SHA": tlsCipherSuite(tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA),
"RSA-AES-128-CBC-SHA": tlsCipherSuite(tls.TLS_RSA_WITH_AES_128_CBC_SHA),
"RSA-AES-128-GCM-SHA256": tlsCipherSuite(tls.TLS_RSA_WITH_AES_128_GCM_SHA256),
"RSA-AES-256-CBC-SHA": tlsCipherSuite(tls.TLS_RSA_WITH_AES_256_CBC_SHA),
"RSA-AES-256-GCM-SHA384": tlsCipherSuite(tls.TLS_RSA_WITH_AES_256_GCM_SHA384),
"RSA-RC4-128-SHA": tlsCipherSuite(tls.TLS_RSA_WITH_RC4_128_SHA),
}
var tlsCurveTypes = map[string]tlsCurveType{
"P-256": tlsCurveType(tls.CurveP256),
"P-384": tlsCurveType(tls.CurveP384),
"P-521": tlsCurveType(tls.CurveP521),
}
var tlsRenegotiationSupportTypes = map[string]tlsRenegotiationSupport{
"never": tlsRenegotiationSupport(tls.RenegotiateNever),
"once": tlsRenegotiationSupport(tls.RenegotiateOnceAsClient),
"freely": tlsRenegotiationSupport(tls.RenegotiateFreelyAsClient),
}
func (c *TLSConfig) Validate() error {
hasCertificate := c.Certificate.Certificate != ""
hasKey := c.Certificate.Key != ""
switch {
case hasCertificate && !hasKey:
return ErrCertificateNoKey
case !hasCertificate && hasKey:
return ErrKeyNoCertificate
}
return nil
}
func (c *TLSConfig) IsEnabled() bool {
return c != nil && (c.Enabled == nil || *c.Enabled)
}
// LoadTLSConfig will load a certificate from config with all TLS based keys
// defined. If Certificate and CertificateKey are configured, client authentication
// will be configured. If no CAs are configured, the host CA will be used by go
// built-in TLS support.
func LoadTLSConfig(config *TLSConfig) (*transport.TLSConfig, error) {
if !config.IsEnabled() {
return nil, nil
}
fail := multierror.Errors{}
logFail := func(es ...error) {
for _, e := range es {
if e != nil {
fail = append(fail, e)
}
}
}
var cipherSuites []uint16
for _, suite := range config.CipherSuites {
cipherSuites = append(cipherSuites, uint16(suite))
}
var curves []tls.CurveID
for _, id := range config.CurveTypes {
curves = append(curves, tls.CurveID(id))
}
cert, err := loadCertificate(&config.Certificate)
logFail(err)
cas, errs := loadCertificateAuthorities(config.CAs)
logFail(errs...)
// fail, if any error occurred when loading certificate files
if err = fail.Err(); err != nil {
return nil, err
}
var certs []tls.Certificate
if cert != nil {
certs = []tls.Certificate{*cert}
}
// return config if no error occurred
return &transport.TLSConfig{
Versions: config.Versions,
Verification: config.VerificationMode,
Certificates: certs,
RootCAs: cas,
CipherSuites: cipherSuites,
CurvePreferences: curves,
Renegotiation: tls.RenegotiationSupport(config.Renegotiation),
}, nil
}
func loadCertificate(config *CertificateConfig) (*tls.Certificate, error) {
certificate := config.Certificate
key := config.Key
hasCertificate := certificate != ""
hasKey := key != ""
switch {
case hasCertificate && !hasKey:
return nil, ErrCertificateNoKey
case !hasCertificate && hasKey:
return nil, ErrKeyNoCertificate
case !hasCertificate && !hasKey:
return nil, nil
}
certPEM, err := readPEMFile(certificate, config.Passphrase)
if err != nil {
logp.Critical("Failed reading certificate file %v: %v", certificate, err)
return nil, fmt.Errorf("%v %v", err, certificate)
}
keyPEM, err := readPEMFile(key, config.Passphrase)
if err != nil {
logp.Critical("Failed reading key file %v: %v", key, err)
return nil, fmt.Errorf("%v %v", err, key)
}
cert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
logp.Critical("Failed loading client certificate", err)
return nil, err
}
return &cert, nil
}
func readPEMFile(path, passphrase string) ([]byte, error) {
pass := []byte(passphrase)
var blocks []*pem.Block
content, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
for len(content) > 0 {
var block *pem.Block
block, content = pem.Decode(content)
if block == nil {
if len(blocks) == 0 {
return nil, errors.New("no pem file")
}
break
}
if x509.IsEncryptedPEMBlock(block) {
var buffer []byte
var err error
if len(pass) == 0 {
err = errors.New("No passphrase available")
} else {
// Note, decrypting pem might succeed even with wrong password, but
// only noise will be stored in buffer in this case.
buffer, err = x509.DecryptPEMBlock(block, pass)
}
if err != nil {
logp.Err("Dropping encrypted pem '%v' block read from %v. %v",
block.Type, path, err)
continue
}
// DEK-Info contains encryption info. Remove header to mark block as
// unencrypted.
delete(block.Headers, "DEK-Info")
block.Bytes = buffer
}
blocks = append(blocks, block)
}
if len(blocks) == 0 {
return nil, errors.New("no PEM blocks")
}
// re-encode available, decrypted blocks
buffer := bytes.NewBuffer(nil)
for _, block := range blocks {
err := pem.Encode(buffer, block)
if err != nil {
return nil, err
}
}
return buffer.Bytes(), nil
}
func loadCertificateAuthorities(CAs []string) (*x509.CertPool, []error) {
errors := []error{}
if len(CAs) == 0 {
return nil, nil
}
roots := x509.NewCertPool()
for _, path := range CAs {
pemData, err := ioutil.ReadFile(path)
if err != nil {
logp.Critical("Failed reading CA certificate: %v", err)
errors = append(errors, fmt.Errorf("%v reading %v", err, path))
continue
}
if ok := roots.AppendCertsFromPEM(pemData); !ok {
logp.Critical("Failed reading CA certificate: %v", err)
errors = append(errors, fmt.Errorf("%v adding %v", ErrNotACertificate, path))
continue
}
}
return roots, errors
}
func (cs *tlsCipherSuite) Unpack(s string) error {
suite, found := tlsCipherSuites[s]
if !found {
return fmt.Errorf("invalid tls cipher suite '%v'", s)
}
*cs = suite
return nil
}
func (ct *tlsCurveType) Unpack(s string) error {
t, found := tlsCurveTypes[s]
if !found {
return fmt.Errorf("invalid tls curve type '%v'", s)
}
*ct = t
return nil
}
func (r *tlsRenegotiationSupport) Unpack(s string) error {
t, found := tlsRenegotiationSupportTypes[s]
if !found {
return fmt.Errorf("invalid tls renegotiation type '%v'", s)
}
*r = t
return nil
}