-
Notifications
You must be signed in to change notification settings - Fork 405
/
tls_utils.go
96 lines (79 loc) · 2.19 KB
/
tls_utils.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
package common
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
// NewTLSSimple creates a new tls config with the given cert and key file paths
func NewTLSSimple(certPath, keyPath string) (*tls.Config, error) {
err := checkFile(certPath)
if err != nil {
return nil, err
}
err = checkFile(keyPath)
if err != nil {
return nil, err
}
// Load the certificates from disk
certificate, err := tls.LoadX509KeyPair(certPath, keyPath)
if err != nil {
return nil, fmt.Errorf("Could not load server key pair: %s", err)
}
return &tls.Config{
Certificates: []tls.Certificate{certificate},
}, nil
}
// AddClientCA adds a client cert to the given tls config
func AddClientCA(tlsConf *tls.Config, clientCAPath string) error {
err := checkFile(clientCAPath)
if err != nil {
return err
}
// Create a certificate pool from the certificate authority
authority, err := ioutil.ReadFile(filepath.Clean(clientCAPath))
if err != nil {
return fmt.Errorf("Could not read client CA (%s) certificate: %s", clientCAPath, err)
}
tlsConf.ClientAuth = tls.RequireAndVerifyClientCert
if tlsConf.ClientCAs == nil {
tlsConf.ClientCAs = x509.NewCertPool()
}
if ok := tlsConf.ClientCAs.AppendCertsFromPEM(authority); !ok {
return errors.New("Failed to append client certs")
}
return nil
}
// AddCA adds a ca cert to the given tls config
func AddCA(tlsConf *tls.Config, caPath string) error {
err := checkFile(caPath)
if err != nil {
return err
}
ca, err := ioutil.ReadFile(filepath.Clean(caPath))
if err != nil {
return fmt.Errorf("could not read ca (%s) certificate: %s", caPath, err)
}
if tlsConf.RootCAs == nil {
tlsConf.RootCAs = x509.NewCertPool()
}
// Append the certificates from the CA
if ok := tlsConf.RootCAs.AppendCertsFromPEM(ca); !ok {
return errors.New("failed to append ca certs")
}
return nil
}
func checkFile(path string) error {
absPath, err := filepath.Abs(path)
if err != nil {
return fmt.Errorf("Unable to resolve %v for TLS: please specify a valid and readable file", path)
}
_, err = os.Stat(absPath)
if err != nil {
return fmt.Errorf("Cannot stat %v for TLS: please specify a valid and readable file", absPath)
}
return nil
}