-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathtlsConfig.go
More file actions
96 lines (84 loc) · 2.35 KB
/
tlsConfig.go
File metadata and controls
96 lines (84 loc) · 2.35 KB
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
package driver
import (
"crypto/tls"
"crypto/x509"
"net/url"
"os"
"github.com/pkg/errors"
)
type TlsConfig struct {
CaPath string
CertPath string
CertKeyPath string
}
func isTlsEnable(url *url.URL) bool {
return url.Query().Get("tls") == "true"
}
func paseTargetUrlForTls(url *url.URL) (*TlsConfig, error) {
var config TlsConfig
caCrt := url.Query().Get("caPath")
_, err := os.Stat(caCrt)
if err != nil {
if os.IsNotExist(err) {
return nil, errors.Wrap(err, "ca file not found")
}
return nil, errors.Wrap(err, "read ca file failed, check your permission")
}
config.CaPath = caCrt
//sometimes client just need ca.crt,but if you enable Two-way Authentication
//you also need cert.crt and certKey.key
certPath := url.Query().Get("certPath")
if certPath == "" {
return &config, nil
}
_, err = os.Stat(certPath)
if err != nil {
if os.IsNotExist(err) {
return nil, errors.Wrap(err, "cert file not found")
}
return nil, errors.Wrap(err, "read cert file failed, check your permission")
}
config.CertPath = certPath
certKeyPath := url.Query().Get("certKeyPath")
if certKeyPath == "" {
return &config, nil
}
_, err = os.Stat(certKeyPath)
if err != nil {
if os.IsNotExist(err) {
return nil, errors.Wrap(err, "key file not found")
}
return nil, errors.Wrap(err, "read key file failed, check your permission")
}
config.CertKeyPath = certKeyPath
return &config, nil
}
func loadCaPool(tlsConfig *TlsConfig) (*x509.CertPool, error) {
if tlsConfig.CaPath == "" {
return nil, errors.New("you enable tls,but caPath is empty")
}
var caPool *x509.CertPool
caData, err := os.ReadFile(tlsConfig.CaPath)
if err != nil {
if os.IsNotExist(err) {
return nil, errors.Wrap(err, "ca file not found")
}
return nil, errors.Wrap(err, "read ca file failed, check your permission")
}
//add ca to x509.CertPool
caPool = x509.NewCertPool()
if !caPool.AppendCertsFromPEM(caData) {
return nil, errors.New("append ca to x509.CertPool failed")
}
return caPool, nil
}
func loadCertificate(tlsConfig *TlsConfig) (*tls.Certificate, error) {
if tlsConfig.CertPath != "" && tlsConfig.CertKeyPath != "" {
clientCert, err := tls.LoadX509KeyPair(tlsConfig.CertPath, tlsConfig.CertKeyPath)
if err != nil {
return nil, errors.Wrap(err, "load x509 key pair failed")
}
return &clientCert, nil
}
return &tls.Certificate{}, nil
}