-
Notifications
You must be signed in to change notification settings - Fork 2
/
tls.go
82 lines (64 loc) · 2.32 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
73
74
75
76
77
78
79
80
81
82
package httpc
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"net/http"
"path/filepath"
)
var defaultTransport = http.DefaultTransport.(*http.Transport).Clone()
// setupClientCertificateFromBytes reads the provided client certificate / key and CA certificate
// from memory and creates / modifies a tls.Config object
func setupClientCertificateFromBytes(clientCert, clientKey, caCert []byte, tlsConfig *tls.Config) (*tls.Config, error) {
// Load the key pair
clientKeyCert, err := tls.X509KeyPair(clientCert, clientKey)
if err != nil {
return nil, fmt.Errorf("failed to load client key / certificate: %s", err)
}
// If required, instantiate CA certificate pool
if tlsConfig == nil || tlsConfig.RootCAs == nil {
caCertPool, err := x509.SystemCertPool()
if err != nil {
return nil, fmt.Errorf("failed to obtain system CA pool: %s", err)
}
tlsConfig.RootCAs = caCertPool
}
// Append CA to pool
if !tlsConfig.RootCAs.AppendCertsFromPEM(caCert) {
return nil, fmt.Errorf("failed to add CA certificate to pool: %s", err)
}
// Append client certificate to config
tlsConfig.Certificates = append(tlsConfig.Certificates, clientKeyCert)
return tlsConfig, nil
}
// readClientCertificateFiles reads the provided client certificate / key and CA certificate
// files
func readClientCertificateFiles(certFile, keyFile, caFile string) ([]byte, []byte, []byte, error) {
// Read the client certificate / key file
clientCert, clientKey, err := readclientKeyCertificate(certFile, keyFile)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to read / decode client key / certificate file: %s", err)
}
// Read CA certificate from file
caCert, err := ioutil.ReadFile(filepath.Clean(caFile))
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to read CA certificate: %s", err)
}
return clientCert, clientKey, caCert, nil
}
// readclientKeyCertificate reads both client certificate and key from their
// respective files
func readclientKeyCertificate(certFile, keyFile string) ([]byte, []byte, error) {
// Read the client certificate file
clientCert, err := ioutil.ReadFile(filepath.Clean(certFile))
if err != nil {
return nil, nil, err
}
// Read the client key file
clientKey, err := ioutil.ReadFile(filepath.Clean(keyFile))
if err != nil {
return nil, nil, err
}
return clientCert, clientKey, nil
}