-
Notifications
You must be signed in to change notification settings - Fork 5
/
mutualtls.go
61 lines (55 loc) · 1.44 KB
/
mutualtls.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
package mutualtls
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"os"
)
func NewServerTLSConfig(certFile, keyFile, caCertFile string) (*tls.Config, error) {
c, err := newTLSConfig(certFile, keyFile)
if err != nil {
return nil, err
}
c.ClientCAs, err = newCACertPool(caCertFile)
if err != nil {
return nil, err
}
c.ClientAuth = tls.RequireAndVerifyClientCert
c.CipherSuites = []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}
return c, nil
}
func NewClientTLSConfig(certFile, keyFile, caCertFile string) (*tls.Config, error) {
c, err := newTLSConfig(certFile, keyFile)
if err != nil {
return nil, err
}
c.RootCAs, err = newCACertPool(caCertFile)
if err != nil {
return nil, err
}
return c, nil
}
func newTLSConfig(certFile, keyFile string) (*tls.Config, error) {
keyPair, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, fmt.Errorf("unable to load cert or key: %s", err)
}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{keyPair},
MinVersion: tls.VersionTLS12,
MaxVersion: tls.VersionTLS13,
}
return tlsConfig, nil
}
func newCACertPool(caCertFile string) (*x509.CertPool, error) {
certBytes, err := os.ReadFile(caCertFile)
if err != nil {
return nil, fmt.Errorf("failed read ca cert file: %s", err.Error())
}
caCertPool := x509.NewCertPool()
if ok := caCertPool.AppendCertsFromPEM(certBytes); !ok {
return nil, errors.New("Unable to load caCert")
}
return caCertPool, nil
}