forked from folbricht/routedns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dtls.go
70 lines (63 loc) · 1.82 KB
/
dtls.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
package rdns
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"github.com/pion/dtls/v2"
)
// DTLSServerConfig is a convenience function that builds a dtls.Config instance for DTLS servers
// based on common options and certificate+key files.
func DTLSServerConfig(caFile, crtFile, keyFile string, mutualTLS bool) (*dtls.Config, error) {
dtlsConfig := &dtls.Config{}
if mutualTLS {
dtlsConfig.ClientAuth = dtls.RequireAndVerifyClientCert
}
if caFile != "" {
certPool := x509.NewCertPool()
b, err := ioutil.ReadFile(caFile)
if err != nil {
return nil, err
}
if ok := certPool.AppendCertsFromPEM(b); !ok {
return nil, fmt.Errorf("no CA certificates found in %s", caFile)
}
dtlsConfig.ClientCAs = certPool
}
if crtFile != "" && keyFile != "" {
var err error
dtlsConfig.Certificates = make([]tls.Certificate, 1)
dtlsConfig.Certificates[0], err = tls.LoadX509KeyPair(crtFile, keyFile)
if err != nil {
return nil, err
}
}
return dtlsConfig, nil
}
// DTLSClientConfig is a convenience function that builds a dtls.Config instance for TLS clients
// based on common options and certificate+key files.
func DTLSClientConfig(caFile, crtFile, keyFile string) (*dtls.Config, error) {
dtlsConfig := &dtls.Config{}
// Add client key/cert if provided
if crtFile != "" && keyFile != "" {
var err error
dtlsConfig.Certificates = make([]tls.Certificate, 1)
dtlsConfig.Certificates[0], err = tls.LoadX509KeyPair(crtFile, keyFile)
if err != nil {
return nil, err
}
}
// Load custom CA set if provided
if caFile != "" {
certPool := x509.NewCertPool()
b, err := ioutil.ReadFile(caFile)
if err != nil {
return nil, err
}
if ok := certPool.AppendCertsFromPEM(b); !ok {
return nil, fmt.Errorf("no CA certificates found in %s", caFile)
}
dtlsConfig.RootCAs = certPool
}
return dtlsConfig, nil
}