-
Notifications
You must be signed in to change notification settings - Fork 35
/
conn.go
571 lines (466 loc) · 14.6 KB
/
conn.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
package conntrack
import (
"fmt"
"sync"
"github.com/mdlayher/netlink"
"github.com/pkg/errors"
"github.com/ti-mo/netfilter"
"golang.org/x/sys/unix"
)
// Conn represents a Netlink connection to the Netfilter
// subsystem and implements all Conntrack actions.
type Conn struct {
conn *netfilter.Conn
workers sync.WaitGroup
}
// DumpOptions is passed as an option to `Dump`-related methods to modify their behaviour.
type DumpOptions struct {
// ZeroCounters resets all flows' counters to zero after the dump operation.
ZeroCounters bool
}
// Dial opens a new Netfilter Netlink connection and returns it
// wrapped in a Conn structure that implements the Conntrack API.
func Dial(config *netlink.Config) (*Conn, error) {
c, err := netfilter.Dial(config)
if err != nil {
return nil, err
}
return &Conn{conn: c}, nil
}
// Close closes a Conn.
//
// If any workers were started using [Conn.Listen], blocks until all have
// terminated.
func (c *Conn) Close() error {
if err := c.conn.Close(); err != nil {
return err
}
c.workers.Wait()
return nil
}
// SetOption enables or disables a netlink socket option for the Conn.
func (c *Conn) SetOption(option netlink.ConnOption, enable bool) error {
return c.conn.SetOption(option, enable)
}
// SetReadBuffer sets the size of the operating system's receive buffer
// associated with the Conn.
//
// The default read buffer size of a socket is configured with
// `sysctl net.core.rmem_default`. The maximum buffer size that can be set
// without elevated privileges is `sysctl net.core.rmem_max`.
func (c *Conn) SetReadBuffer(bytes int) error {
return c.conn.SetReadBuffer(bytes)
}
// SetWriteBuffer sets the size of the operating system's transmit buffer associated with the Conn.
//
// The default write buffer size of a socket is configured with
// `sysctl net.core.wmem_default`. The maximum buffer size that can be set
// without elevated privileges is `sysctl net.core.wmem_max`.
func (c *Conn) SetWriteBuffer(bytes int) error {
return c.conn.SetWriteBuffer(bytes)
}
// Listen joins the Netfilter connection to a multicast group and starts a given
// amount of Flow decoders from the Conn to the Flow channel. Returns an error channel
// the workers will return any errors on. Any error during Flow decoding is fatal and
// will halt the worker it occurs on. When numWorkers amount of errors have been received on
// the error channel, no more events will be produced on evChan.
//
// The Conn will be marked as having listeners active, which will prevent Listen from being
// called again. For listening on other groups, open another socket.
//
// evChan consumers need to be able to keep up with the Event producers. When the channel is full,
// messages will pile up in the Netlink socket's buffer, putting the socket at risk of being closed
// by the kernel when it eventually fills up.
//
// Closing the Conn makes all workers terminate silently.
func (c *Conn) Listen(evChan chan<- Event, numWorkers uint8, groups []netfilter.NetlinkGroup) (chan error, error) {
if numWorkers == 0 {
return nil, errNoWorkers
}
// Prevent Listen() from being called twice on the same Conn.
// This is checked again in JoinGroups(), but an early failure is preferred.
if c.conn.IsMulticast() {
return nil, errConnHasListeners
}
err := c.conn.JoinGroups(groups)
if err != nil {
return nil, err
}
errChan := make(chan error)
// Start numWorkers amount of worker goroutines
for id := uint8(0); id < numWorkers; id++ {
go c.eventWorker(id, evChan, errChan)
}
return errChan, nil
}
// eventWorker is a worker function that decodes Netlink messages into Events.
func (c *Conn) eventWorker(workerID uint8, evChan chan<- Event, errChan chan<- error) {
var err error
var recv []netlink.Message
var ev Event
c.workers.Add(1)
defer c.workers.Done()
for {
// Receive data from the Netlink socket.
recv, err = c.conn.Receive()
// If the Conn gets closed while blocked in Receive(), Go's runtime poller
// will return an src/internal/poll.ErrFileClosing. Since we cannot match
// the underlying error using errors.Is(), retrieve it from the netlink.OpErr.
var opErr *netlink.OpError
if errors.As(err, &opErr) {
if opErr.Err.Error() == "use of closed file" {
return
}
}
// Underlying fd has been closed, exit receive loop.
if errors.Is(err, unix.EBADF) {
return
}
if err != nil {
errChan <- fmt.Errorf("Receive() netlink error, closing worker %d: %w", workerID, err)
return
}
// Receive() always returns a list of Netlink Messages, but multicast messages should never be multi-part
if len(recv) > 1 {
errChan <- errMultipartEvent
return
}
// Decode event and send on channel
ev = *new(Event)
err := ev.Unmarshal(recv[0])
if err != nil {
errChan <- err
return
}
evChan <- ev
}
}
// Dump gets all Conntrack connections from the kernel in the form of a list
// of Flow objects.
func (c *Conn) Dump(opts *DumpOptions) ([]Flow, error) {
msgType := ctGet
if opts != nil && opts.ZeroCounters {
msgType = ctGetCtrZero
}
req, err := netfilter.MarshalNetlink(
netfilter.Header{
SubsystemID: netfilter.NFSubsysCTNetlink,
MessageType: netfilter.MessageType(msgType),
Family: netfilter.ProtoUnspec, // ProtoUnspec dumps both IPv4 and IPv6
Flags: netlink.Request | netlink.Dump,
},
nil)
if err != nil {
return nil, err
}
nlm, err := c.conn.Query(req)
if err != nil {
return nil, err
}
return unmarshalFlows(nlm)
}
// DumpFilter gets all Conntrack connections from the kernel in the form of a list
// of Flow objects, but only returns Flows matching the connmark specified in the Filter parameter.
func (c *Conn) DumpFilter(f Filter, opts *DumpOptions) ([]Flow, error) {
msgType := ctGet
if opts != nil && opts.ZeroCounters {
msgType = ctGetCtrZero
}
req, err := netfilter.MarshalNetlink(
netfilter.Header{
SubsystemID: netfilter.NFSubsysCTNetlink,
MessageType: netfilter.MessageType(msgType),
Family: netfilter.ProtoUnspec, // ProtoUnspec dumps both IPv4 and IPv6
Flags: netlink.Request | netlink.Dump,
},
f.marshal())
if err != nil {
return nil, err
}
nlm, err := c.conn.Query(req)
if err != nil {
return nil, err
}
return unmarshalFlows(nlm)
}
// DumpExpect gets all expected Conntrack expectations from the kernel in the form
// of a list of Expect objects.
func (c *Conn) DumpExpect() ([]Expect, error) {
req, err := netfilter.MarshalNetlink(
netfilter.Header{
SubsystemID: netfilter.NFSubsysCTNetlinkExp,
MessageType: netfilter.MessageType(ctGet),
Family: netfilter.ProtoUnspec, // ProtoUnspec dumps both IPv4 and IPv6
Flags: netlink.Request | netlink.Dump | netlink.Acknowledge,
},
nil)
if err != nil {
return nil, err
}
nlm, err := c.conn.Query(req)
if err != nil {
return nil, err
}
return unmarshalExpects(nlm)
}
// Flush empties the Conntrack table. Deletes all IPv4 and IPv6 entries.
func (c *Conn) Flush() error {
req, err := netfilter.MarshalNetlink(
netfilter.Header{
SubsystemID: netfilter.NFSubsysCTNetlink,
MessageType: netfilter.MessageType(ctDelete),
Family: netfilter.ProtoUnspec, // Family is ignored for flush
Flags: netlink.Request | netlink.Acknowledge,
},
nil)
if err != nil {
return err
}
_, err = c.conn.Query(req)
if err != nil {
return err
}
return nil
}
// FlushFilter deletes all entries from the Conntrack table matching a given Filter.
// Both IPv4 and IPv6 entries are considered for deletion.
func (c *Conn) FlushFilter(f Filter) error {
req, err := netfilter.MarshalNetlink(
netfilter.Header{
SubsystemID: netfilter.NFSubsysCTNetlink,
MessageType: netfilter.MessageType(ctDelete),
Family: netfilter.ProtoUnspec, // Family is ignored for flush
Flags: netlink.Request | netlink.Acknowledge,
},
f.marshal())
if err != nil {
return err
}
_, err = c.conn.Query(req)
if err != nil {
return err
}
return nil
}
// Create creates a new Conntrack entry.
func (c *Conn) Create(f Flow) error {
// Conntrack create requires timeout to be set.
if f.Timeout == 0 {
return errNeedTimeout
}
attrs, err := f.marshal()
if err != nil {
return err
}
pf := netfilter.ProtoIPv4
if f.TupleOrig.IP.IsIPv6() && f.TupleReply.IP.IsIPv6() {
pf = netfilter.ProtoIPv6
}
req, err := netfilter.MarshalNetlink(
netfilter.Header{
SubsystemID: netfilter.NFSubsysCTNetlink,
MessageType: netfilter.MessageType(ctNew),
Family: pf,
Flags: netlink.Request | netlink.Acknowledge |
netlink.Excl | netlink.Create,
}, attrs)
if err != nil {
return err
}
_, err = c.conn.Query(req)
if err != nil {
return err
}
return nil
}
// CreateExpect creates a new Conntrack Expect entry. Warning: Experimental, haven't
// got this to create an Expect correctly. Best-effort implementation based on kernel source.
func (c *Conn) CreateExpect(ex Expect) error {
attrs, err := ex.marshal()
if err != nil {
return err
}
pf := netfilter.ProtoIPv4
if ex.Tuple.IP.IsIPv6() && ex.Mask.IP.IsIPv6() && ex.TupleMaster.IP.IsIPv6() {
pf = netfilter.ProtoIPv6
}
req, err := netfilter.MarshalNetlink(
netfilter.Header{
SubsystemID: netfilter.NFSubsysCTNetlinkExp,
MessageType: netfilter.MessageType(ctExpNew),
Family: pf,
Flags: netlink.Request | netlink.Acknowledge |
netlink.Excl | netlink.Create,
}, attrs)
if err != nil {
return err
}
_, err = c.conn.Query(req)
if err != nil {
return err
}
return nil
}
// Get queries the conntrack table for a connection matching some attributes of a given Flow.
// The following attributes are considered in the query: TupleOrig or TupleReply, in that order,
// and Zone. One of TupleOrig or TupleReply is required for a successful query.
func (c *Conn) Get(f Flow) (Flow, error) {
var qf Flow
attrs, err := f.marshal()
if err != nil {
return qf, err
}
pf := netfilter.ProtoIPv4
if f.TupleOrig.IP.IsIPv6() && f.TupleReply.IP.IsIPv6() {
pf = netfilter.ProtoIPv6
}
req, err := netfilter.MarshalNetlink(
netfilter.Header{
SubsystemID: netfilter.NFSubsysCTNetlink,
MessageType: netfilter.MessageType(ctGet),
Family: pf,
Flags: netlink.Request | netlink.Acknowledge,
}, attrs)
if err != nil {
return qf, err
}
nlm, err := c.conn.Query(req)
if err != nil {
return qf, err
}
// Since this is not a dump (and ACK flag is set), the kernel sends a message containing
// the flow, followed by a Netlink (non-)error message. The error is already parsed by
// the netlink library, so we only read the first message containing the Flow.
qf, err = unmarshalFlow(nlm[0])
if err != nil {
return qf, err
}
return qf, nil
}
// Update updates a Conntrack entry. Only the following attributes are considered
// when sending a Flow update: Helper, Timeout, Status, ProtoInfo, Mark, SeqAdj (orig/reply),
// SynProxy, Labels. All other attributes are immutable past the point of creation.
// See the ctnetlink_change_conntrack() kernel function for exact behaviour.
func (c *Conn) Update(f Flow) error {
// Kernel rejects updates with a master tuple set
if f.TupleMaster.filled() {
return errUpdateMaster
}
attrs, err := f.marshal()
if err != nil {
return err
}
pf := netfilter.ProtoIPv4
if f.TupleOrig.IP.IsIPv6() && f.TupleReply.IP.IsIPv6() {
pf = netfilter.ProtoIPv6
}
req, err := netfilter.MarshalNetlink(
netfilter.Header{
SubsystemID: netfilter.NFSubsysCTNetlink,
MessageType: netfilter.MessageType(ctNew),
Family: pf,
Flags: netlink.Request | netlink.Acknowledge,
}, attrs)
if err != nil {
return err
}
_, err = c.conn.Query(req)
if err != nil {
return err
}
return nil
}
// Delete removes a Conntrack entry given a Flow. Flows are looked up in the conntrack table
// based on the original and reply tuple. When the Flow's ID field is filled, it must match the
// ID on the connection returned from the tuple lookup, or the delete will fail.
func (c *Conn) Delete(f Flow) error {
attrs, err := f.marshal()
if err != nil {
return err
}
// Default to IPv4, set netlink protocol family to IPv6 if orig/reply is IPv6.
pf := netfilter.ProtoIPv4
if f.TupleOrig.IP.IsIPv6() && f.TupleReply.IP.IsIPv6() {
pf = netfilter.ProtoIPv6
}
req, err := netfilter.MarshalNetlink(
netfilter.Header{
SubsystemID: netfilter.NFSubsysCTNetlink,
MessageType: netfilter.MessageType(ctDelete),
Family: pf,
Flags: netlink.Request | netlink.Acknowledge,
}, attrs)
if err != nil {
return err
}
_, err = c.conn.Query(req)
if err != nil {
return err
}
return nil
}
// Stats returns a list of Stats structures, one per CPU present in the machine.
// Each Stats structure contains performance counters of all Conntrack actions
// performed on that specific CPU.
func (c *Conn) Stats() ([]Stats, error) {
req, err := netfilter.MarshalNetlink(
netfilter.Header{
SubsystemID: netfilter.NFSubsysCTNetlink,
MessageType: netfilter.MessageType(ctGetStatsCPU),
Family: netfilter.ProtoUnspec,
Flags: netlink.Request | netlink.Dump,
}, nil)
if err != nil {
return nil, err
}
msgs, err := c.conn.Query(req)
if err != nil {
return nil, err
}
return unmarshalStats(msgs)
}
// StatsExpect returns a list of StatsExpect structures, one per CPU present in the machine.
// Each StatsExpect structure indicates how many Expect entries were initialized,
// created or deleted on each CPU.
func (c *Conn) StatsExpect() ([]StatsExpect, error) {
req, err := netfilter.MarshalNetlink(
netfilter.Header{
SubsystemID: netfilter.NFSubsysCTNetlinkExp,
MessageType: netfilter.MessageType(ctExpGetStatsCPU),
Family: netfilter.ProtoUnspec,
Flags: netlink.Request | netlink.Dump,
}, nil)
if err != nil {
return nil, err
}
msgs, err := c.conn.Query(req)
if err != nil {
return nil, err
}
return unmarshalStatsExpect(msgs)
}
// StatsGlobal queries Conntrack for an internal global counter that describes the total amount
// of Flow entries currently in the Conntrack table. Only the main Conntrack table has this
// fast query available. To get the amount of Expect entries, execute DumpExpect() and count
// the amount of entries returned.
//
// Starting from kernels 4.18 and higher, MaxEntries is returned, describing the maximum size
// of the Conntrack table.
func (c *Conn) StatsGlobal() (StatsGlobal, error) {
req, err := netfilter.MarshalNetlink(
netfilter.Header{
SubsystemID: netfilter.NFSubsysCTNetlink,
MessageType: netfilter.MessageType(ctGetStats),
Family: netfilter.ProtoUnspec,
Flags: netlink.Request | netlink.Dump | netlink.Acknowledge,
}, nil)
var sg StatsGlobal
if err != nil {
return sg, err
}
msgs, err := c.conn.Query(req)
if err != nil {
return sg, err
}
return unmarshalStatsGlobal(msgs[0])
}