forked from folbricht/routedns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtls.go
72 lines (66 loc) · 1.91 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
package rdns
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
)
// TLSServerConfig is a convenience function that builds a tls.Config instance for TLS servers
// based on common options and certificate+key files.
func TLSServerConfig(caFile, crtFile, keyFile string, mutualTLS bool) (*tls.Config, error) {
tlsConfig := &tls.Config{
MinVersion: tls.VersionTLS12,
}
if mutualTLS {
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
}
if caFile != "" {
certPool := x509.NewCertPool()
b, err := ioutil.ReadFile(caFile)
if err != nil {
return nil, err
}
if ok := certPool.AppendCertsFromPEM(b); !ok {
return nil, fmt.Errorf("no CA certificates found in %s", caFile)
}
tlsConfig.ClientCAs = certPool
}
if crtFile != "" && keyFile != "" {
var err error
tlsConfig.Certificates = make([]tls.Certificate, 1)
tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(crtFile, keyFile)
if err != nil {
return nil, err
}
}
return tlsConfig, nil
}
// TLSClientConfig is a convenience function that builds a tls.Config instance for TLS clients
// based on common options and certificate+key files.
func TLSClientConfig(caFile, crtFile, keyFile, serverName string) (*tls.Config, error) {
tlsConfig := &tls.Config{
MinVersion: tls.VersionTLS12,
ServerName: serverName,
}
// Add client key/cert if provided
if crtFile != "" && keyFile != "" {
certificate, err := tls.LoadX509KeyPair(crtFile, keyFile)
if err != nil {
return nil, fmt.Errorf("failed to load client certificate from %s", crtFile)
}
tlsConfig.Certificates = []tls.Certificate{certificate}
}
// Load custom CA set if provided
if caFile != "" {
certPool := x509.NewCertPool()
b, err := ioutil.ReadFile(caFile)
if err != nil {
return nil, err
}
if ok := certPool.AppendCertsFromPEM(b); !ok {
return nil, fmt.Errorf("no CA certificates found in %s", caFile)
}
tlsConfig.RootCAs = certPool
}
return tlsConfig, nil
}