-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathipproxy_test.go
More file actions
354 lines (319 loc) · 9.25 KB
/
ipproxy_test.go
File metadata and controls
354 lines (319 loc) · 9.25 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
package ipproxy
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
"os/exec"
"runtime"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/getlantern/fdcount"
"github.com/stretchr/testify/assert"
)
const (
shortIdleTimeout = 1 * time.Second
longIdleTimeout = 1000 * time.Minute
)
var (
serverTCPConnections int64
)
func TestRoundtrip(t *testing.T) {
dev, err := TUNDevice("tun5", "10.0.1.2", "10.0.2.1", "255.255.255.0", 1500)
require.NoError(t, err)
t.Cleanup(func() { dev.Close() })
outIF, err := net.InterfaceByName("eno2")
require.NoError(t, err)
outIFAddrs, err := outIF.Addrs()
require.NoError(t, err)
var laddrTCP *net.TCPAddr
var laddrUDP *net.UDPAddr
for _, outIFAddr := range outIFAddrs {
switch t := outIFAddr.(type) {
case *net.IPNet:
ipv4 := t.IP.To4()
if ipv4 != nil {
laddrTCP = &net.TCPAddr{IP: ipv4, Port: 0}
laddrUDP = &net.UDPAddr{IP: ipv4, Port: 0}
break
}
}
}
require.NotNil(t, laddrTCP)
log.Debugf("Outbound TCP will use %v", laddrTCP)
log.Debugf("Outbound UDP will use %v", laddrUDP)
var d net.Dialer
p, err := New(&Opts{
IdleTimeout: 70 * time.Second,
StatsInterval: 3 * time.Second,
DialTCP: func(ctx context.Context, network, addr string) (net.Conn, error) {
conn, err := d.DialContext(ctx, network, "localhost:9876")
log.Debugf("Dialed %v", conn.RemoteAddr())
return conn, err
},
DialUDP: func(ctx context.Context, network, addr string) (net.Conn, error) {
return nil, errors.New("not implemented")
},
})
require.NoError(t, err)
// Listen for incoming connections on port 8080
ln, err := net.Listen("tcp", ":9876")
t.Cleanup(func() { ln.Close() })
require.NoError(t, err)
result := bytes.Buffer{}
go func() {
t.Log("Accepting connections")
conn, err := ln.Accept()
require.NoError(t, err)
t.Log("Connection accepted")
// read in loop
for {
buf := make([]byte, 1024)
n, err := conn.Read(buf)
if errors.Is(err, io.EOF) {
t.Log("EOF")
conn.Close()
break
}
t.Log(fmt.Sprintf("read %d bytes: %v", n, string(buf[:n])))
require.NoError(t, err)
result.Write(buf[:n])
}
}()
go p.Serve(context.Background())
// execute: `sudo route add -host 185.85.17.95 dev tun5`
// Add a route to the host 185.85.17.95 using the tun5 device
cmd := exec.Command("sudo", "route", "add", "-host", "185.85.17.95", "dev", "tun5")
err = cmd.Run()
require.NoError(t, err)
go func() {
// connect to 185.85.17.95 on any port and write hello\nhello!
conn, err := net.Dial("tcp", "185.85.17.95:9876")
require.NoError(t, err)
_, err = conn.Write([]byte("hello my baby, hello my darling\n"))
require.NoError(t, err)
time.Sleep(1 * time.Second)
_, err = conn.Write([]byte("bye!"))
require.NoError(t, err)
conn.Close()
}()
time.Sleep(2 * time.Second)
p.Close()
require.Equal(t, "hello my baby, hello my darling\nbye!", result.String())
}
// Note - this test has to be run with root permissions to allow setting up the
// TUN device.
func TestTCPAndUDP(t *testing.T) {
doTest(
t,
2,
shortIdleTimeout,
"10.0.1.2", "10.0.1.1",
func(p Proxy, uconn net.Conn, b []byte) {
assert.Equal(t, "helloudp", string(b))
},
func(p Proxy, conn net.Conn, b []byte) {
assert.Equal(t, "hellotcp", string(b))
conn.Close()
time.Sleep(50 * time.Millisecond)
log.Debug("checking")
assert.Zero(t, p.NumTCPConns(), "TCP client should be quickly purged from connection tracking")
assert.Zero(t, atomic.LoadInt64(&serverTCPConnections), "Server-side TCP connection should have been closed")
},
func(p Proxy, dev io.Closer) {
time.Sleep(10 * shortIdleTimeout)
log.Debug("checking")
assert.Zero(t, p.NumTCPOrigins(), "TCP origin should be purged after idle timeout")
assert.Zero(t, p.NumUDPConns(), "UDP conn should be purged after idle timeout")
})
}
// TestCloseCleanup is a lot like TestTCPandUDP but it relies on calling
// p.Close() for connection cleanup
func TestCloseCleanup(t *testing.T) {
doTest(
t,
1,
longIdleTimeout,
"10.0.2.2", "10.0.2.1",
func(p Proxy, uconn net.Conn, b []byte) {
assert.Equal(t, "helloudp", string(b))
},
func(p Proxy, conn net.Conn, b []byte) {
assert.Equal(t, "hellotcp", string(b))
},
func(p Proxy, dev io.Closer) {
time.Sleep(2 * shortIdleTimeout)
// assert.Equal(t, 1, p.NumTCPOrigins(), "TCP origin should not be purged before idle timeout")
assert.True(t, p.NumTCPConns() > 0, "TCP client should not be purged before idle timeout")
assert.True(t, p.NumUDPConns() > 0, "UDP conns should not be purged before idle timeout")
log.Debug("Closing device")
err := dev.Close()
if assert.NoError(t, err) {
log.Debug("Closing proxy")
err = p.Close()
if assert.NoError(t, err) {
time.Sleep(1 * time.Second)
log.Debug("Checking")
assert.Zero(t, p.NumTCPOrigins(), "TCP origin should be purged after close")
assert.Zero(t, p.NumTCPConns(), "TCP client should be purged after close")
assert.Zero(t, p.NumUDPConns(), "UDP conns should be purged after close")
log.Debug("Done checking")
}
}
})
}
func doTest(t *testing.T, loops int, idleTimeout time.Duration, addr string, gw string, afterUDP func(Proxy, net.Conn, []byte), afterTCP func(Proxy, net.Conn, []byte), finish func(Proxy, io.Closer)) {
var wg sync.WaitGroup
defer func() {
wg.Wait()
buf := make([]byte, 1<<20)
stacklen := runtime.Stack(buf, true)
goroutines := string(buf[:stacklen])
assert.NotContains(t, goroutines, "tcp.(*endpoint).Listen", "tcp listeners should have stopped")
assert.NotContains(t, goroutines, "echoReplier", "all echo repliers should have stopped")
assert.NotContains(t, goroutines, "copyTo", "all copyTo goroutines should have stopped")
assert.NotContains(t, goroutines, "copyFrom", "all copyFrom goroutines should have stopped")
}()
atomic.StoreInt64(&serverTCPConnections, 0)
ip := "127.0.0.1"
dev, err := TUNDevice("", addr, gw, "255.255.255.0", 1500)
if err != nil {
if strings.HasSuffix(err.Error(), "operation not permitted") {
t.Log("This test requires root access. Compile, then run with root privileges. See the README for more details.")
}
t.Fatal(err)
}
defer dev.Close()
d := &net.Dialer{}
p, err := New(&Opts{
IdleTimeout: idleTimeout,
StatsInterval: 1 * time.Second,
DialTCP: func(ctx context.Context, network, addr string) (net.Conn, error) {
// Send everything to local echo server
_, port, _ := net.SplitHostPort(addr)
return d.DialContext(ctx, network, ip+":"+port)
},
DialUDP: func(ctx context.Context, network, addr string) (net.Conn, error) {
// Send everything to local echo server
_, port, _ := net.SplitHostPort(addr)
return net.Dial(network, ip+":"+port)
},
})
if !assert.NoError(t, err) {
return
}
defer p.Close()
wg.Add(1)
go func() {
if err := p.Serve(context.Background()); err != nil {
log.Error(err)
}
wg.Done()
}()
closeCh := make(chan interface{})
echoAddr := tcpEcho(t, closeCh, ip)
udpEcho(t, closeCh, echoAddr)
// point at TUN device rather than echo server directly
_, port, _ := net.SplitHostPort(echoAddr)
echoAddr = gw + ":" + port
_, tcpConnCount, err := fdcount.Matching("TCP")
if !assert.NoError(t, err, "unable to get initial TCP socket count") {
return
}
_, udpConnCount, err := fdcount.Matching("UDP")
if !assert.NoError(t, err, "unable to get initial UDP socket count") {
return
}
for i := 0; i < loops; i++ {
log.Debugf("Loop %d", i)
b := make([]byte, 8)
log.Debugf("UDP dialing echo server at: %v", echoAddr)
uconn, err := net.Dial("udp", echoAddr)
if !assert.NoError(t, err, "Unable to get UDP connection to TUN device") {
return
}
defer uconn.Close()
_, err = uconn.Write([]byte("helloudp"))
if !assert.NoError(t, err) {
return
}
uconn.SetDeadline(time.Now().Add(250 * time.Millisecond))
_, err = io.ReadFull(uconn, b)
if !assert.NoError(t, err) {
return
}
afterUDP(p, uconn, b)
log.Debugf("TCP dialing echo server at: %v", echoAddr)
conn, err := net.DialTimeout("tcp4", echoAddr, 5*time.Second)
if !assert.NoError(t, err) {
return
}
defer conn.Close()
_, err = conn.Write([]byte("hellotcp"))
if !assert.NoError(t, err) {
return
}
_, err = io.ReadFull(conn, b)
if !assert.NoError(t, err) {
return
}
afterTCP(p, conn, b)
finish(p, dev)
}
close(closeCh)
tcpConnCount.AssertDelta(0)
udpConnCount.AssertDelta(0)
}
func tcpEcho(t *testing.T, closeCh <-chan interface{}, ip string) string {
l, err := net.Listen("tcp", ip+":0")
if err != nil {
t.Fatal(err)
}
go func() {
<-closeCh
l.Close()
}()
go func() {
for {
conn, err := l.Accept()
if err != nil {
return
}
go func() {
log.Debug("Copying TCP")
atomic.AddInt64(&serverTCPConnections, 1)
n, err := io.Copy(conn, conn)
log.Debugf("Finished copying TCP: %d: %v", n, err)
atomic.AddInt64(&serverTCPConnections, -1)
}()
}
}()
return l.Addr().String()
}
func udpEcho(t *testing.T, closeCh <-chan interface{}, echoAddr string) {
conn, err := net.ListenPacket("udp", echoAddr)
if err != nil {
t.Fatal(err)
}
go func() {
<-closeCh
conn.Close()
}()
go func() {
b := make([]byte, 20480)
for {
n, addr, err := conn.ReadFrom(b)
if err != nil {
return
}
log.Debugf("Got UDP packet! Addr: %v", addr)
conn.WriteTo(b[:n], addr)
}
}()
}