-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtls.go
More file actions
54 lines (46 loc) · 1.15 KB
/
Copy pathtls.go
File metadata and controls
54 lines (46 loc) · 1.15 KB
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
package lock
import (
"crypto/tls"
"crypto/x509"
"fmt"
"os"
)
type TLSConfig struct {
Cert string `mapstructure:"cert"`
Key string `mapstructure:"key"`
RootCa string `mapstructure:"root_ca"`
}
// tlsConfig builds the client TLS configuration. A nil conf keeps the connection plaintext.
func tlsConfig(conf *TLSConfig) (*tls.Config, error) {
if conf == nil {
return nil, nil
}
cfg := &tls.Config{MinVersion: tls.VersionTLS12}
// Validate rejects a certificate without its key.
if conf.Cert != "" {
// The handshake loads the pair, so a renewed certificate needs no restart.
cfg.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
cert, err := tls.LoadX509KeyPair(conf.Cert, conf.Key)
if err != nil {
return nil, err
}
return new(cert), nil
}
}
if conf.RootCa == "" {
return cfg, nil
}
pool, err := x509.SystemCertPool()
if err != nil {
return nil, err
}
rootCa, err := os.ReadFile(conf.RootCa)
if err != nil {
return nil, err
}
if !pool.AppendCertsFromPEM(rootCa) {
return nil, fmt.Errorf("no certificate found in %q", conf.RootCa)
}
cfg.RootCAs = pool
return cfg, nil
}