forked from premendrasingh/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
icmp.go
345 lines (288 loc) · 8.33 KB
/
icmp.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
package icmp
import (
"expvar"
"net"
"time"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/logp"
"github.com/elastic/beats/packetbeat/flows"
"github.com/elastic/beats/packetbeat/protos"
"github.com/elastic/beats/packetbeat/publish"
"github.com/tsg/gopacket/layers"
)
type icmpPlugin struct {
sendRequest bool
sendResponse bool
localIps []net.IP
// Active ICMP transactions.
// The map key is the hashableIcmpTuple associated with the request.
transactions *common.Cache
transactionTimeout time.Duration
results publish.Transactions
}
type ICMPv4Processor interface {
ProcessICMPv4(flowID *flows.FlowID, hdr *layers.ICMPv4, pkt *protos.Packet)
}
type ICMPv6Processor interface {
ProcessICMPv6(flowID *flows.FlowID, hdr *layers.ICMPv6, pkt *protos.Packet)
}
const (
directionLocalOnly = iota
directionFromInside
directionFromOutside
)
// Notes that are added to messages during exceptional conditions.
const (
duplicateRequestMsg = "Another request with the same Id and Seq was received so this request was closed without receiving a response."
orphanedRequestMsg = "Request was received without an associated response."
orphanedResponseMsg = "Response was received without an associated request."
)
var (
unmatchedRequests = expvar.NewInt("icmp.unmatched_requests")
unmatchedResponses = expvar.NewInt("icmp.unmatched_responses")
duplicateRequests = expvar.NewInt("icmp.duplicate_requests")
)
func New(testMode bool, results publish.Transactions, cfg *common.Config) (*icmpPlugin, error) {
p := &icmpPlugin{}
config := defaultConfig
if !testMode {
if err := cfg.Unpack(&config); err != nil {
return nil, err
}
}
if err := p.init(results, &config); err != nil {
return nil, err
}
return p, nil
}
func (icmp *icmpPlugin) init(results publish.Transactions, config *icmpConfig) error {
icmp.setFromConfig(config)
var err error
icmp.localIps, err = common.LocalIPAddrs()
if err != nil {
logp.Err("icmp", "Error getting local IP addresses: %s", err)
icmp.localIps = []net.IP{}
}
logp.Debug("icmp", "Local IP addresses: %s", icmp.localIps)
var removalListener = func(k common.Key, v common.Value) {
icmp.expireTransaction(k.(hashableIcmpTuple), v.(*icmpTransaction))
}
icmp.transactions = common.NewCacheWithRemovalListener(
icmp.transactionTimeout,
protos.DefaultTransactionHashSize,
removalListener)
icmp.transactions.StartJanitor(icmp.transactionTimeout)
icmp.results = results
return nil
}
func (icmp *icmpPlugin) setFromConfig(config *icmpConfig) {
icmp.sendRequest = config.SendRequest
icmp.sendResponse = config.SendResponse
icmp.transactionTimeout = config.TransactionTimeout
}
func (icmp *icmpPlugin) ProcessICMPv4(
flowID *flows.FlowID,
icmp4 *layers.ICMPv4,
pkt *protos.Packet,
) {
typ := uint8(icmp4.TypeCode >> 8)
code := uint8(icmp4.TypeCode)
id, seq := extractTrackingData(4, typ, &icmp4.BaseLayer)
tuple := &icmpTuple{
icmpVersion: 4,
srcIP: pkt.Tuple.SrcIP,
dstIP: pkt.Tuple.DstIP,
id: id,
seq: seq,
}
msg := &icmpMessage{
ts: pkt.Ts,
Type: typ,
code: code,
length: len(icmp4.BaseLayer.Payload),
}
if isRequest(tuple, msg) {
if flowID != nil {
flowID.AddICMPv4Request(id)
}
icmp.processRequest(tuple, msg)
} else {
if flowID != nil {
flowID.AddICMPv4Response(id)
}
icmp.processResponse(tuple, msg)
}
}
func (icmp *icmpPlugin) ProcessICMPv6(
flowID *flows.FlowID,
icmp6 *layers.ICMPv6,
pkt *protos.Packet,
) {
typ := uint8(icmp6.TypeCode >> 8)
code := uint8(icmp6.TypeCode)
id, seq := extractTrackingData(6, typ, &icmp6.BaseLayer)
tuple := &icmpTuple{
icmpVersion: 6,
srcIP: pkt.Tuple.SrcIP,
dstIP: pkt.Tuple.DstIP,
id: id,
seq: seq,
}
msg := &icmpMessage{
ts: pkt.Ts,
Type: typ,
code: code,
length: len(icmp6.BaseLayer.Payload),
}
if isRequest(tuple, msg) {
if flowID != nil {
flowID.AddICMPv6Request(id)
}
icmp.processRequest(tuple, msg)
} else {
if flowID != nil {
flowID.AddICMPv6Response(id)
}
icmp.processResponse(tuple, msg)
}
}
func (icmp *icmpPlugin) processRequest(tuple *icmpTuple, msg *icmpMessage) {
logp.Debug("icmp", "Processing request. %s", tuple)
trans := icmp.deleteTransaction(tuple.Hashable())
if trans != nil {
trans.notes = append(trans.notes, duplicateRequestMsg)
logp.Debug("icmp", duplicateRequestMsg+" %s", tuple)
duplicateRequests.Add(1)
icmp.publishTransaction(trans)
}
trans = &icmpTransaction{ts: msg.ts, tuple: *tuple}
trans.request = msg
if requiresCounterpart(tuple, msg) {
icmp.transactions.Put(tuple.Hashable(), trans)
} else {
icmp.publishTransaction(trans)
}
}
func (icmp *icmpPlugin) processResponse(tuple *icmpTuple, msg *icmpMessage) {
logp.Debug("icmp", "Processing response. %s", tuple)
revTuple := tuple.Reverse()
trans := icmp.deleteTransaction(revTuple.Hashable())
if trans == nil {
trans = &icmpTransaction{ts: msg.ts, tuple: revTuple}
trans.notes = append(trans.notes, orphanedResponseMsg)
logp.Debug("icmp", orphanedResponseMsg+" %s", tuple)
unmatchedResponses.Add(1)
}
trans.response = msg
icmp.publishTransaction(trans)
}
func (icmp *icmpPlugin) direction(t *icmpTransaction) uint8 {
if !icmp.isLocalIP(t.tuple.srcIP) {
return directionFromOutside
}
if !icmp.isLocalIP(t.tuple.dstIP) {
return directionFromInside
}
return directionLocalOnly
}
func (icmp *icmpPlugin) isLocalIP(ip net.IP) bool {
if ip.IsLoopback() {
return true
}
for _, localIP := range icmp.localIps {
if ip.Equal(localIP) {
return true
}
}
return false
}
func (icmp *icmpPlugin) getTransaction(k hashableIcmpTuple) *icmpTransaction {
v := icmp.transactions.Get(k)
if v != nil {
return v.(*icmpTransaction)
}
return nil
}
func (icmp *icmpPlugin) deleteTransaction(k hashableIcmpTuple) *icmpTransaction {
v := icmp.transactions.Delete(k)
if v != nil {
return v.(*icmpTransaction)
}
return nil
}
func (icmp *icmpPlugin) expireTransaction(tuple hashableIcmpTuple, trans *icmpTransaction) {
trans.notes = append(trans.notes, orphanedRequestMsg)
logp.Debug("icmp", orphanedRequestMsg+" %s", &trans.tuple)
unmatchedRequests.Add(1)
icmp.publishTransaction(trans)
}
func (icmp *icmpPlugin) publishTransaction(trans *icmpTransaction) {
if icmp.results == nil {
return
}
logp.Debug("icmp", "Publishing transaction. %s", &trans.tuple)
event := common.MapStr{}
// common fields - group "env"
event["client_ip"] = trans.tuple.srcIP
event["ip"] = trans.tuple.dstIP
// common fields - group "event"
event["@timestamp"] = common.Time(trans.ts) // timestamp of the first packet
event["type"] = "icmp" // protocol name
event["path"] = trans.tuple.dstIP // what is requested (dst ip)
if trans.HasError() {
event["status"] = common.ERROR_STATUS
} else {
event["status"] = common.OK_STATUS
}
if len(trans.notes) > 0 {
event["notes"] = trans.notes
}
// common fields - group "measurements"
responsetime, hasResponseTime := trans.ResponseTimeMillis()
if hasResponseTime {
event["responsetime"] = responsetime
}
switch icmp.direction(trans) {
case directionFromInside:
if trans.request != nil {
event["bytes_out"] = trans.request.length
}
if trans.response != nil {
event["bytes_in"] = trans.response.length
}
case directionFromOutside:
if trans.request != nil {
event["bytes_in"] = trans.request.length
}
if trans.response != nil {
event["bytes_out"] = trans.response.length
}
}
// event fields - group "icmp"
icmpEvent := common.MapStr{}
event["icmp"] = icmpEvent
icmpEvent["version"] = trans.tuple.icmpVersion
if trans.request != nil {
request := common.MapStr{}
icmpEvent["request"] = request
request["message"] = humanReadable(&trans.tuple, trans.request)
request["type"] = trans.request.Type
request["code"] = trans.request.code
// TODO: Add more info. The IPv4/IPv6 payload could be interesting.
// if icmp.SendRequest {
// request["payload"] = ""
// }
}
if trans.response != nil {
response := common.MapStr{}
icmpEvent["response"] = response
response["message"] = humanReadable(&trans.tuple, trans.response)
response["type"] = trans.response.Type
response["code"] = trans.response.code
// TODO: Add more info. The IPv4/IPv6 payload could be interesting.
// if icmp.SendResponse {
// response["payload"] = ""
// }
}
icmp.results.PublishTransaction(event)
}