-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
tls_credentials.go
86 lines (76 loc) · 2.35 KB
/
tls_credentials.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
package v2raygrpc
import (
"context"
"net"
"os"
"github.com/sagernet/sing-box/common/tls"
internal_credentials "github.com/sagernet/sing-box/transport/v2raygrpc/credentials"
"google.golang.org/grpc/credentials"
)
type TLSTransportCredentials struct {
config tls.Config
}
func NewTLSTransportCredentials(config tls.Config) credentials.TransportCredentials {
return &TLSTransportCredentials{config}
}
func (c *TLSTransportCredentials) Info() credentials.ProtocolInfo {
return credentials.ProtocolInfo{
SecurityProtocol: "tls",
SecurityVersion: "1.2",
ServerName: c.config.ServerName(),
}
}
func (c *TLSTransportCredentials) ClientHandshake(ctx context.Context, authority string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
cfg := c.config.Clone()
if cfg.ServerName() == "" {
serverName, _, err := net.SplitHostPort(authority)
if err != nil {
serverName = authority
}
cfg.SetServerName(serverName)
}
conn, err := tls.ClientHandshake(ctx, rawConn, cfg)
if err != nil {
return nil, nil, err
}
tlsInfo := credentials.TLSInfo{
State: conn.ConnectionState(),
CommonAuthInfo: credentials.CommonAuthInfo{
SecurityLevel: credentials.PrivacyAndIntegrity,
},
}
id := internal_credentials.SPIFFEIDFromState(conn.ConnectionState())
if id != nil {
tlsInfo.SPIFFEID = id
}
return internal_credentials.WrapSyscallConn(rawConn, conn), tlsInfo, nil
}
func (c *TLSTransportCredentials) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
serverConfig, isServer := c.config.(tls.ServerConfig)
if !isServer {
return nil, nil, os.ErrInvalid
}
conn, err := tls.ServerHandshake(context.Background(), rawConn, serverConfig)
if err != nil {
rawConn.Close()
return nil, nil, err
}
tlsInfo := credentials.TLSInfo{
State: conn.ConnectionState(),
CommonAuthInfo: credentials.CommonAuthInfo{
SecurityLevel: credentials.PrivacyAndIntegrity,
},
}
id := internal_credentials.SPIFFEIDFromState(conn.ConnectionState())
if id != nil {
tlsInfo.SPIFFEID = id
}
return internal_credentials.WrapSyscallConn(rawConn, conn), tlsInfo, nil
}
func (c *TLSTransportCredentials) Clone() credentials.TransportCredentials {
return NewTLSTransportCredentials(c.config)
}
func (c *TLSTransportCredentials) OverrideServerName(serverNameOverride string) error {
c.config.SetServerName(serverNameOverride)
return nil
}