forked from thecodeteam/libstorage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils_tls.go
112 lines (93 loc) · 2.59 KB
/
utils_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
package utils
import (
"crypto/tls"
"crypto/x509"
"io/ioutil"
"os"
log "github.com/Sirupsen/logrus"
"github.com/akutz/gofig"
"github.com/akutz/goof"
"github.com/akutz/gotil"
"github.com/emccode/libstorage/api/types"
)
// ParseTLSConfig returns a new TLS configuration.
func ParseTLSConfig(
config gofig.Config, fields log.Fields) (*tls.Config, error) {
f := func(k string, v interface{}) {
if fields == nil {
return
}
fields[k] = v
}
if !config.IsSet(types.ConfigTLS) {
return nil, nil
}
if config.IsSet(types.ConfigTLSDisabled) {
tlsDisabled := config.GetBool(types.ConfigTLSDisabled)
if tlsDisabled {
f(types.ConfigTLSDisabled, true)
return nil, nil
}
}
if !config.IsSet(types.ConfigTLSKeyFile) {
return nil, goof.New("keyFile required")
}
keyFile := config.GetString(types.ConfigTLSKeyFile)
if !gotil.FileExists(keyFile) {
return nil, goof.WithField("path", keyFile, "invalid key file")
}
f(types.ConfigTLSKeyFile, keyFile)
if !config.IsSet(types.ConfigTLSCertFile) {
return nil, goof.New("certFile required")
}
certFile := config.GetString(types.ConfigTLSCertFile)
if !gotil.FileExists(certFile) {
return nil, goof.WithField("path", certFile, "invalid cert file")
}
f(types.ConfigTLSCertFile, certFile)
cer, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, err
}
tlsConfig := &tls.Config{Certificates: []tls.Certificate{cer}}
if config.IsSet(types.ConfigTLSServerName) {
serverName := config.GetString(types.ConfigTLSServerName)
tlsConfig.ServerName = serverName
f(types.ConfigTLSServerName, serverName)
}
if config.IsSet(types.ConfigTLSClientCertRequired) {
clientCertRequired := config.GetBool(types.ConfigTLSClientCertRequired)
if clientCertRequired {
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
}
f(types.ConfigTLSClientCertRequired, clientCertRequired)
}
if config.IsSet(types.ConfigTLSTrustedCertsFile) {
trustedCertsFile := config.GetString(types.ConfigTLSTrustedCertsFile)
if !gotil.FileExists(trustedCertsFile) {
return nil, goof.WithField(
"path", trustedCertsFile, "invalid trust file")
}
f(types.ConfigTLSTrustedCertsFile, trustedCertsFile)
buf, err := func() ([]byte, error) {
f, err := os.Open(trustedCertsFile)
if err != nil {
return nil, err
}
defer f.Close()
buf, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
return buf, nil
}()
if err != nil {
return nil, err
}
certPool := x509.NewCertPool()
certPool.AppendCertsFromPEM(buf)
tlsConfig.RootCAs = certPool
tlsConfig.ClientCAs = certPool
}
return tlsConfig, nil
}