-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathflow.go
306 lines (256 loc) · 8.4 KB
/
flow.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
package conntrack
import (
"fmt"
"net/netip"
"github.com/mdlayher/netlink"
"github.com/ti-mo/netfilter"
)
// Flow represents a snapshot of a Conntrack connection.
type Flow struct {
ID uint32
Timeout uint32
Timestamp Timestamp
Status Status
ProtoInfo ProtoInfo
Helper Helper
Zone uint16
CountersOrig, CountersReply Counter
SecurityContext Security
TupleOrig, TupleReply, TupleMaster Tuple
SeqAdjOrig, SeqAdjReply SequenceAdjust
Labels, LabelsMask []byte
Mark, Use uint32
SynProxy SynProxy
}
// NewFlow returns a new Flow object with the minimum necessary attributes to
// create a Conntrack entry. Writes values into the Status, Timeout, TupleOrig
// and TupleReply fields of the Flow.
//
// proto is the layer 4 protocol number of the connection. status is a
// StatusFlag value, or an ORed combination thereof. srcAddr and dstAddr are the
// source and destination addresses. srcPort and dstPort are the source and
// destination ports. timeout is the non-zero time-to-live of a connection in
// seconds.
func NewFlow(proto uint8, status StatusFlag, srcAddr, destAddr netip.Addr,
srcPort, destPort uint16, timeout, mark uint32) Flow {
var f Flow
f.Status.Value = status
f.Timeout = timeout
f.Mark = mark
f.TupleOrig.IP.SourceAddress = srcAddr
f.TupleOrig.IP.DestinationAddress = destAddr
f.TupleOrig.Proto.SourcePort = srcPort
f.TupleOrig.Proto.DestinationPort = destPort
f.TupleOrig.Proto.Protocol = proto
// Set up TupleReply with source and destination inverted
f.TupleReply.IP.SourceAddress = destAddr
f.TupleReply.IP.DestinationAddress = srcAddr
f.TupleReply.Proto.SourcePort = destPort
f.TupleReply.Proto.DestinationPort = srcPort
f.TupleReply.Proto.Protocol = proto
return f
}
// unmarshal unmarshals netlink attributes into a Flow.
func (f *Flow) unmarshal(ad *netlink.AttributeDecoder) error {
for ad.Next() {
// Attribute has nested flag set, decode it and its children.
if err := f.unmarshalNested(ad); err != nil {
return err
}
switch attributeType(ad.Type()) {
// CTA_TIMEOUT is the time until the Conntrack entry is automatically destroyed.
case ctaTimeout:
f.Timeout = ad.Uint32()
// CTA_ID is the tuple hash value generated by the kernel. It can be relied on for flow identification.
case ctaID:
f.ID = ad.Uint32()
// CTA_USE is the flow's kernel-internal refcount.
case ctaUse:
f.Use = ad.Uint32()
// CTA_MARK is the connection's connmark
case ctaMark:
f.Mark = ad.Uint32()
// CTA_ZONE describes the Conntrack zone the flow is placed in. This can be combined with a CTA_TUPLE_ZONE
// to specify which zone an event originates from.
case ctaZone:
f.Zone = ad.Uint16()
// CTA_LABELS is a binary bitfield attached to a connection that is sent in
// events when changed, as well as in response to dump queries.
case ctaLabels:
f.Labels = ad.Bytes()
// CTA_LABELS_MASK is never sent by the kernel, but it can be used
// in set / update queries to mask label operations on the kernel state table.
// it needs to be exactly as wide as the CTA_LABELS field it intends to mask.
case ctaLabelsMask:
f.LabelsMask = ad.Bytes()
// CTA_STATUS is a bitfield of the state of the connection
// (eg. if packets are seen in both directions, etc.)
case ctaStatus:
f.Status.Value = StatusFlag(ad.Uint32())
}
}
return ad.Err()
}
// unmarshalNested unmarshals nested netlink attributes. Returns errNotNested if
// a nested attribute was recognized but its nested flag was not set.
func (f *Flow) unmarshalNested(ad *netlink.AttributeDecoder) error {
var fn func(nad *netlink.AttributeDecoder) error
t := attributeType(ad.Type())
switch t {
// CTA_TUPLE_* attributes are nested and contain source and destination values for:
// - the IPv4/IPv6 addresses involved
// - ports used in the connection
// - (optional) the Conntrack Zone of the originating/replying side of the flow
case ctaTupleOrig:
fn = f.TupleOrig.unmarshal
case ctaTupleReply:
fn = f.TupleReply.unmarshal
case ctaTupleMaster:
fn = f.TupleMaster.unmarshal
// CTA_PROTOINFO is sent for TCP, DCCP and SCTP protocols only. It conveys extra metadata
// about the state flags seen on the wire. Update events are sent when these change.
case ctaProtoInfo:
fn = f.ProtoInfo.unmarshal
case ctaHelp:
fn = f.Helper.unmarshal
// CTA_COUNTERS_* attributes are nested and contain byte and packet counters for flows in either direction.
case ctaCountersOrig:
fn = f.CountersOrig.unmarshal
case ctaCountersReply:
f.CountersReply.Direction = true
fn = f.CountersReply.unmarshal
// CTA_SECCTX is the SELinux security context of a Conntrack entry.
case ctaSecCtx:
fn = f.SecurityContext.unmarshal
// CTA_TIMESTAMP is a nested attribute that describes the start and end timestamp of a flow.
// It is sent by the kernel with dumps and DESTROY events.
case ctaTimestamp:
fn = f.Timestamp.unmarshal
// CTA_SEQADJ_* is generalized TCP window adjustment metadata. It is not (yet) emitted in Conntrack events.
// The reason for its introduction is outlined in https://lwn.net/Articles/563151.
// Patch set is at http://www.spinics.net/lists/netdev/msg245785.html.
case ctaSeqAdjOrig:
fn = f.SeqAdjOrig.unmarshal
case ctaSeqAdjReply:
f.SeqAdjReply.Direction = true
fn = f.SeqAdjReply.unmarshal
// CTA_SYNPROXY are the connection's SYN proxy parameters
case ctaSynProxy:
fn = f.SynProxy.unmarshal
default:
// No nested attributes matched, nothing to do.
return nil
}
// Found nested attribute, but missing nested flag.
if !nestedFlag(ad.TypeFlags()) {
return fmt.Errorf("attribute %v: %w", t, errNotNested)
}
ad.Nested(fn)
if err := ad.Err(); err != nil {
return fmt.Errorf("unmarshal %s: %w", t, err)
}
return nil
}
// marshal marshals a Flow object into a list of netfilter.Attributes.
func (f Flow) marshal() ([]netfilter.Attribute, error) {
// Flow updates need one of TupleOrig or TupleReply,
// so we enforce having either of those.
if !f.TupleOrig.filled() && !f.TupleReply.filled() {
return nil, errNeedTuples
}
attrs := make([]netfilter.Attribute, 0, 14)
if f.TupleOrig.filled() {
to, err := f.TupleOrig.marshal(uint16(ctaTupleOrig))
if err != nil {
return nil, err
}
attrs = append(attrs, to)
}
if f.TupleReply.filled() {
tr, err := f.TupleReply.marshal(uint16(ctaTupleReply))
if err != nil {
return nil, err
}
attrs = append(attrs, tr)
}
// Optional attributes appended to the list when filled
if f.Timeout != 0 {
a := netfilter.Attribute{Type: uint16(ctaTimeout)}
a.PutUint32(f.Timeout)
attrs = append(attrs, a)
}
if f.Status.Value != 0 {
attrs = append(attrs, f.Status.marshal())
}
if f.Mark != 0 {
a := netfilter.Attribute{Type: uint16(ctaMark)}
a.PutUint32(f.Mark)
attrs = append(attrs, a)
}
if f.Zone != 0 {
a := netfilter.Attribute{Type: uint16(ctaZone)}
a.PutUint16(f.Zone)
attrs = append(attrs, a)
}
if f.ProtoInfo.filled() {
attrs = append(attrs, f.ProtoInfo.marshal())
}
if f.Helper.filled() {
attrs = append(attrs, f.Helper.marshal())
}
if f.TupleMaster.filled() {
tm, err := f.TupleMaster.marshal(uint16(ctaTupleMaster))
if err != nil {
return nil, err
}
attrs = append(attrs, tm)
}
if f.SeqAdjOrig.filled() {
attrs = append(attrs, f.SeqAdjOrig.marshal(false))
}
if f.SeqAdjReply.filled() {
attrs = append(attrs, f.SeqAdjReply.marshal(true))
}
if f.SynProxy.filled() {
attrs = append(attrs, f.SynProxy.marshal())
}
if len(f.Labels) > 0 {
a := netfilter.Attribute{Type: uint16(ctaLabels)}
a.Data = f.Labels
attrs = append(attrs, a)
}
if len(f.LabelsMask) > 0 {
a := netfilter.Attribute{Type: uint16(ctaLabelsMask)}
a.Data = f.LabelsMask
attrs = append(attrs, a)
}
return attrs, nil
}
// unmarshalFlow unmarshals a Flow from a netlink.Message.
// The Message must contain valid attributes.
func unmarshalFlow(nlm netlink.Message) (Flow, error) {
var f Flow
_, ad, err := netfilter.DecodeNetlink(nlm)
if err != nil {
return f, err
}
err = f.unmarshal(ad)
if err != nil {
return f, err
}
return f, nil
}
// unmarshalFlows unmarshals a list of flows from a list of Netlink messages.
// This method can be used to parse the result of a dump or get query.
func unmarshalFlows(nlm []netlink.Message) ([]Flow, error) {
// Pre-allocate to avoid re-allocating output slice on every op
out := make([]Flow, 0, len(nlm))
for i := 0; i < len(nlm); i++ {
f, err := unmarshalFlow(nlm[i])
if err != nil {
return nil, err
}
out = append(out, f)
}
return out, nil
}