-
Notifications
You must be signed in to change notification settings - Fork 19
/
client.go
232 lines (207 loc) · 5.7 KB
/
client.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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
// Copyright (C) 2020-2021, IrineSistiana
//
// This file is part of simple-tls.
//
// simple-tls is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// simple-tls is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package core
import (
"bytes"
"context"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"errors"
"fmt"
"github.com/IrineSistiana/simple-tls/core/ctunnel"
"github.com/IrineSistiana/simple-tls/core/grpc_lb"
"google.golang.org/grpc"
"google.golang.org/grpc/backoff"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/keepalive"
"net"
"os"
"strings"
"time"
)
type Client struct {
BindAddr string
DstAddr string
GRPC bool
GRPCServiceName string
ServerName string
CA string
CertHash string
InsecureSkipVerify bool
IdleTimeout time.Duration
SocketOpts *TcpConfig
OutboundBuf int
InboundBuf int
testListener net.Listener
}
var errEmptyCAFile = errors.New("no valid certificate was found in the ca file")
func (c *Client) ActiveAndServe() error {
var l net.Listener
if c.testListener != nil {
l = c.testListener
} else {
var err error
lc := net.ListenConfig{}
l, err = lc.Listen(context.Background(), "tcp", c.BindAddr)
if err != nil {
return err
}
}
l = wrapListener(l, c.InboundBuf)
if len(c.ServerName) == 0 {
c.ServerName = strings.SplitN(c.DstAddr, ":", 2)[0]
}
var rootCAs *x509.CertPool
if len(c.CA) != 0 {
rootCAs = x509.NewCertPool()
certPEMBlock, err := os.ReadFile(c.CA)
if err != nil {
return fmt.Errorf("cannot read ca file: %w", err)
}
if ok := rootCAs.AppendCertsFromPEM(certPEMBlock); !ok {
return errEmptyCAFile
}
}
dialer := &net.Dialer{
Timeout: time.Second * 5,
Control: GetControlFunc(c.SocketOpts),
}
var chb []byte
if len(c.CertHash) != 0 {
b, err := hex.DecodeString(c.CertHash)
if err != nil {
return fmt.Errorf("invalid cert hash: %w", err)
}
chb = b
}
tlsConfig := &tls.Config{
ServerName: c.ServerName,
RootCAs: rootCAs,
InsecureSkipVerify: len(chb) > 0 || c.InsecureSkipVerify,
VerifyConnection: func(state tls.ConnectionState) error {
if len(chb) > 0 {
cert := state.PeerCertificates[0]
h := sha256.Sum256(cert.RawTBSCertificate)
if bytes.Equal(h[:len(chb)], chb) {
return nil
}
return fmt.Errorf("cert hash mismatch, recieved cert hash is [%s]", hex.EncodeToString(h[:]))
}
if state.Version != tls.VersionTLS13 {
return fmt.Errorf("unsafe tls version %d", state.Version)
}
return nil
},
}
var dialRemote func(ctx context.Context) (net.Conn, error)
if c.GRPC {
grpcDialOpts := []grpc.DialOption{
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: time.Second * 20,
Timeout: time.Second * 5,
PermitWithoutStream: false,
}),
grpc.WithConnectParams(grpc.ConnectParams{
Backoff: backoff.Config{
BaseDelay: time.Second,
Multiplier: 1.1,
Jitter: 0.5,
MaxDelay: time.Second * 5,
},
}),
grpc.WithInitialWindowSize(64 * 1024),
grpc.WithInitialConnWindowSize(64 * 1024),
grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)),
grpc.WithContextDialer(func(ctx context.Context, s string) (net.Conn, error) {
remoteConn, err := dialer.DialContext(ctx, "tcp", s)
if remoteConn != nil {
applyTCPSocketBuf(remoteConn, c.OutboundBuf)
}
return remoteConn, err
}),
}
grpcConnPool := grpc_lb.NewConnPool(grpc_lb.ConnPoolOpts{
Target: c.DstAddr,
ServiceName: c.GRPCServiceName,
DialOpts: grpcDialOpts,
})
dialRemote = func(ctx context.Context) (net.Conn, error) {
return grpcConnPool.GetConn(ctx)
}
} else {
dialRemote = func(ctx context.Context) (net.Conn, error) {
tlsDialer := tls.Dialer{NetDialer: dialer, Config: tlsConfig}
remoteConn, err := tlsDialer.DialContext(ctx, "tcp", c.DstAddr)
if remoteConn != nil {
applyTCPSocketBuf(remoteConn, c.OutboundBuf)
}
return remoteConn, err
}
}
for {
clientConn, err := l.Accept()
if err != nil {
return err
}
go func() {
defer clientConn.Close()
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
serverConn, err := dialRemote(ctx)
if err != nil {
errLogger.Printf("failed to dial server connection: %v", err)
return
}
defer serverConn.Close()
err = ctunnel.OpenTunnel(clientConn, serverConn, ctunnel.TunnelOpts{IdleTimout: c.IdleTimeout})
if err != nil {
logConnErr(clientConn, fmt.Errorf("tunnel closed: %w", err))
}
}()
}
}
// listenerWrapper automatically set tcp socket buf when new conn is accepted.
type listenerWrapper struct {
buf int
innerL net.Listener
}
func wrapListener(l net.Listener, buf int) net.Listener {
lw, ok := l.(*listenerWrapper)
if ok {
lw.buf = buf
return lw
}
return &listenerWrapper{
buf: buf,
innerL: l,
}
}
func (l *listenerWrapper) Accept() (net.Conn, error) {
c, err := l.innerL.Accept()
if c != nil {
applyTCPSocketBuf(c, l.buf)
}
return c, err
}
func (l *listenerWrapper) Close() error {
return l.innerL.Close()
}
func (l *listenerWrapper) Addr() net.Addr {
return l.innerL.Addr()
}