forked from florianl/go-conntrack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conntrack.go
726 lines (626 loc) · 17.6 KB
/
conntrack.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
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
package conntrack
import (
"context"
"encoding/binary"
"fmt"
"log"
"time"
"unsafe"
"github.com/florianl/go-conntrack/internal/unix"
"github.com/mdlayher/netlink"
"github.com/mdlayher/netlink/nlenc"
)
// Supported conntrack subsystems
const (
// Conntrack is the default table containing a list of all tracked connections
Conntrack Table = unix.NFNL_SUBSYS_CTNETLINK
// Expected is a table containing information about related connections to existing ones
Expected Table = unix.NFNL_SUBSYS_CTNETLINK_EXP
)
const (
ipctnlMsgCtNew = iota
ipctnlMsgCtGet
ipctnlMsgCtDelete
ipctnlMsgCtGetCtrZero
ipctnlMsgCtGetStatsCPU
ipctnlMsgCtGetStats
ipctnlMsgCtGetDying
ipctnlMsgCtGetUnconfirmed
)
const (
ipctnlMsgExpNew = iota
ipctnlMsgExpGet
ipctnlMsgExpDelete
ipctnlMsgExpGetStatsCPU
)
const (
MaxNetlinkMessageSize = 16384
NetlinkHeaderSize = 16
)
// for detailes see https://github.com/tensorflow/tensorflow/blob/master/tensorflow/go/tensor.go#L488-L505
var nativeEndian binary.ByteOrder
func init() {
buf := [2]byte{}
*(*uint16)(unsafe.Pointer(&buf[0])) = uint16(0xABCD)
switch buf {
case [2]byte{0xCD, 0xAB}:
nativeEndian = binary.LittleEndian
case [2]byte{0xAB, 0xCD}:
nativeEndian = binary.BigEndian
default:
panic("Could not determine native endianness.")
}
}
// devNull satisfies io.Writer, in case *log.Logger is not provided
type devNull struct{}
func (devNull) Write(p []byte) (int, error) {
return 0, nil
}
// Close the connection to the conntrack subsystem.
func (nfct *Nfct) Close() error {
if nfct.errChan != nil {
close(nfct.errChan)
}
return nfct.Con.Close()
}
// Flush a conntrack subsystem
func (nfct *Nfct) Flush(t Table, f Family) error {
data := putExtraHeader(uint8(f), unix.NFNETLINK_V0, 0)
req := netlink.Message{
Header: netlink.Header{
Type: netlink.HeaderType(t << 8),
Flags: netlink.Request | netlink.Acknowledge,
},
Data: data,
}
if t == Conntrack {
req.Header.Type |= netlink.HeaderType(ipctnlMsgCtDelete)
} else if t == Expected {
req.Header.Type |= netlink.HeaderType(ipctnlMsgExpDelete)
} else {
return ErrUnknownCtTable
}
return nfct.execute(req)
}
// Dump a conntrack subsystem
func (nfct *Nfct) Dump(t Table, f Family) ([]Con, error) {
data := putExtraHeader(uint8(f), unix.NFNETLINK_V0, 0)
req := netlink.Message{
Header: netlink.Header{
Type: netlink.HeaderType(t << 8),
Flags: netlink.Request | netlink.Dump,
},
Data: data,
}
if t == Conntrack {
req.Header.Type |= netlink.HeaderType(ipctnlMsgCtGet)
} else if t == Expected {
req.Header.Type |= netlink.HeaderType(ipctnlMsgExpGet)
} else {
return nil, ErrUnknownCtTable
}
return nfct.query(req)
}
// Create a new entry in the conntrack subsystem with certain attributes
func (nfct *Nfct) Create(t Table, f Family, attributes Con) error {
query, err := nestAttributes(nfct.logger, &attributes)
if err != nil {
return err
}
data := putExtraHeader(uint8(f), unix.NFNETLINK_V0, unix.NFNL_SUBSYS_CTNETLINK)
data = append(data, query...)
req := netlink.Message{
Header: netlink.Header{
Type: netlink.HeaderType(t << 8),
Flags: netlink.Request | netlink.Acknowledge | netlink.Create | netlink.Excl,
},
Data: data,
}
if t == Conntrack {
req.Header.Type |= netlink.HeaderType(ipctnlMsgCtNew)
} else if t == Expected {
req.Header.Type |= netlink.HeaderType(ipctnlMsgExpNew)
} else {
return ErrUnknownCtTable
}
return nfct.execute(req)
}
// Query conntrack subsystem with certain attributes
func (nfct *Nfct) Query(t Table, f Family, filter FilterAttr) ([]Con, error) {
query, err := nestFilter(filter)
if err != nil {
return nil, err
}
data := putExtraHeader(uint8(f), unix.NFNETLINK_V0, unix.NFNL_SUBSYS_CTNETLINK)
data = append(data, query...)
req := netlink.Message{
Header: netlink.Header{
Type: netlink.HeaderType(t << 8),
Flags: netlink.Request | netlink.Dump,
},
Data: data,
}
if t == Conntrack {
req.Header.Type |= netlink.HeaderType(ipctnlMsgCtGet)
} else if t == Expected {
req.Header.Type |= netlink.HeaderType(ipctnlMsgExpGet)
} else {
return nil, ErrUnknownCtTable
}
return nfct.query(req)
}
// Get returns matching conntrack entries with certain attributes
func (nfct *Nfct) Get(t Table, f Family, match Con) ([]Con, error) {
if t != Conntrack {
return nil, ErrUnknownCtTable
}
query, err := nestAttributes(nfct.logger, &match)
if err != nil {
return []Con{}, err
}
data := putExtraHeader(uint8(f), unix.NFNETLINK_V0, unix.NFNL_SUBSYS_CTNETLINK)
data = append(data, query...)
req := netlink.Message{
Header: netlink.Header{
Type: netlink.HeaderType(t << 8),
Flags: netlink.Request | netlink.Acknowledge,
},
Data: data,
}
if t == Conntrack {
req.Header.Type |= netlink.HeaderType(ipctnlMsgCtGet)
} else if t == Expected {
req.Header.Type |= netlink.HeaderType(ipctnlMsgExpGet)
} else {
return []Con{}, ErrUnknownCtTable
}
return nfct.query(req)
}
// Update an existing conntrack entry
func (nfct *Nfct) Update(t Table, f Family, attributes Con) error {
if t != Conntrack {
return ErrUnknownCtTable
}
query, err := nestAttributes(nfct.logger, &attributes)
if err != nil {
return err
}
data := putExtraHeader(uint8(f), unix.NFNETLINK_V0, unix.NFNL_SUBSYS_CTNETLINK)
data = append(data, query...)
req := netlink.Message{
Header: netlink.Header{
Type: netlink.HeaderType(t << 8),
Flags: netlink.Request | netlink.Acknowledge,
},
Data: data,
}
if t == Conntrack {
req.Header.Type |= netlink.HeaderType(ipctnlMsgCtNew)
} else if t == Expected {
req.Header.Type |= netlink.HeaderType(ipctnlMsgExpNew)
} else {
return ErrUnknownCtTable
}
return nfct.execute(req)
}
// send a message with no reply
func (nfct *Nfct) UpdateSingle(t Table, f Family, attrs []*Con) error {
if t != Conntrack {
return ErrUnknownCtTable
}
for _, attr := range attrs {
query, err := nestAttributes(nfct.logger, attr)
if err != nil {
return err
}
data := putExtraHeader(uint8(f), unix.NFNETLINK_V0, unix.NFNL_SUBSYS_CTNETLINK)
data = append(data, query...)
req := netlink.Message{
Header: netlink.Header{
Type: netlink.HeaderType(t << 8),
//Flags: netlink.Request | netlink.Acknowledge,
// no reply
Flags: netlink.Request,
},
Data: data,
}
if t == Conntrack {
req.Header.Type |= netlink.HeaderType(ipctnlMsgCtNew)
} else if t == Expected {
req.Header.Type |= netlink.HeaderType(ipctnlMsgExpNew)
} else {
return ErrUnknownCtTable
}
_, e := nfct.Con.Send(req)
if e != nil {
return e
}
}
return nil
}
// send messages with no reply
func (nfct *Nfct) UpdateBatch(t Table, f Family, attrs []*Con) error {
if t != Conntrack {
return ErrUnknownCtTable
}
var err error
var dataLen, l int
msgs := make([]netlink.Message, 0)
for _, attr := range attrs {
query, err := nestAttributes(nfct.logger, attr)
if err != nil {
return err
}
data := putExtraHeader(uint8(f), unix.NFNETLINK_V0, unix.NFNL_SUBSYS_CTNETLINK)
data = append(data, query...)
req := netlink.Message{
Header: netlink.Header{
Type: netlink.HeaderType(t << 8),
//Flags: netlink.Request | netlink.Acknowledge,
// no reply
Flags: netlink.Request,
},
Data: data,
}
if t == Conntrack {
req.Header.Type |= netlink.HeaderType(ipctnlMsgCtNew)
} else if t == Expected {
req.Header.Type |= netlink.HeaderType(ipctnlMsgExpNew)
} else {
return ErrUnknownCtTable
}
l = len(data) + NetlinkHeaderSize
// exceed max size
if dataLen+l > MaxNetlinkMessageSize {
_, err = nfct.Con.SendMessages(msgs)
if err != nil {
return err
}
msgs = make([]netlink.Message, 0)
dataLen = 0
}
dataLen += l
msgs = append(msgs, req)
}
err = nil
if len(msgs) > 0 {
_, err = nfct.Con.SendMessages(msgs)
}
return err
}
// Delete elements from the conntrack subsystem with certain attributes
func (nfct *Nfct) Delete(t Table, f Family, filters Con) error {
query, err := nestAttributes(nfct.logger, &filters)
if err != nil {
return err
}
data := putExtraHeader(uint8(f), unix.NFNETLINK_V0, unix.NFNL_SUBSYS_CTNETLINK)
data = append(data, query...)
req := netlink.Message{
Header: netlink.Header{
Type: netlink.HeaderType(t << 8),
Flags: netlink.Request | netlink.Acknowledge,
},
Data: data,
}
if t == Conntrack {
req.Header.Type |= netlink.HeaderType(ipctnlMsgCtDelete)
} else if t == Expected {
req.Header.Type |= netlink.HeaderType(ipctnlMsgExpDelete)
} else {
return ErrUnknownCtTable
}
return nfct.execute(req)
}
// DumpCPUStats dumps per CPU statistics
func (nfct *Nfct) DumpCPUStats(t Table) ([]CPUStat, error) {
data := putExtraHeader(unix.AF_UNSPEC, unix.NFNETLINK_V0, 0)
req := netlink.Message{
Header: netlink.Header{
Type: netlink.HeaderType(t << 8),
Flags: netlink.Request | netlink.Dump,
},
Data: data,
}
if t == Conntrack {
req.Header.Type |= netlink.HeaderType(ipctnlMsgCtGetStatsCPU)
} else if t == Expected {
req.Header.Type |= netlink.HeaderType(ipctnlMsgExpGetStatsCPU)
} else {
return nil, ErrUnknownCtTable
}
return nfct.getCPUStats(req)
}
// ParseAttributes extracts all the attributes from the given data
func ParseAttributes(logger *log.Logger, data []byte) (Con, error) {
// At least 2 bytes are needed for the header check
if len(data) < 2 {
return Con{}, ErrDataLength
}
c := Con{}
err := extractAttributes(logger, &c, data)
return c, err
}
// HookFunc is a function, that receives events from a Netlinkgroup.
// Return something different than 0, to stop receiving messages.
type HookFunc func(c Con) int
// AttachErrChan creates and attaches an error channel to the Nfct object.
// If an unexpected error is received this error will be reported via this
// channel.
// A call of (*Nfct).Close() will also close this channel.
func (nfct *Nfct) AttachErrChan() <-chan error {
if nfct.errChan != nil {
return nfct.errChan
}
errChan := make(chan error)
nfct.errChan = errChan
return errChan
}
// Register your function to receive events from a Netlinkgroup. If an unexpected error
// is received it will stop from processing further events.
// If your function returns something different than 0, it will stop.
func (nfct *Nfct) Register(ctx context.Context, t Table, group NetlinkGroup, fn HookFunc) error {
return nfct.register(ctx, t, group, []ConnAttr{}, fn)
}
// RegisterFiltered registers your function to receive events from a Netlinkgroup and applies a filter.
// If an unexpected error is received it will stop from processing further events.
// If your function returns something different than 0, it will stop.
// ConnAttr of the same ConnAttrType will be linked by an OR operation.
// Otherwise, ConnAttr of different ConnAttrType will be connected by an AND operation for the filter.
func (nfct *Nfct) RegisterFiltered(ctx context.Context, t Table, group NetlinkGroup, filter []ConnAttr, fn HookFunc) error {
return nfct.register(ctx, t, group, filter, fn)
}
func (nfct *Nfct) register(ctx context.Context, t Table, groups NetlinkGroup, filter []ConnAttr, fn func(c Con) int) error {
if err := nfct.manageGroups(t, uint32(groups), true); err != nil {
return err
}
if err := nfct.attachFilter(t, filter); err != nil {
return err
}
go func() {
go func() {
// block until context is done
<-ctx.Done()
// Set the read deadline to a point in the past to interrupt
// possible blocking Receive() calls.
nfct.Con.SetReadDeadline(time.Now().Add(-1 * time.Second))
}()
defer func() {
if err := nfct.removeFilter(); err != nil {
nfct.logger.Printf("could not remove filter: %v", err)
}
if err := nfct.manageGroups(t, uint32(groups), false); err != nil {
nfct.logger.Printf("could not unsubscribe from group: %v", err)
}
}()
for {
select {
case <-ctx.Done():
return
default:
}
reply, err := nfct.Con.Receive()
if err != nil {
if opError, ok := err.(*netlink.OpError); ok {
if opError.Timeout() || opError.Temporary() {
continue
}
}
if nfct.errChan != nil {
nfct.errChan <- err
} else {
nfct.logger.Printf("receiving error: %v", err)
}
return
}
c := Con{}
for _, msg := range reply {
if err := parseConnectionMsg(nfct.logger, &c, msg, (int(msg.Header.Type)&0x300)>>8, int(msg.Header.Type)&0xF); err != nil {
nfct.logger.Printf("could not parse received message: %v", err)
continue
}
if ret := fn(c); ret != 0 {
return
}
}
}
}()
return nil
}
func (nfct *Nfct) manageGroups(t Table, groups uint32, join bool) error {
var manage func(group uint32) error
if groups == 0 {
nfct.logger.Println("will not join group 0")
return nil
}
manage = nfct.Con.LeaveGroup
if join {
manage = nfct.Con.JoinGroup
}
var mapping map[uint32]uint32
var nlGroups []NetlinkGroup
switch t {
case Conntrack:
mapping = map[uint32]uint32{
uint32(NetlinkCtNew): 1, // NFNLGRP_CONNTRACK_NEW
uint32(NetlinkCtUpdate): 2, // NFNLGRP_CONNTRACK_UPDATE
uint32(NetlinkCtDestroy): 3, // NFNLGRP_CONNTRACK_DESTROY
}
nlGroups = append(nlGroups, []NetlinkGroup{NetlinkCtNew, NetlinkCtUpdate, NetlinkCtDestroy}...)
case Expected:
mapping = map[uint32]uint32{
uint32(NetlinkCtExpectedNew): 4, // NFNLGRP_CONNTRACK_EXP_NEW
uint32(NetlinkCtExpectedUpdate): 5, // NFNLGRP_CONNTRACK_EXP_UPDATE
uint32(NetlinkCtExpectedDestroy): 6, // NFNLGRP_CONNTRACK_EXP_DESTROY
}
nlGroups = append(nlGroups, []NetlinkGroup{NetlinkCtExpectedNew, NetlinkCtExpectedUpdate, NetlinkCtExpectedDestroy}...)
default:
return ErrUnknownCtTable
}
for _, v := range nlGroups {
if groups&uint32(v) == uint32(v) {
if err := manage(mapping[groups&uint32(v)]); err != nil {
return err
}
}
}
return nil
}
// ErrMsg as defined in nlmsgerr
type ErrMsg struct {
Code int
Len uint32
Type uint16
Flags uint16
Seq uint32
Pid uint32
}
func unmarschalErrMsg(b []byte) (ErrMsg, error) {
var msg ErrMsg
msg.Code = int(nlenc.Uint32(b[0:4]))
msg.Len = nlenc.Uint32(b[4:8])
msg.Type = nlenc.Uint16(b[8:10])
msg.Flags = nlenc.Uint16(b[10:12])
msg.Seq = nlenc.Uint32(b[12:16])
msg.Pid = nlenc.Uint32(b[16:20])
return msg, nil
}
func (nfct *Nfct) execute(req netlink.Message) error {
if err := nfct.setWriteTimeout(); err != nil {
nfct.logger.Printf("could not set write timeout: %v", err)
}
reply, e := nfct.Con.Execute(req)
if e != nil {
return e
}
if e := netlink.Validate(req, reply); e != nil {
return e
}
for _, msg := range reply {
errMsg, err := unmarschalErrMsg(msg.Data)
if err != nil {
return err
}
if errMsg.Code != 0 {
return fmt.Errorf("%#v", errMsg)
}
}
return nil
}
func (nfct *Nfct) send(req netlink.Message) error {
if err := nfct.setWriteTimeout(); err != nil {
nfct.logger.Printf("could not set write timeout: %v", err)
}
verify, err := nfct.Con.Send(req)
if err != nil {
return err
}
if err := netlink.Validate(req, []netlink.Message{verify}); err != nil {
return err
}
return nil
}
func (nfct *Nfct) query(req netlink.Message) ([]Con, error) {
if err := nfct.send(req); err != nil {
return nil, err
}
reply, err := nfct.Con.Receive()
if err != nil {
return nil, err
}
var conn []Con
for _, msg := range reply {
c := Con{}
if err := parseConnectionMsg(nfct.logger, &c, msg, (int(req.Header.Type)&0x300)>>8, int(req.Header.Type)&0xF); err != nil {
return nil, err
}
// check if c is an empty struct
if (Con{}) == c {
continue
}
conn = append(conn, c)
}
return conn, nil
}
func (nfct *Nfct) getCPUStats(req netlink.Message) ([]CPUStat, error) {
var stats []CPUStat
if err := nfct.send(req); err != nil {
return nil, err
}
reply, err := nfct.Con.Receive()
if err != nil {
return nil, err
}
for _, msg := range reply {
if msg.Header.Type == netlink.Error {
errMsg, err := unmarschalErrMsg(msg.Data)
if err != nil {
nfct.logger.Printf("could not unmarshal ErrMsg: %v", err)
continue
}
if errMsg.Code == 0 {
continue
}
nfct.logger.Printf("unknown error: %v", errMsg)
continue
}
var stat CPUStat
offset := checkHeader(msg.Data[:2])
switch Table((int(req.Header.Type) & 0x300) >> 8) {
case Conntrack:
if err := extractCPUStats(&stat, nfct.logger, msg.Data[offset:]); err != nil {
nfct.logger.Printf("could not extract CPU stats: %v", err)
continue
}
case Expected:
if err := extractExpCPUStats(&stat, nfct.logger, msg.Data[offset:]); err != nil {
nfct.logger.Printf("could not extract CPU stats: %v", err)
continue
}
default:
return nil, fmt.Errorf("unknown table")
}
stats = append(stats, stat)
}
return stats, nil
}
// /include/uapi/linux/netfilter/nfnetlink.h:struct nfgenmsg{} res_id is Big Endian
func putExtraHeader(familiy, version uint8, resid uint16) []byte {
buf := make([]byte, 2)
binary.BigEndian.PutUint16(buf, resid)
return append([]byte{familiy, version}, buf...)
}
type extractFunc func(*log.Logger, *Con, []byte) error
func parseConnectionMsg(logger *log.Logger, c *Con, msg netlink.Message, reqTable, reqType int) error {
if msg.Header.Type == netlink.Error {
errMsg, err := unmarschalErrMsg(msg.Data)
if err != nil {
return err
}
if errMsg.Code == 0 {
return nil
}
return fmt.Errorf("%#v", errMsg)
}
var fnMap map[int]extractFunc
switch reqTable {
case unix.NFNL_SUBSYS_CTNETLINK:
fnMap = map[int]extractFunc{
ipctnlMsgCtNew: extractAttributes,
ipctnlMsgCtGet: extractAttributes,
ipctnlMsgCtDelete: extractAttributes,
}
case unix.NFNL_SUBSYS_CTNETLINK_EXP:
fnMap = map[int]extractFunc{
ipctnlMsgExpNew: extractExpectAttributes,
ipctnlMsgExpGet: extractExpectAttributes,
ipctnlMsgExpDelete: extractExpectAttributes,
}
default:
return fmt.Errorf("unknown conntrack table")
}
if fn, ok := fnMap[reqType]; ok {
return fn(logger, c, msg.Data)
}
return fmt.Errorf("unknown message type: 0x%02x", reqType)
}