Repository navigation
Expand file tree
/
Copy pathstack_mipstack_icmp_test.go
More file actions
355 lines (342 loc) · 10.9 KB
/
Copy pathstack_mipstack_icmp_test.go
File metadata and controls
355 lines (342 loc) · 10.9 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
package tun
import (
"bytes"
"errors"
"net/netip"
"sync"
"testing"
"time"
mips "github.com/metacubex/mipstack"
"github.com/metacubex/sing/common/buf"
"github.com/stretchr/testify/require"
)
type echoDestination struct {
writer DirectRouteContext
closed chan struct{}
once sync.Once
}
func (d *echoDestination) IsClosed() bool {
select {
case <-d.closed:
return true
default:
return false
}
}
func (d *echoDestination) Close() error { d.once.Do(func() { close(d.closed) }); return nil }
func (d *echoDestination) WritePacket(b *buf.Buffer) error {
defer b.Release()
source, target, protocol, _ := mipsPacketAddresses(b.Bytes())
offset := 20
kind := byte(0)
if source.Is6() {
offset = 40
kind = 129
}
payload := append([]byte(nil), b.Bytes()[offset:]...)
payload[0] = kind
payload[2], payload[3] = 0, 0
packet := transportPacket(target, source, protocol, payload)
go func() { _ = d.writer.WritePacket(packet) }()
return nil
}
func TestICMPDirectSessionLifecycle(t *testing.T) {
for _, mode := range []string{"expire", "closed"} {
t.Run(mode, func(t *testing.T) {
d := newMemoryTun()
created := make(chan *echoDestination, 4)
h := &testHandler{prepare: func(writer DirectRouteContext) (DirectRouteDestination, error) {
destination := &echoDestination{writer: writer, closed: make(chan struct{})}
t.Cleanup(func() { _ = destination.Close() })
created <- destination
return destination, nil
}}
testStack(t, d, h, func(o *StackOptions) { o.ICMPTimeout = time.Second })
source, target := netip.MustParseAddr("198.18.0.1"), netip.MustParseAddr("8.8.8.8")
echo := func(sequence byte) {
d.in <- transportPacket(source, target, 1, []byte{8, 0, 0, 0, 0, 1, 0, sequence})
packet := readPacket(t, d)
require.Equal(t, byte(0), packet[20])
require.Equal(t, sequence, packet[len(packet)-1])
}
echo(0)
destination := <-created
echo(1)
select {
case <-created:
t.Fatal("ICMP session not reused")
default:
}
if mode == "closed" {
require.NoError(t, destination.Close())
} else {
// DirectRouteMapping expires entries on lookup, in whole seconds.
time.Sleep(time.Second)
}
echo(2)
select {
case replacement := <-created:
require.NotSame(t, destination, replacement)
default:
t.Fatal("stale ICMP session reused")
}
require.True(t, destination.IsClosed())
})
}
}
func TestICMPPolicy(t *testing.T) {
for _, policy := range []string{"drop", "reset", "fallback"} {
policy := policy
t.Run(policy, func(t *testing.T) {
d := newMemoryTun()
called := make(chan struct{}, 1)
h := &testHandler{prepare: func(DirectRouteContext) (DirectRouteDestination, error) {
called <- struct{}{}
switch policy {
case "drop":
return nil, ErrDrop
case "reset":
return nil, ErrReset
default:
return nil, errors.New("dial failed")
}
}}
testStack(t, d, h, nil)
d.in <- transportPacket(netip.MustParseAddr("198.18.0.1"), netip.MustParseAddr("8.8.8.8"), 1, []byte{8, 0, 0, 0, 0, 1, 0, 1})
select {
case <-called:
case <-time.After(time.Second):
t.Fatal("policy not called")
}
if policy == "drop" {
select {
case p := <-d.out:
t.Fatalf("drop emitted %x", p)
case <-time.After(50 * time.Millisecond):
}
return
}
p := readPacket(t, d)
want := byte(0)
if policy == "reset" {
want = 3
}
if p[20] != want {
t.Fatalf("wrong ICMP policy response %x", p)
}
})
}
}
func TestICMPAdmissionLimitDoesNotBlockInput(t *testing.T) {
d := newMemoryTun()
started := make(chan struct{})
release := make(chan struct{})
var startOnce sync.Once
h := &testHandler{prepare: func(DirectRouteContext) (DirectRouteDestination, error) {
startOnce.Do(func() { close(started) })
<-release
return nil, nil
}}
s := testStack(t, d, h, nil)
source := netip.MustParseAddr("198.18.0.2")
target := netip.MustParseAddr("8.8.8.8")
packet := transportPacket(source, target, 1, []byte{8, 0, 0, 0, 0, 1, 0, 1})
// The first request blocks in PrepareConnection. Processing well beyond the
// admission limit proves packet handling keeps admitting and dropping
// packets instead of waiting for preparation.
s.processPackets([][]byte{packet}, 0)
select {
case <-started:
case <-time.After(time.Second):
t.Fatal("ICMP preparation did not start")
}
sent := make(chan struct{})
go func() {
for i := 0; i < 64; i++ {
s.processPackets([][]byte{packet}, 0)
}
close(sent)
}()
select {
case <-sent:
case <-time.After(time.Second):
t.Fatal("packet input blocked while ICMP preparation was stalled")
}
deadline := time.After(time.Second)
for len(s.icmpSlots) < cap(s.icmpSlots) {
select {
case <-deadline:
t.Fatalf("ICMP admission did not fill: %d/%d", len(s.icmpSlots), cap(s.icmpSlots))
default:
time.Sleep(time.Millisecond)
}
}
close(release)
// Exactly the admitted requests produce fallback echo replies. The rest
// were dropped at admission.
for i := 0; i < cap(s.icmpSlots); i++ {
readPacket(t, d)
}
select {
case extra := <-d.out:
t.Fatalf("excess ICMP request was not dropped: %x", extra)
case <-time.After(100 * time.Millisecond):
}
deadline = time.After(time.Second)
for len(s.icmpSlots) != 0 {
select {
case <-deadline:
t.Fatalf("ICMP admission slots did not drain: %d remaining", len(s.icmpSlots))
default:
time.Sleep(time.Millisecond)
}
}
// Once preparation has completed and the slots drain, a fresh request is
// admitted again.
s.processPackets([][]byte{packet}, 0)
readPacket(t, d)
}
func TestICMPInterfaceAddressBypassesPolicy(t *testing.T) {
for _, family := range []string{"ipv4", "ipv6"} {
t.Run(family, func(t *testing.T) {
source := netip.MustParseAddr("198.18.0.2")
local := netip.MustParseAddr("198.18.0.1")
remote := netip.MustParseAddr("8.8.8.8")
protocol, echo, reply, rejected, offset := byte(1), byte(8), byte(0), byte(3), 20
if family == "ipv6" {
source = netip.MustParseAddr("fd00::2")
local = netip.MustParseAddr("fd00::1")
remote = netip.MustParseAddr("2001:4860:4860::8888")
protocol, echo, reply, rejected, offset = 58, 128, 129, 1, 40
}
d := newMemoryTun()
called := make(chan struct{}, 2)
testStack(t, d, &testHandler{prepare: func(DirectRouteContext) (DirectRouteDestination, error) {
called <- struct{}{}
return nil, ErrReset
}}, nil)
payload := []byte{echo, 0, 0, 0, 0, 1, 0, 7, 42}
d.in <- transportPacket(source, local, protocol, payload)
response := readPacket(t, d)
src, dst, proto, ok := mipsPacketAddresses(response)
if !ok || src != local || dst != source || proto != protocol || response[offset] != reply || !bytes.Equal(response[offset+4:], payload[4:]) {
t.Fatalf("invalid interface echo reply: %x", response)
}
select {
case <-called:
t.Fatal("interface echo reached routing policy")
default:
}
d.in <- transportPacket(source, remote, protocol, payload)
response = readPacket(t, d)
if response[offset] != rejected {
t.Fatalf("remote echo bypassed reset policy: %x", response)
}
select {
case <-called:
default:
t.Fatal("remote echo did not reach routing policy")
}
})
}
}
func TestMipsICMPResetAdministrativelyProhibited(t *testing.T) {
for _, ipv6 := range []bool{false, true} {
t.Run(map[bool]string{false: "ipv4", true: "ipv6"}[ipv6], func(t *testing.T) {
d := newMemoryTun()
s := testStack(t, d, &testHandler{prepare: func(DirectRouteContext) (DirectRouteDestination, error) { return nil, ErrReset }}, nil)
source, target := netip.MustParseAddr("198.18.0.2"), netip.MustParseAddr("8.8.8.8")
protocol, kind, code, offset, limit := byte(1), byte(8), byte(13), 20, 576
if ipv6 {
source, target = netip.MustParseAddr("fd00::2"), netip.MustParseAddr("2001:4860::8888")
protocol, kind, code, offset, limit = 58, 128, 1, 40, 1280
}
payload := make([]byte, 1400)
payload[0] = kind
s.processPackets([][]byte{transportPacket(source, target, protocol, payload)}, 0)
response := readPacket(t, d)
require.LessOrEqual(t, len(response), limit)
require.Equal(t, code, response[offset+1])
if ipv6 {
require.Equal(t, byte(1), response[offset])
} else {
require.Equal(t, byte(3), response[offset])
require.Zero(t, mipsTestChecksum(response[offset:]))
}
})
}
}
func TestMipsICMPRepliesOnly(t *testing.T) {
for _, ipv6 := range []bool{false, true} {
for _, mode := range []string{"fallback", "error", "direct"} {
t.Run(map[bool]string{false: "ipv4", true: "ipv6"}[ipv6]+"/"+mode, func(t *testing.T) {
source, target := netip.MustParseAddr("198.18.0.2"), netip.MustParseAddr("8.8.8.8")
protocol, echo, replyType := byte(1), byte(8), byte(0)
if ipv6 {
source, target = netip.MustParseAddr("fd00::2"), netip.MustParseAddr("2001:4860::8888")
protocol, echo, replyType = 58, 128, 129
}
payload := []byte{echo, 0, 0, 0, 0x12, 0x34, 0x56, 0x78, 42, 43}
input := transportPacket(source, target, protocol, payload)
original := append([]byte(nil), input...)
replyPayload := append([]byte(nil), payload...)
replyPayload[0] = replyType
replyPacket := transportPacket(target, source, protocol, replyPayload)
d := newMemoryTun()
var writer *mipsICMPWriter
prepared := make(chan struct{})
burst := func() {
results := make(chan error, 4)
for i := 0; i < 4; i++ {
go func() { results <- writer.WritePacket(replyPacket) }()
}
for i := 0; i < 4; i++ {
require.NoError(t, <-results)
}
}
s := testStack(t, d, &testHandler{prepare: func(context DirectRouteContext) (DirectRouteDestination, error) {
writer = context.(*mipsICMPWriter)
close(prepared)
require.NotNil(t, writer.responder.IPPacket())
require.NotNil(t, writer.responder.Message().Payload)
if mode == "error" {
return nil, errors.New("dial failed")
}
if mode == "fallback" {
return nil, nil
}
// Replies may start before PrepareConnection returns.
burst()
destination := &echoDestination{writer: writer, closed: make(chan struct{})}
t.Cleanup(func() { _ = destination.Close() })
return destination, nil
}}, nil)
s.processPackets([][]byte{input}, 0)
select {
case <-prepared:
case <-time.After(time.Second):
t.Fatal("ICMP preparation not started")
}
require.Equal(t, original, input, "borrowed request was modified")
for i := range input {
input[i] = 0 // Simulate the delivery buffer being reused.
}
count := 1
if mode == "direct" {
burst() // The same writer remains usable after the callback.
count = 9
}
for i := 0; i < count; i++ {
packet, err := mips.ParseIPPacket(readPacket(t, d))
require.NoError(t, err)
message, err := packet.ICMPMessage() // Validates the family-specific checksum.
require.NoError(t, err)
require.Equal(t, target, message.Source)
require.Equal(t, source, message.Destination)
require.Equal(t, replyType, message.Type)
require.Equal(t, payload[4:], message.Body)
}
})
}
}
}