forked from ti-mo/conntrack
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconn_test.go
494 lines (403 loc) · 11.2 KB
/
conn_test.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
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
package conntrack_test
import (
"encoding/binary"
"fmt"
"log"
"net"
"net/netip"
"testing"
"time"
"github.com/mdlayher/netlink"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/ti-mo/conntrack"
"github.com/ti-mo/netfilter"
)
func TestConnDialError(t *testing.T) {
// Attempt to open a Netlink socket into a netns that is highly unlikely
// to exist, so we can catch an error from Dial.
_, err := conntrack.Dial(&netlink.Config{NetNS: 1337})
assert.EqualError(t, err, "setns: bad file descriptor")
}
func TestConnBufferSizes(t *testing.T) {
c, err := conntrack.Dial(nil)
require.NoError(t, err, "dialing conn")
assert.NoError(t, c.SetReadBuffer(256))
assert.NoError(t, c.SetWriteBuffer(256))
require.NoError(t, c.Close(), "closing conn")
}
func ExampleConn_createUpdateFlow() {
// Open a Conntrack connection.
c, err := conntrack.Dial(nil)
if err != nil {
log.Fatal(err)
}
// Set up a new Flow object using a given set of attributes.
f := conntrack.NewFlow(
17, 0,
net.ParseIP("2a00:1450:400e:804::200e"),
net.ParseIP("2a00:1450:400e:804::200f"),
1234, 80, 120, 0,
)
// Send the Flow to the kernel.
err = c.Create(f)
if err != nil {
log.Fatal(err)
}
f.Timeout = 240
// Update the Flow's timeout to 240 seconds.
err = c.Update(f)
if err != nil {
log.Fatal(err)
}
// Query the kernel based on the Flow's source/destination tuples.
// Returns a new Flow object with its connection ID assigned by the kernel.
qf, err := c.Get(f)
if err != nil {
log.Fatal(err)
}
// Print the result. The Flow has a timeout greater than 120 seconds.
log.Print(qf)
}
func ExampleConn_dumpFilter() {
// Open a Conntrack connection.
c, err := conntrack.Dial(nil)
if err != nil {
log.Fatal(err)
}
f1 := conntrack.NewFlow(
6, 0, net.IPv4(1, 2, 3, 4), net.IPv4(5, 6, 7, 8),
1234, 80, 120, 0x00ff, // Set a connection mark
)
f2 := conntrack.NewFlow(
17, 0, net.ParseIP("2a00:1450:400e:804::200e"), net.ParseIP("2a00:1450:400e:804::200f"),
1234, 80, 120, 0xff00, // Set a connection mark
)
_ = c.Create(f1)
_ = c.Create(f2)
// Dump all records in the Conntrack table that match the filter's mark/mask.
df, err := c.DumpFilter(conntrack.Filter{Mark: 0xff00, Mask: 0xff00}, nil)
if err != nil {
log.Fatal(err)
}
// Print the result. Only f2 is displayed.
log.Print(df)
}
func ExampleConn_flush() {
// Open a Conntrack connection.
c, err := conntrack.Dial(nil)
if err != nil {
log.Fatal(err)
}
// Evict all entries from the conntrack table in the current network namespace.
err = c.Flush()
if err != nil {
log.Fatal(err)
}
}
func ExampleConn_flushFilter() {
// Open a Conntrack connection.
c, err := conntrack.Dial(nil)
if err != nil {
log.Fatal(err)
}
f1 := conntrack.NewFlow(
6, 0, net.IPv4(1, 2, 3, 4), net.IPv4(5, 6, 7, 8),
1234, 80, 120, 0x00ff, // Set a connection mark
)
f2 := conntrack.NewFlow(
17, 0, net.ParseIP("2a00:1450:400e:804::200e"), net.ParseIP("2a00:1450:400e:804::200f"),
1234, 80, 120, 0xff00, // Set a connection mark
)
_ = c.Create(f1)
_ = c.Create(f2)
// Flush only the second flow matching the filter's mark/mask.
err = c.FlushFilter(conntrack.Filter{Mark: 0xff00, Mask: 0xff00})
if err != nil {
log.Fatal(err)
}
// Getting f1 succeeds.
_, err = c.Get(f1)
if err != nil {
log.Fatal(err)
}
// Getting f2 will fail, since it was flushed.
_, err = c.Get(f2)
if err != nil {
log.Println("Flow f2 missing, as expected", err)
}
}
func ExampleConn_delete() {
// Open a Conntrack connection.
c, err := conntrack.Dial(nil)
if err != nil {
log.Fatal(err)
}
f := conntrack.NewFlow(
6, 0, net.IPv4(1, 2, 3, 4), net.IPv4(5, 6, 7, 8),
1234, 80, 120, 0,
)
// Create the Flow, will return err if unsuccessful.
err = c.Create(f)
if err != nil {
log.Fatal(err)
}
// Delete the Flow based on its IP/port tuple, will return err if unsuccessful.
err = c.Delete(f)
if err != nil {
log.Fatal(err)
}
}
func ExampleConn_listen() {
// Open a Conntrack connection.
c, err := conntrack.Dial(nil)
if err != nil {
log.Fatal(err)
}
// Make a buffered channel to receive event updates on.
evCh := make(chan conntrack.Event, 1024)
// Listen for all Conntrack and Conntrack-Expect events with 4 decoder goroutines.
// All errors caught in the decoders are passed on channel errCh.
errCh, err := c.Listen(evCh, 4, append(netfilter.GroupsCT, netfilter.GroupsCTExp...))
if err != nil {
log.Fatal(err)
}
// Listen to Conntrack events from all network namespaces on the system.
err = c.SetOption(netlink.ListenAllNSID, true)
if err != nil {
log.Fatal(err)
}
// Start a goroutine to print all incoming messages on the event channel.
go func() {
for {
fmt.Println(<-evCh)
}
}()
// Stop the program as soon as an error is caught in a decoder goroutine.
log.Print(<-errCh)
}
func TestLabel(t *testing.T) {
// Open a Conntrack connection.
c, err := conntrack.Dial(nil)
if err != nil {
log.Fatalf("1. %s", err)
}
// Dump all records in the Conntrack table that match the filter's mark/mask.
df, err := c.Dump(nil)
if err != nil {
log.Fatalf("2. %s", err)
}
var uf conntrack.Flow
var found bool
for i, f := range df {
if f.TupleOrig.Proto.Protocol == 6 &&
f.TupleOrig.Proto.DestinationPort == 22 {
uf = f
fmt.Printf("### 1. %d: flow:%+v \n", i, f)
found = true
break
}
}
if !found {
fmt.Printf("### 2. not selected flow \n")
}
fmt.Printf("### 2. selected flow:%+v \n", uf)
// get a single flow
// Set up a new Flow object using a given set of attributes.
src := uf.TupleOrig.IP.SourceAddress.String()
dst := uf.TupleOrig.IP.DestinationAddress.String()
mark := uint32(1111)
timestamp := uint32(time.Now().Unix())
fmt.Printf("%d \n", timestamp)
f := conntrack.NewFlow(
uf.TupleOrig.Proto.Protocol,
0,
net.ParseIP(src),
net.ParseIP(dst),
uf.TupleOrig.Proto.SourcePort,
uf.TupleOrig.Proto.DestinationPort,
0,
mark)
f.TupleOrig.Proto.ICMPv4 = uf.TupleOrig.Proto.ICMPv4
f.TupleOrig.Proto.ICMPID = uf.TupleOrig.Proto.ICMPID
f.TupleOrig.Proto.ICMPType = uf.TupleOrig.Proto.ICMPType
//////////////////////
// update label
f.Labels = make([]byte, 16)
f.LabelsMask = make([]byte, 16)
binary.BigEndian.PutUint32(f.Labels[0:4], timestamp)
binary.BigEndian.PutUint32(f.LabelsMask[0:4], ^uint32(0))
if false {
f.Labels[10] = 99
f.Labels[11] = 88
f.LabelsMask[10] = 0xff
f.LabelsMask[11] = 0xff
}
fmt.Printf("### 3. Labels: %+v \n", f.Labels)
fmt.Printf("### 3. mask: %+v \n", f.LabelsMask)
// update
err = c.Update(f)
if err != nil {
log.Fatalf("3. %s", err)
}
////////////////////////
// Query the kernel based on the Flow's source/destination tuples.
// Returns a new Flow object with its connection ID assigned by the kernel.
qf, err := c.Get(f)
if err != nil {
log.Fatalf("4. %s", err)
}
fmt.Printf("### 3. get flow:%+v \n", qf)
}
func TestDump(t *testing.T) {
// Open a Conntrack connection.
c, err := conntrack.Dial(nil)
if err != nil {
log.Fatalf("1. %s", err)
}
// Dump all records in the Conntrack table that match the filter's mark/mask.
df, err := c.Dump(nil)
if err != nil {
log.Fatalf("2. %s", err)
}
var i int
for _, f := range df {
if f.TupleOrig.Proto.Protocol == 1 {
i++
fmt.Printf("### %d: flow:%+v \n", i, f)
}
}
}
func testDump1(t *testing.T) {
// Open a Conntrack connection.
log.Printf("start dump...\n")
c, err := conntrack.Dial(nil)
if err != nil {
log.Fatalf("1. %s", err)
}
dumpCt(c)
}
func dumpCt(c *conntrack.Conn) {
// Dump all records in the Conntrack table that match the filter's mark/mask.
df, err := c.Dump(nil)
if err != nil {
log.Fatalf("2. %s", err)
}
//log.Printf("length=%d \n", len(df))
for i, f := range df {
var proto *conntrack.ProtoInfoTCP
if f.ProtoInfo.TCP != nil &&
//f.TupleOrig.IP.DestinationAddress == netip.MustParseAddr("37.153.118.121") {
f.TupleOrig.IP.DestinationAddress == netip.MustParseAddr("1.1.1.100") {
proto = f.ProtoInfo.TCP
} else {
//fmt.Printf("### %d: flow:%+v \n", i, f)
continue
}
fmt.Printf("### %d: before: flow:%+v, tcp=%+v, flag=0x%x \n", i, f, *proto, proto.OriginalFlags)
proto.State = 2
proto.OriginalFlags |= 0x800
fmt.Printf("### %d: after: flow:%+v, tcp=%+v, flag=0x%x \n", i, f, *proto, proto.OriginalFlags)
// Update the Flow's timeout to 240 seconds.
err = c.Update(f)
if err != nil {
log.Fatal(err)
}
// Query the kernel based on the Flow's source/destination tuples.
// Returns a new Flow object with its connection ID assigned by the kernel.
qf, err := c.Get(f)
if err != nil {
log.Fatal(err)
}
proto = qf.ProtoInfo.TCP
fmt.Printf("### %d: tcp=%+v \n", i, *proto)
}
}
func updateCt(conn *conntrack.Conn, uf *conntrack.Flow) {
if uf.Status.Value&conntrack.StatusSeenReply != 0 {
// already syn_recved
return
} else if uf.ProtoInfo.TCP == nil {
// only tcp
return
} else if uf.Zone < uint16(100) || uint16(2100) < uf.Zone {
// not NLB Traffic
return
}
fmt.Printf("### 1.New event: %+v, Zone=%d, ProtoInfo=%+v \n",
uf, uf.Zone, uf.ProtoInfo.TCP)
f := conntrack.NewFlow(
uf.TupleOrig.Proto.Protocol,
uf.Status.Value|conntrack.StatusSeenReply|conntrack.StatusAssured,
uf.TupleOrig.IP.SourceAddress,
uf.TupleOrig.IP.DestinationAddress,
uf.TupleOrig.Proto.SourcePort,
uf.TupleOrig.Proto.DestinationPort,
0,
uf.Mark)
/*
f.TupleOrig.Proto.ICMPv4 = uf.TupleOrig.Proto.ICMPv4
f.TupleOrig.Proto.ICMPID = uf.TupleOrig.Proto.ICMPID
f.TupleOrig.Proto.ICMPType = uf.TupleOrig.Proto.ICMPType
*/
// 0x0800
// value & mask
var flags uint16 = 0x0808
f.Zone = uf.Zone
f.ProtoInfo.TCP = uf.ProtoInfo.TCP
f.ProtoInfo.TCP.State = 2
f.ProtoInfo.TCP.OriginalFlags |= flags
f.ProtoInfo.TCP.ReplyFlags |= flags
fmt.Printf("### 2.Update conntrack: %s:%d->%s:%d(%d), Zone(OvsPortId)=%d, ProtoInfo=%+v \n",
uf.TupleOrig.IP.SourceAddress,
uf.TupleOrig.Proto.SourcePort,
uf.TupleOrig.IP.DestinationAddress,
uf.TupleOrig.Proto.DestinationPort,
uf.TupleOrig.Proto.Protocol,
uf.Zone,
f.ProtoInfo.TCP)
err := conn.Update(f)
if err != nil {
fmt.Printf("failed to update: err=%s \n", err)
}
// Query the kernel based on the Flow's source/destination tuples.
// Returns a new Flow object with its connection ID assigned by the kernel.
qf, err := conn.Get(f)
if err != nil {
fmt.Printf("failed to get ct: err=%s \n", err)
}
fmt.Printf("### 3.Updated CT: %+v, ### ProtoInfo=%+v \n", qf, qf.ProtoInfo.TCP)
}
func testUpdate(t *testing.T) {
fmt.Printf("Start TestMain\n")
eventConn, err := conntrack.Dial(nil)
if err != nil {
fmt.Printf("unexpected error dialing namespaced connection: %s \n", err)
return
}
defer eventConn.Close()
// Open a Conntrack connection.
conn, err := conntrack.Dial(nil)
if err != nil {
log.Fatalf("failed to connect netlink: err=%s \n", err)
return
}
defer conn.Close()
// Subscribe to new/update conntrack events using a single worker.
ev := make(chan conntrack.Event)
errChan, err := eventConn.Listen(ev, 1, []netfilter.NetlinkGroup{
netfilter.GroupCTNew,
//netfilter.GroupCTUpdate,
//netfilter.GroupCTDestroy,
})
for {
select {
case <-errChan:
case e := <-ev:
if e.Type == conntrack.EventNew && e.Flow != nil {
//fmt.Printf("new event: %+v\n", e.Flow)
updateCt(conn, e.Flow)
}
}
}
}