-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtls.go
95 lines (78 loc) · 1.79 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
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"os"
"path/filepath"
)
type CertPool interface {
AppendCertsFromPEM(caBytes []byte) bool
}
var (
ErrFailedToAppend = errors.New("failed to append Root certificate")
ErrTLS = errors.New("TLS Error")
ErrCertPool = errors.New("certPool Error")
ErrCACertFile = errors.New("caCertFile Error")
)
type CertError struct {
Err error
CertFile string
Msg string
}
func (ce *CertError) Error() string {
return fmt.Sprintf("CertError: %s - %s (%s)", ce.Err.Error(), ce.Msg, ce.CertFile)
}
func (ce *CertError) Unwrap() error {
return fmt.Errorf(" %w: %s", ce.Err, ce.Msg)
}
func setupTLS(certFile, certKeyFile, caFile string, certPool CertPool) (*tls.Config, error) {
tlsConfig := &tls.Config{
MinVersion: tls.VersionTLS12,
MaxVersion: tls.VersionTLS13,
}
var err error
tlsConfig.Certificates = make([]tls.Certificate, 1)
tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(
certFile,
certKeyFile,
)
if err != nil {
cErr := &CertError{
CertFile: certFile,
Msg: err.Error(),
Err: ErrTLS,
}
return nil, cErr
}
caBytes, err := os.ReadFile(filepath.Clean(caFile))
if err != nil {
cErr := &CertError{
CertFile: certFile,
Msg: err.Error(),
Err: ErrCACertFile,
}
return nil, cErr
}
ok := certPool.AppendCertsFromPEM(caBytes)
if !ok {
cErr := &CertError{
CertFile: certFile,
Err: ErrFailedToAppend,
}
return nil, cErr
}
certPoolAsX509CertPool, ok := certPool.(*x509.CertPool)
if !ok {
cErr := &CertError{
CertFile: certFile,
Err: ErrCertPool,
}
return nil, cErr
}
tlsConfig.ClientCAs = certPoolAsX509CertPool
tlsConfig.RootCAs = certPoolAsX509CertPool
tlsConfig.ServerName = "0.0.0.0"
return tlsConfig, nil
}