-
Notifications
You must be signed in to change notification settings - Fork 41
/
rce.go
60 lines (51 loc) · 1.63 KB
/
rce.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
// Copyright 2017-2023 Block, Inc.
package rce
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
)
// TLSFiles represents the TLS files necessary to create a tls.Config.
type TLSFiles struct {
CACert string
Cert string
Key string
}
// TLSConfig returns a new tls.Config.
func (f TLSFiles) TLSConfig() (*tls.Config, error) {
// If all files empty, then no TLS config
if f.CACert == "" && f.Cert == "" && f.Key == "" {
return nil, nil
}
// If any file is given, all must be given
switch {
case f.CACert == "":
return nil, fmt.Errorf("CA certificate file not specified")
case f.Cert == "":
return nil, fmt.Errorf("Client certificate file not specified")
case f.Key == "":
return nil, fmt.Errorf("Client key file not specified")
}
// Load CA cert
caCert, err := ioutil.ReadFile(f.CACert)
if err != nil {
return nil, err
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
// Load client cert+key
cert, err := tls.LoadX509KeyPair(f.Cert, f.Key)
if err != nil {
return nil, fmt.Errorf("tls.LoadX509KeyPair %s %s: %s", f.Cert, f.Key, err)
}
// Build tls.Config suitable for both client and server side
tlsConfig := &tls.Config{
RootCAs: caCertPool, // client uses to verify server
ClientCAs: caCertPool, // server uses to verify client
ClientAuth: tls.RequireAndVerifyClientCert, // server must verify client cert
Certificates: []tls.Certificate{cert}, // client/server cert (given to other side of connection)
}
tlsConfig.BuildNameToCertificate() // maps CommonName and SubjectAlternateName to cert
return tlsConfig, nil
}