/
transport.go
202 lines (167 loc) · 5.24 KB
/
transport.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package ca
import (
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"fmt"
"net"
"strings"
"sync"
"time"
"google.golang.org/grpc/credentials"
"golang.org/x/net/context"
)
var (
// alpnProtoStr is the specified application level protocols for gRPC.
alpnProtoStr = []string{"h2"}
)
type timeoutError struct{}
func (timeoutError) Error() string { return "mutablecredentials: Dial timed out" }
func (timeoutError) Timeout() bool { return true }
func (timeoutError) Temporary() bool { return true }
// MutableTLSCreds is the credentials required for authenticating a connection using TLS.
type MutableTLSCreds struct {
// Mutex for the tls config
sync.Mutex
// TLS configuration
config *tls.Config
// TLS Credentials
tlsCreds credentials.TransportAuthenticator
// store the subject for easy access
subject pkix.Name
}
// Info implements the credentials.TransportAuthenticator interface
func (c *MutableTLSCreds) Info() credentials.ProtocolInfo {
return credentials.ProtocolInfo{
SecurityProtocol: "tls",
SecurityVersion: "1.2",
}
}
// GetRequestMetadata implements the credentials.TransportAuthenticator interface
func (c *MutableTLSCreds) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return nil, nil
}
// RequireTransportSecurity implements the credentials.TransportAuthenticator interface
func (c *MutableTLSCreds) RequireTransportSecurity() bool {
return true
}
// ClientHandshake implements the credentials.TransportAuthenticator interface
func (c *MutableTLSCreds) ClientHandshake(addr string, rawConn net.Conn, timeout time.Duration) (net.Conn, credentials.AuthInfo, error) {
// borrow all the code from the original TLS credentials
var errChannel chan error
if timeout != 0 {
errChannel = make(chan error, 2)
time.AfterFunc(timeout, func() {
errChannel <- timeoutError{}
})
}
c.Lock()
if c.config.ServerName == "" {
colonPos := strings.LastIndex(addr, ":")
if colonPos == -1 {
colonPos = len(addr)
}
c.config.ServerName = addr[:colonPos]
}
conn := tls.Client(rawConn, c.config)
// Need to allow conn.Handshake to have access to config,
// would create a deadlock otherwise
c.Unlock()
var err error
if timeout == 0 {
err = conn.Handshake()
} else {
go func() {
errChannel <- conn.Handshake()
}()
err = <-errChannel
}
if err != nil {
rawConn.Close()
return nil, nil, err
}
return conn, nil, nil
}
// ServerHandshake implements the credentials.TransportAuthenticator interface
func (c *MutableTLSCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
c.Lock()
conn := tls.Server(rawConn, c.config)
c.Unlock()
if err := conn.Handshake(); err != nil {
rawConn.Close()
return nil, nil, err
}
return conn, credentials.TLSInfo{State: conn.ConnectionState()}, nil
}
// LoadNewTLSConfig replaces the currently loaded TLS config with a new one
func (c *MutableTLSCreds) LoadNewTLSConfig(newConfig *tls.Config) error {
newSubject, err := GetAndValidateCertificateSubject(newConfig.Certificates)
if err != nil {
return err
}
c.Lock()
defer c.Unlock()
c.subject = newSubject
c.config = newConfig
return nil
}
// Config returns the current underlying TLS config.
func (c *MutableTLSCreds) Config() *tls.Config {
c.Lock()
defer c.Unlock()
return c.config
}
// Role returns the OU for the certificate encapsulated in this TransportAuthenticator
func (c *MutableTLSCreds) Role() string {
c.Lock()
defer c.Unlock()
return c.subject.OrganizationalUnit[0]
}
// Organization returns the O for the certificate encapsulated in this TransportAuthenticator
func (c *MutableTLSCreds) Organization() string {
c.Lock()
defer c.Unlock()
return c.subject.Organization[0]
}
// NodeID returns the CN for the certificate encapsulated in this TransportAuthenticator
func (c *MutableTLSCreds) NodeID() string {
c.Lock()
defer c.Unlock()
return c.subject.CommonName
}
// NewMutableTLS uses c to construct a mutable TransportAuthenticator based on TLS.
func NewMutableTLS(c *tls.Config) (*MutableTLSCreds, error) {
originalTC := credentials.NewTLS(c)
if len(c.Certificates) < 1 {
return nil, fmt.Errorf("invalid configuration: needs at least one certificate")
}
subject, err := GetAndValidateCertificateSubject(c.Certificates)
if err != nil {
return nil, err
}
tc := &MutableTLSCreds{config: c, tlsCreds: originalTC, subject: subject}
tc.config.NextProtos = alpnProtoStr
return tc, nil
}
// GetAndValidateCertificateSubject is a helper method to retrieve and validate the subject
// from the x509 certificate underlying a tls.Certificate
func GetAndValidateCertificateSubject(certs []tls.Certificate) (pkix.Name, error) {
for i := range certs {
cert := &certs[i]
x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
if err != nil {
continue
}
if len(x509Cert.Subject.OrganizationalUnit) < 1 {
return pkix.Name{}, fmt.Errorf("no OU found in certificate subject")
}
if len(x509Cert.Subject.Organization) < 1 {
return pkix.Name{}, fmt.Errorf("no organization found in certificate subject")
}
if x509Cert.Subject.CommonName == "" {
return pkix.Name{}, fmt.Errorf("no valid subject names found for TLS configuration")
}
return x509Cert.Subject, nil
}
return pkix.Name{}, fmt.Errorf("no valid certificates found for TLS configuration")
}