-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
publish.go
310 lines (258 loc) · 6.48 KB
/
publish.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
package publish
import (
"errors"
"fmt"
"sync"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/logp"
"github.com/elastic/beats/libbeat/publisher"
"github.com/nranchev/go-libGeoIP"
)
type Transactions interface {
PublishTransaction(common.MapStr) bool
}
type Flows interface {
PublishFlows([]common.MapStr) bool
}
type PacketbeatPublisher struct {
pub publisher.Publisher
client publisher.Client
topo topologyProvider
geoLite *libgeo.GeoIP
ignoreOutgoing bool
wg sync.WaitGroup
done chan struct{}
trans chan common.MapStr
flows chan []common.MapStr
}
type ChanTransactions struct {
Channel chan common.MapStr
}
// XXX: currently implemented by libbeat publisher. This functionality is only
// required by packetbeat. Source for TopologyProvider should become local to
// packetbeat.
type topologyProvider interface {
IsPublisherIP(ip string) bool
GetServerName(ip string) string
GeoLite() *libgeo.GeoIP
}
func (t *ChanTransactions) PublishTransaction(event common.MapStr) bool {
t.Channel <- event
return true
}
var debugf = logp.MakeDebug("publish")
func NewPublisher(
pub publisher.Publisher,
hwm, bulkHWM int,
ignoreOutgoing bool,
) (*PacketbeatPublisher, error) {
topo, ok := pub.(topologyProvider)
if !ok {
return nil, errors.New("Requires topology provider")
}
return &PacketbeatPublisher{
pub: pub,
topo: topo,
geoLite: topo.GeoLite(),
ignoreOutgoing: ignoreOutgoing,
client: pub.Connect(),
done: make(chan struct{}),
trans: make(chan common.MapStr, hwm),
flows: make(chan []common.MapStr, bulkHWM),
}, nil
}
func (p *PacketbeatPublisher) PublishTransaction(event common.MapStr) bool {
select {
case p.trans <- event:
return true
default:
// drop event if queue is full
return false
}
}
func (p *PacketbeatPublisher) PublishFlows(event []common.MapStr) bool {
select {
case p.flows <- event:
return true
case <-p.done:
// drop event, if worker has been stopped
return false
}
}
func (p *PacketbeatPublisher) Start() {
p.wg.Add(1)
go func() {
defer p.wg.Done()
for {
select {
case <-p.done:
return
case event := <-p.trans:
p.onTransaction(event)
}
}
}()
p.wg.Add(1)
go func() {
defer p.wg.Done()
for {
select {
case <-p.done:
return
case events := <-p.flows:
p.onFlow(events)
}
}
}()
}
func (p *PacketbeatPublisher) Stop() {
p.client.Close()
close(p.done)
p.wg.Wait()
}
func (p *PacketbeatPublisher) onTransaction(event common.MapStr) {
if err := validateEvent(event); err != nil {
logp.Warn("Dropping invalid event: %v", err)
return
}
if !p.normalizeTransAddr(event) {
return
}
p.client.PublishEvent(event)
}
func (p *PacketbeatPublisher) onFlow(events []common.MapStr) {
pub := events[:0]
for _, event := range events {
if err := validateEvent(event); err != nil {
logp.Warn("Dropping invalid event: %v", err)
continue
}
if !p.addGeoIPToFlow(event) {
continue
}
pub = append(pub, event)
}
p.client.PublishEvents(pub)
}
// filterEvent validates an event for common required fields with types.
// If event is to be filtered out the reason is returned as error.
func validateEvent(event common.MapStr) error {
ts, ok := event["@timestamp"]
if !ok {
return errors.New("missing '@timestamp' field from event")
}
_, ok = ts.(common.Time)
if !ok {
return errors.New("invalid '@timestamp' field from event")
}
t, ok := event["type"]
if !ok {
return errors.New("missing 'type' field from event")
}
_, ok = t.(string)
if !ok {
return errors.New("invalid 'type' field from event")
}
return nil
}
func (p *PacketbeatPublisher) normalizeTransAddr(event common.MapStr) bool {
debugf("normalize address for: %v", event)
var srcServer, dstServer string
src, ok := event["src"].(*common.Endpoint)
debugf("has src: %v", ok)
if ok {
// check if it's outgoing transaction (as client)
isOutgoing := p.topo.IsPublisherIP(src.IP)
if isOutgoing {
if p.ignoreOutgoing {
// duplicated transaction -> ignore it
debugf("Ignore duplicated transaction on: %s -> %s", srcServer, dstServer)
return false
}
//outgoing transaction
event["direction"] = "out"
}
srcServer = p.topo.GetServerName(src.IP)
event["client_ip"] = src.IP
event["client_port"] = src.Port
event["client_proc"] = src.Proc
event["client_server"] = srcServer
delete(event, "src")
}
dst, ok := event["dst"].(*common.Endpoint)
debugf("has dst: %v", ok)
if ok {
dstServer = p.topo.GetServerName(dst.IP)
event["ip"] = dst.IP
event["port"] = dst.Port
event["proc"] = dst.Proc
event["server"] = dstServer
delete(event, "dst")
//check if it's incoming transaction (as server)
if p.topo.IsPublisherIP(dst.IP) {
// incoming transaction
event["direction"] = "in"
}
}
if p.geoLite != nil {
realIP, exists := event["real_ip"]
if exists && len(realIP.(common.NetString)) > 0 {
loc := p.geoLite.GetLocationByIP(string(realIP.(common.NetString)))
if loc != nil && loc.Latitude != 0 && loc.Longitude != 0 {
loc := fmt.Sprintf("%f, %f", loc.Latitude, loc.Longitude)
event["client_location"] = loc
}
} else {
if len(srcServer) == 0 && src != nil { // only for external IP addresses
loc := p.geoLite.GetLocationByIP(src.IP)
if loc != nil && loc.Latitude != 0 && loc.Longitude != 0 {
loc := fmt.Sprintf("%f, %f", loc.Latitude, loc.Longitude)
event["client_location"] = loc
}
}
}
}
return true
}
func (p *PacketbeatPublisher) addGeoIPToFlow(event common.MapStr) bool {
getLocation := func(host common.MapStr, ip_type string) string {
ip, exists := host[ip_type]
if !exists {
return ""
}
str, ok := ip.(string)
if !ok {
logp.Warn("IP address must be string")
return ""
}
loc := p.geoLite.GetLocationByIP(str)
if loc == nil || loc.Latitude == 0 || loc.Longitude == 0 {
return ""
}
return fmt.Sprintf("%f, %f", loc.Latitude, loc.Longitude)
}
if p.geoLite == nil {
return true
}
ipFieldNames := [][]string{
{"ip", "ip_location"},
{"outter_ip", "outter_ip_location"},
{"ipv6", "ipv6_location"},
{"outter_ipv6", "outter_ipv6_location"},
}
source := event["source"].(common.MapStr)
dest := event["dest"].(common.MapStr)
for _, name := range ipFieldNames {
loc := getLocation(source, name[0])
if loc != "" {
source[name[1]] = loc
}
loc = getLocation(dest, name[0])
if loc != "" {
dest[name[1]] = loc
}
}
event["source"] = source
event["dest"] = dest
return true
}