forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
423 lines (347 loc) · 10.5 KB
/
main.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
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"runtime"
"runtime/pprof"
"strconv"
"strings"
"time"
"github.com/BurntSushi/toml"
"github.com/akrennmair/gopcap"
"github.com/nranchev/go-libGeoIP"
)
const Version = "0.3.3"
type Packet struct {
ts time.Time
tuple IpPortTuple
payload []byte
}
type protocolType uint16
const (
UnknownProtocol protocolType = iota
HttpProtocol
MysqlProtocol
RedisProtocol
PgsqlProtocol
)
var protocolNames = []string{"unknown", "http", "mysql", "redis", "pgsql"}
type tomlConfig struct {
Interfaces tomlInterfaces
RunOptions tomlRunOptions
Protocols map[string]tomlProtocol
Procs tomlProcs
Output map[string]tomlMothership
Agent tomlAgent
Logging tomlLogging
Passwords tomlPasswords
}
type tomlInterfaces struct {
Device string
}
type tomlRunOptions struct {
Uid int
Gid int
}
type tomlLogging struct {
Selectors []string
}
type tomlPasswords struct {
Hide_keywords []string
}
var _Config tomlConfig
var _ConfigMeta toml.MetaData
var _GeoLite *libgeo.GeoIP
func Bytes_Ipv4_Ntoa(bytes []byte) string {
var strarr []string = make([]string, 4)
for i, b := range bytes {
strarr[i] = strconv.Itoa(int(b))
}
return strings.Join(strarr, ".")
}
func decodePktEth(datalink int, pkt *pcap.Packet) {
defer RECOVER("decodePktEth exception")
packet := new(Packet)
var l2hlen int
var eth_type uint16
switch datalink {
case pcap.LINKTYPE_ETHERNET: // Ethernet
l2hlen = 14
// bytes 12 and 13 are the pkt type
eth_type = Bytes_Ntohs(pkt.Data[12:14])
case pcap.LINKTYPE_LINUX_SLL: // linux loopback
l2hlen = 16
// bytes 14 and 15 are the pkt type
eth_type = Bytes_Ntohs(pkt.Data[14:16])
case pcap.LINKTYPE_NULL: // bsd loopback
l2hlen = 4
if Bytes_Htohl(pkt.Data[0:4]) == 2 {
eth_type = 0x800
} else {
// unknown
eth_type = 0
}
}
if eth_type != 0x800 {
DEBUG("ip", "Not ipv4 packet. Ignoring")
return
}
if len(pkt.Data) < l2hlen+20 {
DEBUG("ip", "Packet too short to be ethernet")
return
}
// IP header
iphl := int((uint16(pkt.Data[l2hlen]) & 0x0f) * 4)
if iphl < 20 {
DEBUG("ip", "IP header shorter than 20 bytes, ignoring")
return
}
if len(pkt.Data) < l2hlen+iphl {
DEBUG("ip", "Packet too short to be IP")
return
}
iphdr := pkt.Data[l2hlen : l2hlen+iphl]
packet.ts = pkt.Time
packet.tuple.Src_ip = Bytes_Ntohl(iphdr[12:16])
packet.tuple.Dst_ip = Bytes_Ntohl(iphdr[16:20])
mf := (uint8(iphdr[6]&0x20) != 0)
frag_offset := (uint16(iphdr[7]) << 3) | (uint16(iphdr[6]) & 0x1F)
if mf || frag_offset > 0 {
DEBUG("ip", "Fragmented packets not yet supported")
return
}
ip_length := int(Bytes_Ntohs(iphdr[2:4]))
protocol := uint8(iphdr[9])
if protocol != 6 {
DEBUG("ip", "Not TCP packet. Ignoring")
return
}
if len(pkt.Data) < l2hlen+iphl+20 {
DEBUG("ip", "Packet too short to be TCP")
return
}
tcphl := int((uint16(pkt.Data[l2hlen+iphl+12]) >> 4) * 4)
if tcphl > 20 && len(pkt.Data) < l2hlen+iphl+tcphl {
DEBUG("ip", "Packet too short to contain TCP header")
return
}
tcphdr := pkt.Data[l2hlen+iphl : l2hlen+iphl+tcphl]
packet.tuple.Src_port = Bytes_Ntohs(tcphdr[0:2])
packet.tuple.Dst_port = Bytes_Ntohs(tcphdr[2:4])
data_offset := (tcphdr[12] >> 4) * 4
if l2hlen+iphl+int(data_offset) > l2hlen+ip_length {
DEBUG("ip", "data_offset pointing outside of packet")
return
}
if len(pkt.Data) < l2hlen+ip_length {
DEBUG("ip", "Captured packet smaller then advertised in IP layer")
return
}
packet.payload = pkt.Data[l2hlen+iphl+int(data_offset) : l2hlen+ip_length]
FollowTcp(tcphdr, packet)
}
func writeHeapProfile(filename string) {
f, err := os.Create(filename)
if err != nil {
ERR("Failed creating file %s: %s", filename, err)
return
}
pprof.WriteHeapProfile(f)
f.Close()
INFO("Created memory profile file %s.", filename)
}
func debugMemStats() {
var m runtime.MemStats
runtime.ReadMemStats(&m)
DEBUG("mem", "Memory stats: In use: %d Total (even if freed): %d System: %d",
m.Alloc, m.TotalAlloc, m.Sys)
}
func loadGeoIPData() {
geoip_path := "/usr/share/GeoIP/GeoIP.dat"
fi, err := os.Lstat(geoip_path)
if err != nil {
WARN("Could not load GeoIP data: %s", err.Error())
return
}
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
// follow symlink
geoip_path, err = filepath.EvalSymlinks(geoip_path)
if err != nil {
WARN("Could not load GeoIP data: %s", err.Error())
return
}
}
_GeoLite, err = libgeo.Load(geoip_path)
if err != nil {
WARN("Could not load GeoIP data: %s", err.Error())
}
}
func main() {
// Use our own FlagSet, because some libraries pollute the global one
var cmdLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
configfile := cmdLine.String("c", "packetbeat.conf", "Configuration file")
file := cmdLine.String("I", "", "file")
loop := cmdLine.Int("l", 1, "Loop file. 0 - loop forever")
debugSelectorsStr := cmdLine.String("d", "", "Enable certain debug selectors")
oneAtAtime := cmdLine.Bool("O", false, "Read packets one at a time (press Enter)")
toStdout := cmdLine.Bool("e", false, "Output to stdout instead of syslog")
topSpeed := cmdLine.Bool("t", false, "Read packets as fast as possible, without sleeping")
publishDisabled := cmdLine.Bool("N", false, "Disable actual publishing for testing")
verbose := cmdLine.Bool("v", false, "Log at INFO level")
printVersion := cmdLine.Bool("version", false, "Print version and exit")
memprofile := cmdLine.String("memprofile", "", "write memory profile to this file")
cmdLine.Parse(os.Args[1:])
if *printVersion {
fmt.Printf("Packetbeat version %s (%s)\n", Version, runtime.GOARCH)
return
}
logLevel := LOG_ERR
if *verbose {
logLevel = LOG_INFO
}
debugSelectors := []string{}
if len(*debugSelectorsStr) > 0 {
debugSelectors = strings.Split(*debugSelectorsStr, ",")
logLevel = LOG_DEBUG
}
var h *pcap.Pcap
var err error
if _ConfigMeta, err = toml.DecodeFile(*configfile, &_Config); err != nil {
fmt.Printf("TOML config parsing failed on %s: %s. Exiting.\n", *configfile, err)
return
}
if len(debugSelectors) == 0 {
debugSelectors = _Config.Logging.Selectors
}
LogInit(logLevel, "", !*toStdout, debugSelectors)
if !IS_DEBUG("stdlog") {
// disable standard logging by default
log.SetOutput(ioutil.Discard)
}
if *file != "" {
h, err = pcap.Openoffline(*file)
if h == nil {
ERR("Openoffline(%s) failed: %s", *file, err)
return
}
} else {
device := _Config.Interfaces.Device
h, err = pcap.Openlive(device, 65535, true, 0)
if h == nil {
ERR("pcap.Openlive failed(%s): %s", device, err)
return
}
}
defer func() {
h.Close()
}()
if err = DropPrivileges(); err != nil {
CRIT(err.Error())
return
}
if *file == "" {
filter := configToFilter(&_Config)
if filter != "" {
DEBUG("pcapfilter", "Installing filter '%s'", filter)
err := h.Setfilter(filter)
if err != nil {
ERR("pcap.Setfilter failed: %s", err)
return
}
}
}
if err = Publisher.Init(*publishDisabled); err != nil {
CRIT(err.Error())
return
}
if err = procWatcher.Init(&_Config.Procs); err != nil {
CRIT(err.Error())
return
}
if err = TcpInit(); err != nil {
CRIT(err.Error())
return
}
datalink := h.Datalink()
if datalink != pcap.LINKTYPE_ETHERNET && datalink != pcap.LINKTYPE_LINUX_SLL &&
datalink != pcap.LINKTYPE_NULL {
ERR("Unsupported link type: %d", datalink)
}
loadGeoIPData()
counter := 0
live := true
loopCount := 1
var lastPktTime *time.Time = nil
for live {
var pkt *pcap.Packet
var res int32
if *oneAtAtime {
fmt.Println("Press enter to read packet")
fmt.Scanln()
}
pkt, res = h.NextEx()
switch res {
case -1:
ERR("pcap.NextEx() error: %s", h.Geterror())
live = false
continue
case -2:
DEBUG("pcapread", "End of file")
loopCount += 1
if *loop > 0 && loopCount > *loop {
// give a bit of time to the publish goroutine
// to flush
time.Sleep(300 * time.Millisecond)
live = false
continue
}
DEBUG("pcapread", "Reopening the file")
h.Close()
h, err = pcap.Openoffline(*file)
if h == nil {
ERR("Openoffline(%s) failed: %s", *file, err)
return
}
lastPktTime = nil
continue
case 0:
// timeout
continue
}
if res != 1 {
panic(fmt.Sprintf("Unexpected return code from pcap.NextEx: %d", res))
}
if pkt == nil {
panic("Nil packet despite res=1")
}
if *file != "" {
if lastPktTime != nil && !*topSpeed {
sleep := pkt.Time.Sub(*lastPktTime)
if sleep > 0 {
time.Sleep(sleep)
} else {
WARN("Time in pcap went backwards: %d", sleep)
}
}
_lastPktTime := pkt.Time
lastPktTime = &_lastPktTime
pkt.Time = time.Now() // overwrite what we get from the pcap
}
counter++
DEBUG("pcapread", "Packet number: %d", counter)
decodePktEth(datalink, pkt)
}
INFO("Input finish. Processed %d packets. Have a nice day!", counter)
if *memprofile != "" {
// wait for all TCP streams to expire
time.Sleep(TCP_STREAM_EXPIRY * 1.2)
PrintTcpMap()
runtime.GC()
writeHeapProfile(*memprofile)
debugMemStats()
}
}