forked from aporeto-inc/netlink-go
/
nflog.go
332 lines (267 loc) · 7.84 KB
/
nflog.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
// +build linux !darwin
package nflog
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"syscall"
"go.aporeto.io/netlink-go/common"
"go.aporeto.io/netlink-go/common/syscallwrappers"
"go.aporeto.io/trireme-lib/controller/pkg/packet"
)
// NewNFLog -- Create a new Nflog handle
func NewNFLog() NFLog {
n := &NfLog{Syscalls: syscallwrappers.NewSyscalls()}
return n
}
// BindAndListenForLogs -- a complete set to open/unbind/bind/bindgroup and listen for logs
// group -- group to bind with and listen
// packetSize -- max expected packetSize (0:unlimited)
func BindAndListenForLogs(groups []uint16, packetSize uint32, callback func(*NfPacket, interface{}), errorCallback func(err error)) (NFLog, error) {
nflHandle := NewNFLog()
nflog, err := nflHandle.NFlogOpen()
if err != nil {
return nil, fmt.Errorf("Error opening NFLog handle: %v ", err)
}
if err := nflHandle.NFlogBindGroup(groups, callback, errorCallback); err != nil {
nflHandle.NFlogClose()
return nil, fmt.Errorf("Error binding to nflog group: %v ", err)
}
if err := nflHandle.NFlogSetMode(groups, packetSize); err != nil {
nflHandle.NFlogClose()
return nil, fmt.Errorf("Unable to set copy packet mode: %v ", err)
}
go nflHandle.ReadLogs()
return nflog, nil
}
// NFlogOpen Open a new netlink socket
// Create a new sock handle and return the handle
// Open a new socket and return it in the NflogHandle.
// The fd for the socket is stored in an unexported handle
func (nl *NfLog) NFlogOpen() (NFLog, error) {
sh := &SockHandles{Syscalls: nl.Syscalls}
fd, err := nl.Syscalls.Socket(syscall.AF_NETLINK, syscall.SOCK_RAW, syscall.NETLINK_NETFILTER)
if err != nil {
return nil, err
}
sh.fd = fd
sh.rcvbufSize = common.NfnlBuffSize
sh.lsa.Family = syscall.AF_NETLINK
err = nl.Syscalls.Bind(fd, &sh.lsa)
if err != nil {
return nil, err
}
nl.Socket = sh
nl.NflogHandle = nl
return nl.NflogHandle, nil
}
// NFlogUnbind -- passes an unbind command to nfnetlink for AF_INET.
func (nl *NfLog) NFlogUnbind() error {
config := &NflMsgConfigCommand{
command: NFULNL_CFG_CMD_PF_UNBIND,
}
hdr := common.BuildNlMsgHeader(common.NfnlNFLog,
common.NlmFRequest|common.NlmFAck,
0,
)
nfgen := common.BuildNfgenMsg(syscall.AF_INET, common.NFNetlinkV0, 0, hdr)
attr := common.BuildNfAttrMsg(NFULA_CFG_CMD, hdr, config.Length())
data := nfgen.ToWireFormat()
data = append(data, attr.ToWireFormat()...)
data = append(data, config.ToWireFormat()...)
netlinkMsg := &syscall.NetlinkMessage{
Header: *hdr,
Data: data,
}
if nl.Socket != nil {
return nl.Socket.query(netlinkMsg)
}
return fmt.Errorf("NFlogOpen was not called. No Socket open")
}
// NFlogBind -- Bind to a PF family
func (nl *NfLog) NFlogBind() error {
config := &NflMsgConfigCommand{
command: NFULNL_CFG_CMD_PF_BIND,
}
hdr := common.BuildNlMsgHeader(common.NfnlNFLog,
common.NlmFRequest|common.NlmFAck,
0,
)
nfgen := common.BuildNfgenMsg(syscall.AF_INET, common.NFNetlinkV0, 0, hdr)
attr := common.BuildNfAttrMsg(NFULA_CFG_CMD, hdr, config.Length())
data := nfgen.ToWireFormat()
data = append(data, attr.ToWireFormat()...)
data = append(data, config.ToWireFormat()...)
netlinkMsg := &syscall.NetlinkMessage{
Header: *hdr,
Data: data,
}
if nl.Socket != nil {
return nl.Socket.query(netlinkMsg)
}
return fmt.Errorf("NFlogOpen was not called. No Socket open")
}
// NFlogBindGroup -- Bind to a group
// group -- group to bind with
func (nl *NfLog) NFlogBindGroup(groups []uint16, callback func(*NfPacket, interface{}), errorCallback func(err error)) error {
nl.callback = callback
nl.errorCallback = errorCallback
for _, g := range groups {
config := &NflMsgConfigCommand{
command: NFULNL_CFG_CMD_BIND,
}
hdr := common.BuildNlMsgHeader(common.NfnlNFLog,
common.NlmFRequest|common.NlmFAck,
0,
)
nfgen := common.BuildNfgenMsg(syscall.AF_INET, common.NFNetlinkV0, g, hdr)
attr := common.BuildNfAttrMsg(NFULA_CFG_CMD, hdr, config.Length())
data := nfgen.ToWireFormat()
data = append(data, attr.ToWireFormat()...)
data = append(data, config.ToWireFormat()...)
netlinkMsg := &syscall.NetlinkMessage{
Header: *hdr,
Data: data,
}
if nl.Socket != nil {
err := nl.Socket.query(netlinkMsg)
if err != nil {
return err
}
}
}
return nil
}
// NFlogSetMode -- Set queue mode CopyMeta
// packetSize -- The range of bytes from packets to copy
func (nl *NfLog) NFlogSetMode(groups []uint16, packetSize uint32) error {
for _, g := range groups {
config := &NflMsgConfigMode{
copyMode: NFULNL_COPY_PACKET,
copyRange: packetSize,
}
hdr := common.BuildNlMsgHeader(common.NfnlNFLog,
common.NlmFRequest|common.NlmFAck,
0,
)
nfgen := common.BuildNfgenMsg(syscall.AF_UNSPEC, common.NFNetlinkV0, g, hdr)
attr := common.BuildNfAttrMsg(NFULA_CFG_MODE, hdr, config.Length())
data := nfgen.ToWireFormat()
data = append(data, attr.ToWireFormat()...)
data = append(data, config.ToWireFormat()...)
netlinkMsg := &syscall.NetlinkMessage{
Header: *hdr,
Data: data,
}
if nl.Socket != nil {
err := nl.Socket.query(netlinkMsg)
if err != nil {
return err
}
}
}
return nil
}
// ReadLogs -- Listen for logs on the current socket
func (nl *NfLog) ReadLogs() {
defer nl.NFlogClose()
buffer := make([]byte, 65536)
for {
s, _, err := nl.Syscalls.Recvfrom(nl.Socket.getFd(), buffer, 0)
if err != nil {
if nl.errorCallback != nil {
nl.errorCallback(fmt.Errorf("Netlink error %v", err))
}
if err == syscall.ENOBUFS {
continue
}
return
}
err = nl.parseLog(buffer[:s])
if err != nil {
if nl.errorCallback != nil {
nl.errorCallback(fmt.Errorf("Parse error %v", err))
}
}
}
}
// parseLog -- parse the log and call parsePacket
func (nl *NfLog) parseLog(buffer []byte) error {
for len(buffer) > 0 {
reader := bytes.NewReader(buffer)
var header syscall.NlMsghdr
binary.Read(reader, binary.LittleEndian, &header)
msgLen := header.Len
if msgLen > uint32(len(buffer)) {
return fmt.Errorf("Message was truncated")
}
if header.Type == ((common.NFNL_SUBSYS_ULOG << 8) | NFULNL_MSG_PACKET) {
err := nl.parsePacket(buffer[16 : msgLen-1])
if err != nil {
return fmt.Errorf("Failed to parse NFPacket: %v", err)
}
}
buffer = buffer[msgLen:]
}
return nil
}
// parsePacket -- parse packet and set callback for any further processing
func (nl *NfLog) parsePacket(buffer []byte) error {
reader := bytes.NewReader(buffer)
var header nflogHeader
binary.Read(reader, binary.LittleEndian, &header)
var m NfPacket
var tlvHeader nflogTlv
for reader.Len() != 0 {
err := binary.Read(reader, binary.LittleEndian, &tlvHeader)
if err != nil {
return err
}
payloadLen := tlvHeader.Len - 4
switch tlvHeader.Type {
case NFULA_PREFIX:
payload := make([]byte, NfaAlign16(payloadLen))
reader.Read(payload)
m.Prefix = string(payload[:payloadLen-1])
case NFULA_PAYLOAD:
payload := make([]byte, NfaAlign16(payloadLen))
reader.Read(payload)
ipPacket, err := packet.New(packet.PacketTypeNetwork, payload, "", false)
if err != nil {
return err
}
if ipPacket != nil {
m.SrcIP = ipPacket.SourceAddress()
m.DstIP = ipPacket.DestinationAddress()
m.Version = IPVersion
m.Protocol = ipPacket.IPProto()
m.Length = ipPacket.IPTotalLen()
m.SrcPort = ipPacket.SourcePort()
m.DstPort = ipPacket.DestPort()
}
m.Payload = payload[:payloadLen]
nl.callback(&NfPacket{
Payload: m.Payload,
IPLayer: m.IPLayer,
Ports: m.Ports,
Prefix: m.Prefix,
PacketPayload: m.PacketPayload,
NflogHandle: nl,
}, nil)
default:
reader.Seek(int64(NfaAlign16(payloadLen)), io.SeekCurrent)
}
}
return nil
}
// GetNFloghandle -- Get the nflog handle created
func (nl *NfLog) GetNFloghandle() NFLog {
return nl.NflogHandle
}
// NFlogClose -- close the current socket
func (nl *NfLog) NFlogClose() {
if nl.Socket != nil {
nl.Socket.close()
}
}