This repository has been archived by the owner on Mar 26, 2024. It is now read-only.
/
cmdr.go
318 lines (288 loc) · 8.29 KB
/
cmdr.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
311
312
313
314
315
316
317
318
// Copyright © 2020 Hedzr Yeh.
package tls
import (
"crypto/tls"
"crypto/x509"
"github.com/hedzr/cmdr"
"github.com/hedzr/log/dir"
"gopkg.in/hedzr/errors.v3"
"net"
"os"
"path"
)
// NewCmdrTLSConfig builds the *CmdrTLSConfig object from cmdr config file and cmdr command-line arguments
func NewCmdrTLSConfig(appTag, prefixInConfigFile, prefixInCommandline string) *CmdrTLSConfig {
s := &CmdrTLSConfig{}
if len(prefixInConfigFile) > 0 {
s.InitTLSConfigFromConfigFile(appTag, prefixInConfigFile)
}
if len(prefixInCommandline) > 0 {
s.InitTLSConfigFromCommandline(prefixInCommandline)
}
return s
}
// CmdrTLSConfig wraps the certificates.
// For server-side, the `Cert` field must be a bundle of server certificates with all root CAs chain.
// For server-side, the `Cacert` is optional for extra client CA's.
type CmdrTLSConfig struct {
Enabled bool
Cacert string // server-side: optional server's CA; client-side: client's CA
ServerCert string // client-side: the server's cert
Cert string // server-side: server's cert bundle; client-side: client's cert
Key string // server-side: server's key; client-side: client's key
ClientAuth bool
MinTLSVersion uint16
}
// IsServerCertValid checks the server or CA cert are present.
func (s *CmdrTLSConfig) IsServerCertValid() bool {
return s.ServerCert != "" || s.Cacert != ""
}
// IsCertValid checks the cert and privateKey are present
func (s *CmdrTLSConfig) IsCertValid() bool {
return s.Cert != "" && s.Key != ""
}
// IsClientAuthEnabled checks if the client-side authentication is enabled
func (s *CmdrTLSConfig) IsClientAuthEnabled() bool {
return s.ClientAuth && s.Cert != "" && s.Key != ""
}
// InitTLSConfigFromCommandline loads the parsed command-line arguments to *CmdrTLSConfig
func (s *CmdrTLSConfig) InitTLSConfigFromCommandline(prefix string) {
var b bool
var sz string
b = cmdr.GetBoolRP(prefix, "client-auth")
if b {
s.ClientAuth = b
}
sz = cmdr.GetStringRP(prefix, "cacert")
if sz != "" {
s.Cacert = sz
}
sz = cmdr.GetStringRP(prefix, "cert")
if sz != "" {
s.Cert = sz
}
sz = cmdr.GetStringRP(prefix, "key")
if sz != "" {
s.Key = sz
}
for _, loc := range cmdr.GetStringSliceRP(prefix, "locations") {
if s.Cacert != "" && dir.FileExists(path.Join(loc, s.Cacert)) {
s.Cacert = path.Join(loc, s.Cacert)
} else if s.Cacert != "" {
continue
}
if s.Cert != "" && dir.FileExists(path.Join(loc, s.Cert)) {
s.Cert = path.Join(loc, s.Cert)
} else if s.Cert != "" {
continue
}
if s.Key != "" && dir.FileExists(path.Join(loc, s.Key)) {
s.Key = path.Join(loc, s.Key)
} else if s.Key != "" {
continue
}
}
switch cmdr.GetIntRP(prefix, "tls-version", 2) {
case 0:
s.MinTLSVersion = tls.VersionTLS10
case 1:
s.MinTLSVersion = tls.VersionTLS11
case 3:
s.MinTLSVersion = tls.VersionTLS13
default:
s.MinTLSVersion = tls.VersionTLS12
}
}
// InitTLSConfigFromConfigFile loads CmdrTLSConfig members from cmdr config file.
//
// The entries in config file looks like:
//
// prefix := "my-service.server.tls"
// tls:
// enabled: true
// cacert: root.pem
// cert: cert.pem
// key: cert.key
// locations:
// - ./ci/certs
// - $CFG_DIR/certs
func (s *CmdrTLSConfig) InitTLSConfigFromConfigFile(appTag, prefix string) {
if len(appTag) > 0 {
prefix = appTag + "." + prefix
}
enabled := cmdr.GetBoolRP(prefix, "enabled")
if enabled {
s.ClientAuth = cmdr.GetBoolRP(prefix, "client-auth")
s.Cacert = cmdr.GetStringRP(prefix, "cacert")
s.Cert = cmdr.GetStringRP(prefix, "cert")
s.Key = cmdr.GetStringRP(prefix, "key")
for _, loc := range cmdr.GetStringSliceRP(prefix, "locations") {
cmdr.Logger.Debugf("> tls - testing loc: %v", loc)
if s.Cacert != "" && dir.FileExists(path.Join(loc, s.Cacert)) {
s.Cacert = path.Join(loc, s.Cacert)
} else if s.Cacert != "" {
continue
}
if s.Cert != "" && dir.FileExists(path.Join(loc, s.Cert)) {
s.Cert = path.Join(loc, s.Cert)
} else if s.Cert != "" {
continue
}
if s.Key != "" && dir.FileExists(path.Join(loc, s.Key)) {
s.Key = path.Join(loc, s.Key)
} else if s.Key != "" {
continue
}
}
switch cmdr.GetIntRP(prefix, "tls-version", int(s.MinTLSVersion-tls.VersionTLS10)) {
case 0:
s.MinTLSVersion = tls.VersionTLS10
case 1:
s.MinTLSVersion = tls.VersionTLS11
case 3:
s.MinTLSVersion = tls.VersionTLS13
default:
s.MinTLSVersion = tls.VersionTLS12
}
cmdr.Logger.Debugf("> cfg_dir: %v / %v", path.Dir(cmdr.GetUsedConfigFile()), os.Getenv("CFG_DIR"))
cmdr.Logger.Debugf("> tls matched: %+v", s)
}
}
// ToServerTLSConfig builds an tls.Config object for server.Serve
func (s *CmdrTLSConfig) ToServerTLSConfig() (config *tls.Config) {
var err error
config, err = s.newTLSConfig()
if err == nil {
if s.Cacert != "" {
var rootPEM []byte
rootPEM, err = dir.ReadFile(s.Cacert)
if err != nil || rootPEM == nil {
return
}
pool := x509.NewCertPool()
ok := pool.AppendCertsFromPEM(rootPEM)
if ok {
config.ClientCAs = pool
}
}
} else {
cmdr.Logger.Errorf("%+v", err)
}
return config
}
// ToTLSConfig converts to *tls.Config
func (s *CmdrTLSConfig) ToTLSConfig() (config *tls.Config) {
config, _ = s.newTLSConfig()
return config
}
func (s *CmdrTLSConfig) newTLSConfig() (config *tls.Config, err error) {
var cert tls.Certificate
cert, err = tls.LoadX509KeyPair(s.Cert, s.Key)
if err != nil {
err = errors.New("error parsing X509 certificate/key pair, pwd=%q, cert=%q", dir.GetCurrentDir(), s.Cert).WithErrors(err)
return
}
cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
if err != nil {
err = errors.New("error parsing certificate").WithErrors(err)
return
}
// Create TLSConfig
// We will determine the cipher suites that we prefer.
config = &tls.Config{
Certificates: []tls.Certificate{cert},
MinVersion: s.MinTLSVersion,
}
// Require client certificates as needed
if s.IsClientAuthEnabled() {
config.ClientAuth = tls.RequireAndVerifyClientCert
}
// Add in CAs if applicable.
if s.ClientAuth {
if s.Cacert != "" {
var rootPEM []byte
rootPEM, err = dir.ReadFile(s.Cacert)
if err != nil || rootPEM == nil {
return nil, err
}
pool := x509.NewCertPool()
ok := pool.AppendCertsFromPEM(rootPEM)
if !ok {
err = errors.New("failed to parse root ca certificate")
}
config.ClientCAs = pool
}
config.ClientAuth = tls.RequireAndVerifyClientCert
}
if err != nil {
config = nil
}
return
}
// NewTLSListener builds net.Listener for tls mode or not
func (s *CmdrTLSConfig) NewTLSListener(l net.Listener) (listener net.Listener, err error) {
if s != nil && s.IsCertValid() {
var config *tls.Config
config, err = s.newTLSConfig()
if err != nil {
cmdr.Logger.Fatalf("error: %v", err)
}
listener = tls.NewListener(l, config)
}
return
}
// Dial connects to the given network address using net.Dial
// and then initiates a TLS handshake, returning the resulting
// TLS connection.
//
// Dial interprets a nil configuration as equivalent to
// the zero configuration; see the documentation of Config
// for the defaults.
func (s *CmdrTLSConfig) Dial(network, addr string) (conn net.Conn, err error) {
if s != nil && s.IsServerCertValid() {
roots := x509.NewCertPool()
err = s.addCert(roots, s.ServerCert)
if err != nil {
return
}
err = s.addCert(roots, s.Cacert)
if err != nil {
return
}
cfg := &tls.Config{
RootCAs: roots,
}
if s.IsClientAuthEnabled() {
var cert tls.Certificate
cert, err = tls.LoadX509KeyPair(s.Cert, s.Key)
if err != nil {
return
}
cfg.Certificates = []tls.Certificate{cert}
cfg.InsecureSkipVerify = true
}
cmdr.Logger.Printf("Connecting to %s over TLS...\n", addr)
// Use the tls.Config here in http.Transport.TLSClientConfig
conn, err = tls.Dial(network, addr, cfg)
} else {
cmdr.Logger.Printf("Connecting to %s...\n", addr)
conn, err = net.Dial(network, addr)
}
return
}
func (s *CmdrTLSConfig) addCert(roots *x509.CertPool, certPath string) (err error) {
if certPath != "" {
var rootPEM []byte
rootPEM, err = dir.ReadFile(certPath)
if err != nil {
return
}
ok := roots.AppendCertsFromPEM(rootPEM)
if !ok {
// panic("failed to parse root certificate")
err = errors.New("failed to parse root certificate")
return
}
}
return
}