This repository was archived by the owner on May 5, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerictcp.go
More file actions
405 lines (340 loc) · 8.58 KB
/
Copy pathgenerictcp.go
File metadata and controls
405 lines (340 loc) · 8.58 KB
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
package main
import (
"bufio"
"bytes"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"log"
"net"
"os"
"strconv"
"strings"
"time"
)
var (
genericTCPRedirectRules = make(map[int][]GenericRedirectRule)
genericTCPRedirectPorts = make(map[int]bool)
)
type GenericRedirectRule struct {
Host string
Port int
SRV string
}
type GenericTCPProxy struct {
ListenPort int
Rule []GenericRedirectRule
// TLS config for upstream connections
ClientTLSConfig *tls.Config
ServerTLSConfig *tls.Config
debug bool
ServerCA tls.Certificate
}
type GTCPConnection struct {
id string
clientConn net.Conn
serverConn net.Conn
listenPort int
Rule []GenericRedirectRule
debug bool
}
func loadGenericTCPRules() error {
genericTCPFile := "generic-tcp.txt"
if _, err := os.Stat(genericTCPFile); os.IsNotExist(err) {
return nil
}
file, err := os.Open(genericTCPFile)
if err != nil {
return fmt.Errorf("failed to open generic-tcp file: %w", err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
lineNum := 0
fromPort := 0
for scanner.Scan() {
lineNum++
line := strings.TrimSpace(scanner.Text())
// Skip empty lines
if line == "" {
continue
}
if fromPort == 0 {
fromPort, err = strconv.Atoi(line)
if err != nil {
log.Printf("Warning: Invalid port on line %d: %s", lineNum, line)
}
continue
} else {
slice := strings.Split(line, ":")
if len(slice) < 2 {
log.Printf("Warning: Invalid host:port combo on line %d: %s", lineNum, line)
continue
}
host := slice[0]
port, err := strconv.Atoi(slice[1])
if err != nil {
log.Printf("Warning: Invalid port on line %d: %s", lineNum, slice[2])
continue
}
parts := strings.SplitN(host, ".", 3)
srv := ""
if len(parts) == 3 && strings.HasPrefix(parts[0], "_") && parts[1] == "_tcp" {
srv = parts[0]
host = parts[2]
}
rule := GenericRedirectRule{
Host: host,
Port: port,
SRV: srv,
}
genericTCPRedirectRules[fromPort] = append(genericTCPRedirectRules[port], rule)
genericTCPRedirectPorts[fromPort] = true
fromPort = 0
}
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("error reading generic-tcp file: %w", err)
}
if len(genericTCPRedirectPorts) == 0 {
return fmt.Errorf("Got no redirect rules")
}
return nil
}
func genericTCPProxyMain(systemRoots *x509.CertPool, ca tls.Certificate, tlsServerConfig *tls.Config) {
if err := loadGenericTCPRules(); err != nil {
log.Fatalf("Error loading exclusion rules: %v", err)
}
if len(genericTCPRedirectPorts) != 0 {
ClientTLSConfig := &tls.Config{
MinVersion: tls.VersionTLS12,
RootCAs: systemRoots,
}
for listenPort, rule := range genericTCPRedirectRules {
p := &GenericTCPProxy{
ListenPort: listenPort,
Rule: rule,
ClientTLSConfig: ClientTLSConfig,
ServerTLSConfig: tlsServerConfig,
debug: *debug,
ServerCA: ca,
}
p.Start()
log.Printf("Generic TCP proxy started")
}
}
}
// Start starts the mail proxy listener
func (p *GenericTCPProxy) Start() {
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", p.ListenPort))
if err != nil {
log.Fatalf("failed to start proxy on port %d: %s", p.ListenPort, err)
}
go func() {
for {
conn, err := listener.Accept()
if err != nil {
if p.debug {
log.Printf("%d proxy accept error: %v", p.ListenPort, err)
}
continue
} else {
log.Printf("%d proxy accepted connection", p.ListenPort)
}
go p.handleConnection(conn)
}
}()
}
// handleConnection handles a single client connection
func (p *GenericTCPProxy) handleConnection(clientConn net.Conn) {
// Check if connection is from localhost unless allow-remote-connections is set
if *blockRemoteConnections {
host, _, err := net.SplitHostPort(clientConn.RemoteAddr().String())
if err != nil {
if p.debug {
log.Printf("[%d] Error parsing remote address: %v", p.ListenPort, err)
}
clientConn.Close()
return
}
// Check if the connection is from localhost
ip := net.ParseIP(host)
if ip == nil || !ip.IsLoopback() {
if p.debug {
log.Printf("[%d] Rejected non-localhost connection from %s", p.ListenPort, host)
}
clientConn.Close()
return
}
}
connID := fmt.Sprintf("%d-%p", p.ListenPort, clientConn)
c := >CPConnection{
id: connID,
clientConn: clientConn,
debug: p.debug,
listenPort: p.ListenPort,
Rule: p.Rule,
}
if c.debug {
log.Printf("[%s] New connection from %s", connID, clientConn.RemoteAddr())
}
err := c.connectToServer(p.ClientTLSConfig)
if err != nil {
log.Printf("[%s] Error when connecting to remote: %s", connID, err)
clientConn.Close()
return
}
p.handleData(c)
}
// connectToServer establishes connection to the real mail server
func (c *GTCPConnection) connectToServer(tlsConfig *tls.Config) error {
rule := c.Rule[0]
host := rule.Host
port := rule.Port
fallbackSN := ""
if rule.SRV != "" {
_, addrs, err := net.LookupSRV(strings.TrimSuffix(strings.TrimPrefix(rule.SRV, "_"), "._tcp"), "tcp", host)
if err == nil {
fallbackSN = fmt.Sprintf("%s:%d", host, port)
host = addrs[0].Target
port = int(addrs[0].Port)
}
}
// Add port if not specified
server := host
if !strings.Contains(server, ":") {
server = fmt.Sprintf("%s:%d", server, port)
}
if c.debug {
log.Printf("[%s] Connecting to %s", c.id, server)
}
var tlsConf *tls.Config
if tlsConfig == nil {
tlsConf = &tls.Config{
ServerName: host,
}
} else {
tlsConf = tlsConfig
tlsConf.ServerName = host
}
conn, err := tls.Dial("tcp", server, tlsConf)
if err != nil {
if fallbackSN != "" {
conn, err2 := tls.Dial("tcp", fallbackSN, tlsConf)
if err2 != nil {
return fmt.Errorf("%s, %s", err, err2)
}
c.serverConn = conn
return nil
}
return err
}
c.serverConn = conn
return nil
}
func (p *GenericTCPProxy) handleData(c *GTCPConnection) {
// Peek at the ClientHello to determine routing
clientHello, err := peekClientHello(c.clientConn)
if err != nil {
log.Printf("[%s] Error on peeking handshake: %s", c.id, err)
c.clientConn.Close()
return
}
if clientHello.isModernClient && *blockModernConnections {
return
}
var sConfig *tls.Config
// Create TLS server config
if p.ServerTLSConfig == nil {
sConfig = new(tls.Config)
} else {
sConfig = p.ServerTLSConfig
}
//sConfig.Certificates = []tls.Certificate{sConfig.RootCAs}
sConfig.GetCertificate = func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
return &p.ServerCA, nil
}
// Create a connection that can replay the ClientHello
var tlsConn *tls.Conn
if clientHello != nil {
// We have already read the ClientHello, so we need to create a special connection
// that will replay it when the TLS handshake starts
replayConn := &replayConn{
Conn: c.clientConn,
buffer: bytes.NewBuffer(clientHello.raw),
}
tlsConn = tls.Server(replayConn, sConfig)
} else {
// No ClientHello was peeked, proceed normally
tlsConn = tls.Server(c.clientConn, sConfig)
}
// Perform TLS handshake
err = tlsConn.Handshake()
if err != nil {
log.Printf("[%s] Error on peeking handshake: %s", c.id, err)
tlsConn.Close()
return
}
if c.debug {
log.Printf("[%s] Handshake finish", c.id)
}
c.transparentProxy(tlsConn)
}
// transparentProxy switches to transparent proxy mode after authentication
func (c *GTCPConnection) transparentProxy(tlsConn *tls.Conn) {
if c.debug {
log.Printf("[%s] Switching to transparent proxy mode", c.id)
}
// Verify connections are established
if tlsConn == nil {
if c.debug {
log.Printf("[%s] ERROR: clientConn is nil in transparentProxy", c.id)
}
return
}
if c.serverConn == nil {
if c.debug {
log.Printf("[%s] ERROR: serverConn is nil in transparentProxy", c.id)
}
return
}
errc := make(chan error, 2)
go func() {
_, err := io.Copy(tlsConn, c.serverConn)
errc <- err
}()
go func() {
_, err := io.Copy(c.serverConn, tlsConn)
errc <- err
}()
err2 := <-errc
if c.debug {
log.Printf("[%s] Close starting", c.id)
}
tlsConn.CloseWrite()
err1 := <-errc
ignore := func(err error) bool {
if err == nil {
return true
}
s := err.Error()
return strings.Contains(s, "use of closed network connection") ||
strings.Contains(s, "protocol is shutdown") ||
strings.Contains(s, "close_notify") ||
strings.Contains(s, "i/o timeout") ||
err == io.EOF
}
if !ignore(err1) {
log.Printf("[%s] copy error: %v", c.id, err1)
}
if !ignore(err2) {
log.Printf("[%s] copy error: %v", c.id, err2)
}
if c.debug {
log.Printf("[%s] Goodbye!", c.id)
}
tlsConn.SetDeadline(time.Time{})
c.serverConn.SetDeadline(time.Time{})
tlsConn.Close()
c.serverConn.Close()
}