-
Notifications
You must be signed in to change notification settings - Fork 51
/
nflog_linux.go
90 lines (73 loc) · 2.28 KB
/
nflog_linux.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
// +build linux
package nflog
import (
"context"
"sync"
"go.aporeto.io/netlink-go/nflog"
"go.aporeto.io/trireme-lib/collector"
"go.uber.org/zap"
)
type nfLog struct {
getPUContext GetPUContextFunc
ipv4groupSource uint16
ipv4groupDest uint16
collector collector.EventCollector
srcNflogHandle nflog.NFLog
dstNflogHandle nflog.NFLog
sync.Mutex
}
// NewNFLogger provides an NFLog instance
func NewNFLogger(ipv4groupSource, ipv4groupDest uint16, getPUContext GetPUContextFunc, collector collector.EventCollector) NFLogger {
return &nfLog{
ipv4groupSource: ipv4groupSource,
ipv4groupDest: ipv4groupDest,
collector: collector,
getPUContext: getPUContext,
}
}
// Run runs the Nf Logger
func (a *nfLog) Run(ctx context.Context) {
a.Lock()
a.srcNflogHandle, _ = nflog.BindAndListenForLogs([]uint16{a.ipv4groupSource}, 64, a.sourceNFLogsHanlder, a.nflogErrorHandler)
a.dstNflogHandle, _ = nflog.BindAndListenForLogs([]uint16{a.ipv4groupDest}, 64, a.destNFLogsHandler, a.nflogErrorHandler)
a.Unlock()
go func() {
<-ctx.Done()
a.Lock()
a.srcNflogHandle.NFlogClose()
a.dstNflogHandle.NFlogClose()
a.Unlock()
}()
}
func (a *nfLog) sourceNFLogsHanlder(buf *nflog.NfPacket, _ interface{}) {
record, packetEvent, err := a.recordFromNFLogBuffer(buf, false)
if err != nil {
zap.L().Error("sourceNFLogsHanlder: create flow record", zap.Error(err))
return
}
if record != nil {
a.collector.CollectFlowEvent(record)
}
if packetEvent != nil {
a.collector.CollectPacketEvent(packetEvent)
}
}
func (a *nfLog) destNFLogsHandler(buf *nflog.NfPacket, _ interface{}) {
record, packetEvent, err := a.recordFromNFLogBuffer(buf, true)
if err != nil {
zap.L().Error("destNFLogsHandler: create flow record", zap.Error(err))
return
}
if record != nil {
a.collector.CollectFlowEvent(record)
}
if packetEvent != nil {
a.collector.CollectPacketEvent(packetEvent)
}
}
func (a *nfLog) nflogErrorHandler(err error) {
zap.L().Error("Error while processing nflog packet", zap.Error(err))
}
func (a *nfLog) recordFromNFLogBuffer(buf *nflog.NfPacket, puIsSource bool) (*collector.FlowRecord, *collector.PacketReport, error) {
return recordFromNFLogData(buf.Payload, buf.Prefix, buf.Protocol, buf.SrcIP, buf.DstIP, buf.SrcPort, buf.DstPort, a.getPUContext, puIsSource)
}