/
net_capture.go
334 lines (279 loc) · 9.86 KB
/
net_capture.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
package ebpf
import (
"context"
"encoding/binary"
"fmt"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/aquasecurity/tracee/pkg/events"
"github.com/aquasecurity/tracee/pkg/logger"
"github.com/aquasecurity/tracee/types/trace"
)
//
// User chooses through config/cmdline how to capture pcap files:
//
// - single file
// - per process
// - per container
// - per command
//
// and might have more than 1 way enabled simultaneously.
//
const (
familyIpv4 int = 1 << iota
familyIpv6
)
func (t *Tracee) handleNetCaptureEvents(ctx context.Context) {
logger.Debugw("Starting handleNetCaptureEvents goroutine")
defer logger.Debugw("Stopped handleNetCaptureEvents goroutine")
var errChanList []<-chan error
// source pipeline stage (re-used from regular pipeline)
eventsChan, errChan := t.decodeEvents(ctx, t.netCapChannel)
errChanList = append(errChanList, errChan)
// process events stage (network capture only)
errChan = t.processNetCapEvents(ctx, eventsChan)
errChanList = append(errChanList, errChan)
// pipeline started, wait for completion.
if err := t.WaitForPipeline(errChanList...); err != nil {
logger.Errorw("Pipeline", "error", err)
}
}
func (t *Tracee) processNetCapEvents(ctx context.Context, in <-chan *trace.Event) <-chan error {
errc := make(chan error, 1)
go func() {
defer close(errc)
for {
select {
case event := <-in:
// TODO: Support captures pipeline in t.processEvent
err := t.normalizeEventCtxTimes(event)
if err != nil {
t.handleError(err)
t.eventsPool.Put(event)
continue
}
t.processNetCapEvent(event)
_ = t.stats.NetCapCount.Increment()
t.eventsPool.Put(event)
case lost := <-t.lostNetCapChannel:
if err := t.stats.LostNtCapCount.Increment(lost); err != nil {
logger.Errorw("Incrementing lost network events count", "error", err)
}
logger.Warnw(fmt.Sprintf("Lost %d network capture events", lost))
case <-ctx.Done():
return
}
}
}()
return errc
}
// processNetCapEvent processes network packets meant to be captured.
//
// TODO: usually networking parsing functions are big, still, this might need
// some refactoring to make it smaller (code reuse might not be a key for the
// refactor).
func (t *Tracee) processNetCapEvent(event *trace.Event) {
eventId := events.ID(event.EventID)
switch eventId {
case events.NetPacketCapture:
var (
ok bool
payloadLayer3 []byte
payloadLayer2 []byte
layerType gopacket.LayerType
)
// sanity checks
payloadArg := events.GetArg(event, "payload")
if payloadArg == nil {
logger.Debugw("Network capture: no payload packet")
return
}
if payloadLayer3, ok = payloadArg.Value.([]byte); !ok {
logger.Debugw("Network capture: non []byte argument")
return
}
payloadLayer3Size := len(payloadLayer3)
if payloadLayer3Size < 1 {
logger.Debugw("Network capture: empty payload")
return
}
// event retval encodes layer 3 protocol type
if event.ReturnValue&familyIpv4 == familyIpv4 {
layerType = layers.LayerTypeIPv4
} else if event.ReturnValue&familyIpv6 == familyIpv6 {
layerType = layers.LayerTypeIPv6
} else {
logger.Debugw("Unsupported layer3 protocol")
}
// make room for fake layer 2 header
layer2Slice := make([]byte, 4)
payloadLayer2 = append(layer2Slice[:], payloadLayer3...)
// parse packet
packet := gopacket.NewPacket(
payloadLayer2[4:payloadLayer3Size],
layerType,
gopacket.Default,
)
if packet == nil {
logger.Debugw("Could not parse packet")
return
}
// amount of bytes the TCP header has based on data offset field
tcpDoff := func(l4 gopacket.TransportLayer) uint32 {
var doff uint32
if v, ok := l4.(*layers.TCP); ok {
doff = 20 // TCP header default length is 20 bytes
if v.DataOffset > uint8(5) { // unless doff is set, then...
doff = uint32(v.DataOffset) * 4 // doff * 32bit words == tcp header length
}
}
return doff
}
// NOTES:
//
// 1) Fake Layer 2:
//
// Tracee captures L3 packets only, but pcap needs a L2 header, as it
// mixes IPv4 and IPv6 packets in the same pcap file.
//
// The easiest link type is "Null", which emulates a BSD loopback
// encapsulation (4-byte field differentiating IPv4 and IPv6 packets).
//
// So, from now on, instead of having the initial 32-bit as the "sizeof"
// (the event argument), it will become this "fake L2 header" as if it
// were the BSD loopback encapsulation header.
//
// 2) Fake IP header length Field:
//
// Tcpdump, when reading the generated pcap files, will complain about
// missing packet payload if the IP header says one length and the
// actual data in the payload is smaller (what happens when tracee
// pcap-snaplen option is not set to max). The code bellow changes IP
// length field to the length of the captured data.
//
captureLength := t.config.Capture.Net.CaptureLength // after last known header
// parse packet
layer3 := packet.NetworkLayer()
layer4 := packet.TransportLayer()
ipHeaderLength := uint32(0) // IP header length is dynamic
udpHeaderLength := uint32(8) // UDP header length is 8 bytes
tcpHeaderLength := uint32(0) // TCP header length is dynamic
// will calculate L4 protocol headers length value
ipHeaderLengthValue := uint32(0)
udpHeaderLengthValue := uint32(0)
switch v := layer3.(type) {
case (*layers.IPv4):
// Fake L2 header: IPv4 (BSD encap header spec)
binary.BigEndian.PutUint32(payloadLayer2, 2) // set value 2 to first 4 bytes (uint32)
// IP header depends on IHL flag (default: 5 * 4 = 20 bytes)
ipHeaderLength += uint32(v.IHL) * 4
ipHeaderLengthValue += ipHeaderLength
switch v.Protocol {
case layers.IPProtocolICMPv4:
// ICMP
break // always has "headers" only (payload = 0)
case layers.IPProtocolUDP:
// UDP
udpHeaderLengthValue += udpHeaderLength
ipHeaderLengthValue += udpHeaderLength
case layers.IPProtocolTCP:
// TCP
tcpHeaderLength = tcpDoff(layer4)
ipHeaderLengthValue += tcpHeaderLength
}
// add capture length (length to capture after last known proto header)
ipHeaderLengthValue += captureLength
udpHeaderLengthValue += captureLength
// capture length is bigger than the pkt payload: no need for mangling
if ipHeaderLengthValue != uint32(len(payloadLayer2[4:])) {
break
} // else: mangle the packet (below) due to capture length
// sanity check for max uint16 size in IP header length field
if ipHeaderLengthValue >= (1 << 16) {
ipHeaderLengthValue = (1 << 16) - 1
}
// change IPv4 total length field for the correct (new) packet size
binary.BigEndian.PutUint16(payloadLayer2[6:], uint16(ipHeaderLengthValue))
// no flags, frag offset OR checksum changes (tcpdump does not complain)
switch v.Protocol {
// TCP does not have a length field (uses checksum to verify)
// no checksum recalculation (tcpdump does not complain)
case layers.IPProtocolUDP:
// NOTE: tcpdump might complain when parsing UDP packets that
// are meant for a specific L7 protocol, like DNS, for
// example, if their port is the protocol port and user
// is only capturing "headers". That happens because it
// tries to parse the DNS header and, if it does not
// exist, it causes an error. To avoid that, one can run
// tcpdump -q -r ./file.pcap, so it does not try to parse
// upper layers in detail. That is the reason why the
// default pcap snaplen is 96b.
//
// change UDP header length field for the correct (new) size
binary.BigEndian.PutUint16(
payloadLayer2[4+ipHeaderLength+4:],
uint16(udpHeaderLengthValue),
)
}
case (*layers.IPv6):
// Fake L2 header: IPv6 (BSD encap header spec)
binary.BigEndian.PutUint32(payloadLayer2, 28) // set value 28 to first 4 bytes (uint32)
ipHeaderLength = uint32(40) // IPv6 does not have an IHL field
ipHeaderLengthValue += ipHeaderLength
switch v.NextHeader {
case layers.IPProtocolICMPv6:
// ICMPv6
break // always has "headers" only (payload = 0)
case layers.IPProtocolUDP:
// UDP
udpHeaderLengthValue += udpHeaderLength
ipHeaderLengthValue += udpHeaderLength
case layers.IPProtocolTCP:
// TCP
tcpHeaderLength = tcpDoff(layer4)
ipHeaderLengthValue += tcpHeaderLength
}
// add capture length (length to capture after last known proto header)
ipHeaderLengthValue += captureLength
udpHeaderLengthValue += captureLength
// capture length is bigger than the pkt payload: no need for mangling
if ipHeaderLengthValue != uint32(len(payloadLayer2[4:])) {
break
} // else: mangle the packet (below) due to capture length
// sanity check for max uint16 size in IP header length field
if ipHeaderLengthValue >= (1 << 16) {
ipHeaderLengthValue = (1 << 16) - 1
}
// change IPv6 payload length field for the correct (new) packet size
binary.BigEndian.PutUint16(payloadLayer2[12:], uint16(ipHeaderLengthValue))
// no flags, frag offset OR checksum changes (tcpdump does not complain)
switch v.NextHeader {
// TCP does not have a length field (uses checksum to verify)
// no checksum recalculation (tcpdump does not complain)
case layers.IPProtocolUDP:
// NOTE: same as IPv4 note
// change UDP header length field for the correct (new) size
binary.BigEndian.PutUint16(
payloadLayer2[4+ipHeaderLength+4:],
uint16(udpHeaderLengthValue),
)
}
default:
return
}
// This might be too much, but keep it here for now
// logger.Debugw(
// "capturing network",
// "command", event.ProcessName,
// "srcIP", srcIP,
// "dstIP", dstIP,
// )
// capture the packet to all enabled pcap files
err := t.netCapturePcap.Write(event, payloadLayer2)
if err != nil {
logger.Errorw("Could not write pcap data", "err", err)
}
default:
logger.Debugw("Network capture: wrong net capture event type")
}
}