forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp.go
363 lines (281 loc) · 7.57 KB
/
tcp.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
package main
import (
"fmt"
"strings"
"time"
"github.com/packetbeat/gopacket"
"github.com/packetbeat/gopacket/layers"
)
const TCP_STREAM_EXPIRY = 10 * 1e9
const TCP_STREAM_HASH_SIZE = 2 ^ 16
const TCP_MAX_DATA_IN_STREAM = 10 * 1e6
type CmdlineTuple struct {
Src, Dst []byte
}
const (
TcpDirectionReverse = 0
TcpDirectionOriginal = 1
)
type Packet struct {
ts time.Time
tuple IpPortTuple
payload []byte
}
type TcpStream struct {
id uint32
tuple *IpPortTuple
timer *time.Timer
protocol protocolType
lastSeq [2]uint32
httpData [2]*HttpStream
mysqlData [2]*MysqlStream
redisData [2]*RedisStream
pgsqlData [2]*PgsqlStream
thriftData [2]*ThriftStream
}
type Endpoint struct {
Ip string
Port uint16
Name string
Cmdline string
Proc string
}
var __id uint32 = 0
func GetId() uint32 {
__id += 1
return __id
}
// Config
type tomlProtocol struct {
Ports []int
Send_request bool
Send_response bool
}
var tcpStreamsMap = make(map[HashableIpPortTuple]*TcpStream, TCP_STREAM_HASH_SIZE)
var tcpPortMap map[uint16]protocolType
func decideProtocol(tuple *IpPortTuple) protocolType {
protocol, exists := tcpPortMap[tuple.Src_port]
if exists {
return protocol
}
protocol, exists = tcpPortMap[tuple.Dst_port]
if exists {
return protocol
}
return UnknownProtocol
}
func (stream *TcpStream) AddPacket(pkt *Packet, tcphdr *layers.TCP, original_dir uint8) {
// create/reset timer
if stream.timer != nil {
stream.timer.Stop()
}
stream.timer = time.AfterFunc(TCP_STREAM_EXPIRY, func() { stream.Expire() })
switch stream.protocol {
case HttpProtocol:
if len(pkt.payload) > 0 {
HttpMod.Parse(pkt, stream, original_dir)
}
if tcphdr.FIN {
HttpMod.ReceivedFin(stream, original_dir)
}
case MysqlProtocol:
if len(pkt.payload) > 0 {
ParseMysql(pkt, stream, original_dir)
}
case RedisProtocol:
if len(pkt.payload) > 0 {
ParseRedis(pkt, stream, original_dir)
}
case PgsqlProtocol:
if len(pkt.payload) > 0 {
ParsePgsql(pkt, stream, original_dir)
}
case ThriftProtocol:
if len(pkt.payload) > 0 {
ThriftMod.Parse(pkt, stream, original_dir)
}
if tcphdr.FIN {
ThriftMod.ReceivedFin(stream, original_dir)
}
}
}
func (stream *TcpStream) GapInStream(original_dir uint8) {
switch stream.protocol {
case PgsqlProtocol:
GapInPgsqlStream(stream, original_dir)
break
}
}
func (stream *TcpStream) Expire() {
DEBUG("mem", "Tcp stream expired")
// de-register from dict
delete(tcpStreamsMap, stream.tuple.raw)
// nullify to help the GC
stream.httpData = [2]*HttpStream{nil, nil}
stream.mysqlData = [2]*MysqlStream{nil, nil}
stream.redisData = [2]*RedisStream{nil, nil}
stream.pgsqlData = [2]*PgsqlStream{nil, nil}
}
func TcpSeqBefore(seq1 uint32, seq2 uint32) bool {
return int32(seq1-seq2) < 0
}
func TcpSeqBeforeEq(seq1 uint32, seq2 uint32) bool {
return int32(seq1-seq2) <= 0
}
func FollowTcp(tcphdr *layers.TCP, pkt *Packet) {
stream, exists := tcpStreamsMap[pkt.tuple.raw]
var original_dir uint8 = TcpDirectionOriginal
created := false
if !exists {
stream, exists = tcpStreamsMap[pkt.tuple.revRaw]
if !exists {
protocol := decideProtocol(&pkt.tuple)
if protocol == UnknownProtocol {
// don't follow
return
}
DEBUG("tcp", "Stream doesn't exists, creating new")
// create
stream = &TcpStream{id: GetId(), tuple: &pkt.tuple, protocol: protocol}
tcpStreamsMap[pkt.tuple.raw] = stream
created = true
} else {
original_dir = TcpDirectionReverse
}
}
tcp_start_seq := tcphdr.Seq
tcp_seq := tcp_start_seq + uint32(len(pkt.payload))
DEBUG("tcp", "pkt.start_seq=%v pkt.last_seq=%v stream.last_seq=%v (len=%d)",
tcp_start_seq, tcp_seq, stream.lastSeq[original_dir], len(pkt.payload))
if len(pkt.payload) > 0 &&
stream.lastSeq[original_dir] != 0 {
if TcpSeqBeforeEq(tcp_seq, stream.lastSeq[original_dir]) {
DEBUG("tcp", "Ignoring what looks like a retrasmitted segment. pkt.seq=%v len=%v stream.seq=%v",
tcphdr.Seq, len(pkt.payload), stream.lastSeq[original_dir])
return
}
if TcpSeqBefore(stream.lastSeq[original_dir], tcp_start_seq) {
DEBUG("tcp", "Gap in tcp stream. last_seq: %d, seq: %d", stream.lastSeq[original_dir], tcp_start_seq)
if !created {
stream.GapInStream(original_dir)
// drop stream
stream.Expire()
return
}
}
}
stream.lastSeq[original_dir] = tcp_seq
stream.AddPacket(pkt, tcphdr, original_dir)
}
func PrintTcpMap() {
fmt.Printf("Streams in memory:")
for _, stream := range tcpStreamsMap {
fmt.Printf(" %d", stream.id)
}
fmt.Printf("\n")
fmt.Printf("Streams dict: %s", tcpStreamsMap)
}
func configToPortsMap(config *tomlConfig) map[uint16]protocolType {
var res = map[uint16]protocolType{}
var proto protocolType
for proto = UnknownProtocol + 1; int(proto) < len(protocolNames); proto++ {
protoConfig, exists := config.Protocols[protocolNames[proto]]
if !exists {
// skip
continue
}
for _, port := range protoConfig.Ports {
res[uint16(port)] = proto
}
}
return res
}
func configToFilter(config *tomlConfig) string {
res := []string{}
for _, protoConfig := range config.Protocols {
for _, port := range protoConfig.Ports {
res = append(res, fmt.Sprintf("port %d", port))
}
}
return strings.Join(res, " or ")
}
func TcpInit() error {
tcpPortMap = configToPortsMap(&_Config)
return nil
}
type DecoderStruct struct {
Parser *gopacket.DecodingLayerParser
sll layers.LinuxSLL
lo layers.Loopback
eth layers.Ethernet
ip4 layers.IPv4
ip6 layers.IPv6
tcp layers.TCP
payload gopacket.Payload
decoded []gopacket.LayerType
}
func CreateDecoder(datalink layers.LinkType) (*DecoderStruct, error) {
var d DecoderStruct
DEBUG("pcapread", "Layer type: %s", datalink.String())
switch datalink {
case layers.LinkTypeLinuxSLL:
d.Parser = gopacket.NewDecodingLayerParser(
layers.LayerTypeLinuxSLL,
&d.sll, &d.ip4, &d.ip6, &d.tcp, &d.payload)
case layers.LinkTypeEthernet:
d.Parser = gopacket.NewDecodingLayerParser(
layers.LayerTypeEthernet,
&d.eth, &d.ip4, &d.ip6, &d.tcp, &d.payload)
case layers.LinkTypeNull: // loopback on OSx
d.Parser = gopacket.NewDecodingLayerParser(
layers.LayerTypeLoopback,
&d.lo, &d.ip4, &d.ip6, &d.tcp, &d.payload)
default:
return nil, fmt.Errorf("Unsuported link type: %s", datalink.String())
}
d.decoded = []gopacket.LayerType{}
return &d, nil
}
func (decoder *DecoderStruct) DecodePacketData(data []byte, ci *gopacket.CaptureInfo) {
var err error
var packet Packet
err = decoder.Parser.DecodeLayers(data, &decoder.decoded)
if err != nil {
DEBUG("pcapread", "Decoding error: %s", err)
return
}
has_tcp := false
for _, layerType := range decoder.decoded {
switch layerType {
case layers.LayerTypeIPv4:
DEBUG("ip", "IPv4 packet")
packet.tuple.Src_ip = decoder.ip4.SrcIP
packet.tuple.Dst_ip = decoder.ip4.DstIP
packet.tuple.ip_length = 4
case layers.LayerTypeIPv6:
DEBUG("ip", "IPv6 packet")
packet.tuple.Src_ip = decoder.ip6.SrcIP
packet.tuple.Dst_ip = decoder.ip6.DstIP
packet.tuple.ip_length = 16
case layers.LayerTypeTCP:
DEBUG("ip", "TCP packet")
packet.tuple.Src_port = uint16(decoder.tcp.SrcPort)
packet.tuple.Dst_port = uint16(decoder.tcp.DstPort)
has_tcp = true
case gopacket.LayerTypePayload:
packet.payload = decoder.payload
}
}
if !has_tcp {
DEBUG("pcapread", "No TCP header found in message")
return
}
if len(packet.payload) == 0 && !decoder.tcp.FIN {
// We have no use for this atm.
DEBUG("pcapread", "Ignore empty non-FIN packet")
return
}
packet.ts = ci.Timestamp
packet.tuple.ComputeHashebles()
FollowTcp(&decoder.tcp, &packet)
}