-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathproxy_test.go
More file actions
555 lines (512 loc) · 14.2 KB
/
Copy pathproxy_test.go
File metadata and controls
555 lines (512 loc) · 14.2 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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
package sshpass
import (
"bufio"
"io"
"net"
"net/url"
"strconv"
"strings"
"testing"
"time"
)
func TestProxyDialUnsupportedScheme(t *testing.T) {
_, err := proxyDial("ftp://proxy:21", "example.com:22", 5)
if err == nil {
t.Fatal("expected error for unsupported scheme")
}
}
func TestProxyDialInvalidURL(t *testing.T) {
_, err := proxyDial("not a url", "example.com:22", 5)
if err == nil {
t.Fatal("expected error for invalid URL")
}
}
func TestProxyDialSchemeRouting(t *testing.T) {
// These will fail at the network layer (no real proxy), but should fail
// with a connection error, not a scheme-routing error — proving the
// correct dialer was selected.
cases := []struct {
name string
url string
}{
{"socks5", "socks5://127.0.0.1:1"},
{"socks5h", "socks5h://127.0.0.1:1"},
{"socks4", "socks4://127.0.0.1:1"},
{"http", "http://127.0.0.1:1"},
{"https", "https://127.0.0.1:1"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
_, err := proxyDial(tc.url, "example.com:22", 1)
if err == nil {
t.Fatal("expected connection error (no real proxy)")
}
if strings.Contains(err.Error(), "unsupported proxy scheme") {
t.Errorf("scheme was not routed correctly: %s", err)
}
})
}
}
// --- HTTP CONNECT proxy tests ---
// startHTTPProxy starts a mock HTTP CONNECT proxy that accepts any CONNECT
// request and tunnels the connection to the target. It returns the proxy
// address and a shutdown function.
func startHTTPProxy(t *testing.T, requireAuth string) (addr string, shutdown func()) {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to listen: %v", err)
}
go func() {
for {
conn, err := ln.Accept()
if err != nil {
return
}
go func(c net.Conn) {
defer c.Close()
br := bufio.NewReader(c)
// Read request line.
line, err := br.ReadString('\n')
if err != nil {
return
}
_ = line
// Read headers until blank line.
var headers string
for {
h, err := br.ReadString('\n')
if err != nil {
return
}
headers += h
if h == "\r\n" || h == "\n" {
break
}
}
if requireAuth != "" {
if !strings.Contains(headers, requireAuth) {
c.Write([]byte("HTTP/1.1 407 Proxy Authentication Required\r\n\r\n"))
return
}
}
c.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
// Tunnel any buffered data + future data.
if br.Buffered() > 0 {
buf := make([]byte, br.Buffered())
br.Read(buf)
c.Write(buf)
}
io.Copy(c, br)
}(conn)
}
}()
return ln.Addr().String(), func() { ln.Close() }
}
func TestHTTPProxyConnectAndTunnel(t *testing.T) {
// Start a target echo server.
targetLn, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to listen: %v", err)
}
defer targetLn.Close()
go func() {
for {
conn, err := targetLn.Accept()
if err != nil {
return
}
go func(c net.Conn) {
defer c.Close()
io.Copy(c, c) // echo
}(conn)
}
}()
proxyAddr, shutdown := startHTTPProxy(t, "")
defer shutdown()
proxyURL := "http://" + proxyAddr
conn, err := proxyDial(proxyURL, targetLn.Addr().String(), 5)
if err != nil {
t.Fatalf("proxyDial failed: %v", err)
}
defer conn.Close()
// Write data and verify echo (proves the tunnel works bidirectionally).
msg := []byte("hello-proxy\n")
conn.SetDeadline(time.Now().Add(3 * time.Second))
if _, err := conn.Write(msg); err != nil {
t.Fatalf("write failed: %v", err)
}
buf := make([]byte, len(msg))
if _, err := io.ReadFull(conn, buf); err != nil {
t.Fatalf("read failed: %v", err)
}
if string(buf) != string(msg) {
t.Errorf("echo = %q, want %q", buf, msg)
}
}
func TestHTTPProxyAuth(t *testing.T) {
targetLn, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to listen: %v", err)
}
defer targetLn.Close()
// Proxy requires Basic auth user:pass.
proxyAddr, shutdown := startHTTPProxy(t, "Proxy-Authorization: Basic dXNlcjpwYXNz")
defer shutdown()
u := &url.URL{
Scheme: "http",
Host: proxyAddr,
User: url.UserPassword("user", "pass"),
}
conn, err := httpConnectDial(u, "http", targetLn.Addr().String(), 5)
if err != nil {
t.Fatalf("httpConnectDial with auth failed: %v", err)
}
conn.Close()
}
func TestHTTPProxyRejected(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to listen: %v", err)
}
defer ln.Close()
go func() {
for {
conn, err := ln.Accept()
if err != nil {
return
}
go func(c net.Conn) {
defer c.Close()
br := bufio.NewReader(c)
for {
h, err := br.ReadString('\n')
if err != nil {
return
}
if h == "\r\n" || h == "\n" {
break
}
}
c.Write([]byte("HTTP/1.1 403 Forbidden\r\n\r\n"))
}(conn)
}
}()
_, err = proxyDial("http://"+ln.Addr().String(), "example.com:22", 5)
if err == nil {
t.Fatal("expected error for rejected proxy connection")
}
if !strings.Contains(err.Error(), "403") {
t.Errorf("error should mention status 403, got: %v", err)
}
}
// --- SOCKS4 proxy tests ---
// startSocks4Proxy starts a mock SOCKS4 proxy that accepts CONNECT requests
// and tunnels to the target. It returns the proxy address and shutdown.
func startSocks4Proxy(t *testing.T, targetAddr string) (addr string, shutdown func()) {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to listen: %v", err)
}
go func() {
for {
conn, err := ln.Accept()
if err != nil {
return
}
go func(c net.Conn) {
defer c.Close()
var req [8]byte
if _, err := io.ReadFull(c, req[:]); err != nil {
return
}
// Read userid (null-terminated).
br := bufio.NewReader(c)
_, _ = br.ReadString(0)
// Read hostname for SOCKS4A (if IP is 0.0.0.x).
if req[4] == 0 && req[5] == 0 && req[6] == 0 && req[7] != 0 {
_, _ = br.ReadString(0)
}
// Reply: success (0x5a).
resp := []byte{0x00, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
c.Write(resp)
// Tunnel.
io.Copy(c, br)
}(conn)
}
}()
return ln.Addr().String(), func() { ln.Close() }
}
func TestSocks4ProxyConnectAndTunnel(t *testing.T) {
// Start a target echo server.
targetLn, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to listen: %v", err)
}
defer targetLn.Close()
go func() {
for {
conn, err := targetLn.Accept()
if err != nil {
return
}
go func(c net.Conn) {
defer c.Close()
io.Copy(c, c)
}(conn)
}
}()
proxyAddr, shutdown := startSocks4Proxy(t, targetLn.Addr().String())
defer shutdown()
// Use the numeric IP of the echo server so SOCKS4 (not 4A) is used.
host, portStr, _ := net.SplitHostPort(targetLn.Addr().String())
port, _ := strconv.Atoi(portStr)
_ = host
_ = port
conn, err := proxyDial("socks4://"+proxyAddr, targetLn.Addr().String(), 5)
if err != nil {
t.Fatalf("proxyDial socks4 failed: %v", err)
}
defer conn.Close()
msg := []byte("socks4-test\n")
conn.SetDeadline(time.Now().Add(3 * time.Second))
if _, err := conn.Write(msg); err != nil {
t.Fatalf("write failed: %v", err)
}
buf := make([]byte, len(msg))
if _, err := io.ReadFull(conn, buf); err != nil {
t.Fatalf("read failed: %v", err)
}
if string(buf) != string(msg) {
t.Errorf("echo = %q, want %q", buf, msg)
}
}
func TestSocks4AProxyHostnameMode(t *testing.T) {
// SOCKS4A with a hostname (non-IP) target should send the hostname.
targetLn, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to listen: %v", err)
}
defer targetLn.Close()
go func() {
for {
conn, err := targetLn.Accept()
if err != nil {
return
}
go func(c net.Conn) {
defer c.Close()
io.Copy(c, c)
}(conn)
}
}()
proxyAddr, shutdown := startSocks4Proxy(t, "")
defer shutdown()
// Pass a hostname target (localhost) to trigger SOCKS4A mode.
conn, err := proxyDial("socks4://"+proxyAddr, targetLn.Addr().String(), 5)
if err != nil {
t.Fatalf("proxyDial socks4 (4A mode) failed: %v", err)
}
conn.Close()
}
func TestSocks4ProxyRejected(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to listen: %v", err)
}
defer ln.Close()
go func() {
for {
conn, err := ln.Accept()
if err != nil {
return
}
go func(c net.Conn) {
defer c.Close()
var req [8]byte
io.ReadFull(c, req[:])
br := bufio.NewReader(c)
br.ReadString(0)
if req[4] == 0 && req[5] == 0 && req[6] == 0 && req[7] != 0 {
br.ReadString(0)
}
// Reply: rejected (0x5b).
c.Write([]byte{0x00, 0x5b, 0, 0, 0, 0, 0, 0})
}(conn)
}
}()
_, err = proxyDial("socks4://"+ln.Addr().String(), "127.0.0.1:22", 5)
if err == nil {
t.Fatal("expected error for rejected SOCKS4 connection")
}
if !strings.Contains(err.Error(), "rejected") {
t.Errorf("error should mention rejection, got: %v", err)
}
}
// --- Default port tests ---
func TestSocksDialDefaultPort(t *testing.T) {
// When no port is in the proxy URL, socksDial defaults to 1080.
// We can't easily test the actual connection, but we can verify the
// address parsing doesn't panic and routes to the right port by checking
// the error message mentions port 1080.
_, err := proxyDial("socks5://127.0.0.1", "example.com:22", 1)
if err == nil {
return // connected somehow (unlikely)
}
// The connection error should reference 127.0.0.1:1080.
if !strings.Contains(err.Error(), "1080") {
t.Logf("note: error did not mention default port 1080: %v", err)
}
}
func TestHTTPProxyDefaultPort(t *testing.T) {
// http:// without port should default to 80.
_, err := proxyDial("http://127.0.0.1", "example.com:22", 1)
if err == nil {
return
}
// Should not be a "missing host" or "unsupported scheme" error.
if strings.Contains(err.Error(), "unsupported proxy scheme") {
t.Errorf("http scheme should be supported: %v", err)
}
}
// TestHTTPProxyPreservesBufferedData verifies the Bug 1 fix: when the proxy
// (or the SSH server behind it) pushes data immediately after the "200
// Connection established" response headers — in the same TCP segment that the
// bufio.Reader consumed while parsing headers — those bytes must be delivered
// to the caller, not lost in the bufio buffer.
func TestHTTPProxyPreservesBufferedData(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to listen: %v", err)
}
defer ln.Close()
// The "extra" data the proxy injects right after the headers, simulating
// an SSH banner or handshake start pushed by the target server.
extraData := []byte("SSH-2.0-OpenSSH_8.9\r\n")
go func() {
for {
conn, err := ln.Accept()
if err != nil {
return
}
go func(c net.Conn) {
defer c.Close()
br := bufio.NewReader(c)
// Consume the CONNECT request line + headers.
for {
line, err := br.ReadString('\n')
if err != nil {
return
}
if line == "\r\n" || line == "\n" {
break
}
}
// Write the 200 response AND the extra data in a single
// Write call so they land in the same TCP segment and the
// client's bufio.Reader buffers both.
resp := append([]byte("HTTP/1.1 200 Connection established\r\n\r\n"), extraData...)
c.Write(resp)
// Echo any subsequent data from the client.
io.Copy(c, br)
}(conn)
}
}()
conn, err := proxyDial("http://"+ln.Addr().String(), "example.com:22", 5)
if err != nil {
t.Fatalf("proxyDial failed: %v", err)
}
defer conn.Close()
// The extraData bytes must be readable from the returned connection.
// If the bufferedConn fix is missing, this read will hang/timeout because
// the bytes are stuck in the bufio.Reader that was discarded.
buf := make([]byte, len(extraData))
conn.SetDeadline(time.Now().Add(3 * time.Second))
if _, err := io.ReadFull(conn, buf); err != nil {
t.Fatalf("failed to read buffered data (Bug 1 regression?): %v", err)
}
if string(buf) != string(extraData) {
t.Errorf("buffered data = %q, want %q", buf, extraData)
}
}
// TestSocks4ProxyUserID verifies that the username from the proxy URL is sent
// as the SOCKS4 userid field in the CONNECT request.
func TestSocks4ProxyUserID(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to listen: %v", err)
}
defer ln.Close()
receivedUserID := make(chan string, 1)
go func() {
conn, err := ln.Accept()
if err != nil {
return
}
defer conn.Close()
// Read the 8-byte SOCKS4 header.
var header [8]byte
if _, err := io.ReadFull(conn, header[:]); err != nil {
receivedUserID <- ""
return
}
// Read the null-terminated userid.
br := bufio.NewReader(conn)
userid, _ := br.ReadString(0)
userid = strings.TrimRight(userid, "\x00")
receivedUserID <- userid
// Reply success so the caller doesn't hang.
conn.Write([]byte{0x00, 0x5a, 0, 0, 0, 0, 0, 0})
}()
conn, err := proxyDial("socks4://myuser@"+ln.Addr().String(), "127.0.0.1:22", 5)
if err != nil {
t.Fatalf("proxyDial failed: %v", err)
}
conn.Close()
select {
case uid := <-receivedUserID:
if uid != "myuser" {
t.Errorf("SOCKS4 userid = %q, want %q", uid, "myuser")
}
case <-time.After(3 * time.Second):
t.Fatal("timed out waiting for proxy to receive SOCKS4 request")
}
}
// TestSocks5ProxyTimeout verifies that socks5Dial does not hang forever when
// the proxy accepts the TCP connection but never responds to the SOCKS5
// negotiation (Bug 2 regression test).
func TestSocks5ProxyTimeout(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to listen: %v", err)
}
defer ln.Close()
go func() {
for {
conn, err := ln.Accept()
if err != nil {
return
}
// Accept the connection but never send any SOCKS5 response,
// simulating a broken/hung proxy.
go func(c net.Conn) {
defer c.Close()
io.Copy(io.Discard, c)
}(conn)
}
}()
start := time.Now()
_, err = proxyDial("socks5://"+ln.Addr().String(), "example.com:22", 2)
elapsed := time.Since(start)
if err == nil {
t.Fatal("expected timeout error, got nil")
}
// Should time out around 2s, not hang indefinitely. Allow some slack.
if elapsed > 5*time.Second {
t.Errorf("dial took %v, expected ~2s timeout", elapsed)
}
if !strings.Contains(err.Error(), "timed out") {
t.Errorf("error should mention timeout, got: %v", err)
}
}