-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtlsconfig.go
79 lines (68 loc) · 1.56 KB
/
tlsconfig.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
package tlsconfig
import (
"crypto/tls"
"crypto/x509"
"io/ioutil"
)
func New(opts ...Option) *tls.Config {
cf := &tls.Config{
Certificates: []tls.Certificate{},
}
for _, opt := range opts {
opt(cf)
}
return cf
}
type Option func(cf *tls.Config)
func CA(cert string) Option {
return func(cf *tls.Config) {
if cf.RootCAs == nil {
cf.RootCAs = x509.NewCertPool()
}
if caCrt, err := ioutil.ReadFile(cert); err == nil {
cf.RootCAs.AppendCertsFromPEM(caCrt)
}
}
}
func ClientCA(cert string) Option {
return func(cf *tls.Config) {
if cf.ClientCAs == nil {
cf.ClientCAs = x509.NewCertPool()
}
if caCrt, err := ioutil.ReadFile(cert); err == nil {
cf.ClientCAs.AppendCertsFromPEM(caCrt)
}
}
}
func CertKeyPair(cert string, key string) Option {
return func(cf *tls.Config) {
if pair, err := tls.LoadX509KeyPair(cert, key); err == nil {
cf.Certificates = append(cf.Certificates, pair)
}
}
}
func ClientAuth(t tls.ClientAuthType) Option {
return func(cf *tls.Config) {
cf.ClientAuth = t
}
}
func ClientAuthVerified() Option {
return func(cf *tls.Config) {
cf.ClientAuth = tls.RequireAndVerifyClientCert
}
}
func ServerAuthSkip() Option {
return func(cf *tls.Config) {
cf.InsecureSkipVerify = true
}
}
func GetCertificate(getter func(*tls.ClientHelloInfo) (*tls.Certificate, error)) Option {
return func(cf *tls.Config) {
cf.GetCertificate = getter
}
}
func GetClientCertificate(getter func(*tls.CertificateRequestInfo) (*tls.Certificate, error)) Option {
return func(cf *tls.Config) {
cf.GetClientCertificate = getter
}
}