/
tls.go
59 lines (52 loc) · 1.31 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
package tls
import (
"crypto/tls"
"crypto/x509"
"io/ioutil"
"net"
"github.com/MainfluxLabs/mproxy/pkg/errors"
)
var (
errTLSdetails = errors.New("failed to get TLS details of connection")
errParseRoot = errors.New("failed to parse root certificate")
)
// LoadTLSCfg return a TLS configuration that can be used in TLS servers
func LoadTLSCfg(ca, crt, key string) (*tls.Config, error) {
caCertPEM, err := ioutil.ReadFile(ca)
if err != nil {
return nil, err
}
roots := x509.NewCertPool()
if ok := roots.AppendCertsFromPEM(caCertPEM); !ok {
return nil, errParseRoot
}
cert, err := tls.LoadX509KeyPair(crt, key)
if err != nil {
return nil, err
}
return &tls.Config{
Certificates: []tls.Certificate{cert},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: roots,
}, nil
}
// ClientCert returns client certificate
func ClientCert(conn net.Conn) (x509.Certificate, error) {
switch connVal := conn.(type) {
case *tls.Conn:
if err := connVal.Handshake(); err != nil {
return x509.Certificate{}, err
}
state := connVal.ConnectionState()
if state.Version == 0 {
return x509.Certificate{}, errTLSdetails
}
if len(state.PeerCertificates) == 0 {
return x509.Certificate{}, nil
}
cert := *state.PeerCertificates[0]
return cert, nil
default:
return x509.Certificate{}, nil
}
}