forked from florianl/go-nflog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nflog.go
296 lines (252 loc) · 7.01 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
//+build linux
package nflog
import (
"context"
"encoding/binary"
"fmt"
"log"
"github.com/mdlayher/netlink"
"github.com/mdlayher/netlink/nlenc"
"golang.org/x/sys/unix"
)
// Nflog represents a netfilter log handler
type Nflog struct {
// Con is the pure representation of a netlink socket
Con *netlink.Conn
logger *log.Logger
flags []byte //uint16
bufsize []byte //uint32
qthresh []byte //uint32
timeout []byte //uint32
group uint16
copyMode uint8
}
// devNull satisfies io.Writer, in case *log.Logger is not provided
type devNull struct{}
func (devNull) Write(p []byte) (int, error) {
return 0, nil
}
// Open a connection to the netfilter log subsystem
func Open(config *Config) (*Nflog, error) {
var nflog Nflog
if config == nil {
config = &Config{}
}
if err := checkFlags(config.Flags); err != nil {
return nil, err
}
if config.Copymode != NfUlnlCopyNone && config.Copymode != NfUlnlCopyMeta && config.Copymode != NfUlnlCopyPacket {
return nil, ErrCopyMode
}
con, err := netlink.Dial(unix.NETLINK_NETFILTER, &netlink.Config{NetNS: config.NetNS})
if err != nil {
return nil, err
}
nflog.Con = con
if config.Logger == nil {
nflog.logger = log.New(new(devNull), "", 0)
} else {
nflog.logger = config.Logger
}
nflog.flags = []byte{0x00, 0x00}
binary.BigEndian.PutUint16(nflog.flags, config.Flags)
nflog.timeout = []byte{0x00, 0x00, 0x00, 0x00}
binary.BigEndian.PutUint32(nflog.timeout, config.Timeout)
nflog.bufsize = []byte{0x00, 0x00, 0x00, 0x00}
binary.BigEndian.PutUint32(nflog.bufsize, config.Bufsize)
nflog.qthresh = []byte{0x00, 0x00, 0x00, 0x00}
binary.BigEndian.PutUint32(nflog.qthresh, config.QThresh)
nflog.group = config.Group
nflog.copyMode = config.Copymode
return &nflog, nil
}
func checkFlags(flags uint16) error {
if flags > NfUlnlCfgFConntrack {
return ErrUnknownFlag
}
return nil
}
// Close the connection to the netfilter log subsystem
func (nflog *Nflog) Close() error {
return nflog.Con.Close()
}
// HookFunc is a function, that receives events from a Netlinkgroup
// To stop receiving messages on this HookFunc, return something different than 0
type HookFunc func(m Msg) int
// Register your own function as callback for a netfilter log group
func (nflog *Nflog) Register(ctx context.Context, fn HookFunc) error {
// unbinding existing handler (if any)
seq, err := nflog.setConfig(unix.AF_UNSPEC, 0, 0, []netlink.Attribute{
{Type: nfUlACfgCmd, Data: []byte{nfUlnlCfgCmdPfUnbind}},
})
if err != nil {
return err
}
// binding to family
_, err = nflog.setConfig(unix.AF_UNSPEC, seq, 0, []netlink.Attribute{
{Type: nfUlACfgCmd, Data: []byte{nfUlnlCfgCmdPfBind}},
})
if err != nil {
return err
}
// binding to generic group
_, err = nflog.setConfig(unix.AF_UNSPEC, seq, 0, []netlink.Attribute{
{Type: nfUlACfgCmd, Data: []byte{nfUlnlCfgCmdBind}},
})
if err != nil {
return err
}
// binding to the requested group
_, err = nflog.setConfig(unix.AF_UNSPEC, seq, nflog.group, []netlink.Attribute{
{Type: nfUlACfgCmd, Data: []byte{nfUlnlCfgCmdBind}},
})
if err != nil {
return err
}
// set copy mode and buffer size
data := append(nflog.bufsize, nflog.copyMode)
data = append(data, 0x0)
_, err = nflog.setConfig(unix.AF_UNSPEC, seq, nflog.group, []netlink.Attribute{
{Type: nfUlACfgMode, Data: data},
})
if err != nil {
return err
}
var attrs []netlink.Attribute
if nflog.flags[0] != 0 || nflog.flags[1] != 0 {
// set flags
attrs = append(attrs, netlink.Attribute{Type: nfUlACfgFlags, Data: nflog.flags})
}
if nflog.timeout[0] != 0 || nflog.timeout[1] != 0 || nflog.timeout[2] != 0 || nflog.timeout[3] != 0 {
// set timeout
attrs = append(attrs, netlink.Attribute{Type: nfUlACfgTimeOut, Data: nflog.timeout})
}
if nflog.qthresh[0] != 0 || nflog.qthresh[1] != 1 || nflog.qthresh[2] != 0 || nflog.qthresh[3] != 0 {
// set qthresh
attrs = append(attrs, netlink.Attribute{Type: nfUlACfgQThresh, Data: nflog.timeout})
}
if len(attrs) != 0 {
_, err = nflog.setConfig(unix.AF_UNSPEC, seq, nflog.group, attrs)
if err != nil {
return err
}
}
go func() {
defer func() {
// unbinding from group
_, err = nflog.setConfig(unix.AF_UNSPEC, seq, nflog.group, []netlink.Attribute{
{Type: nfUlACfgCmd, Data: []byte{nfUlnlCfgCmdUnbind}},
})
if err != nil {
nflog.logger.Printf("Could not unbind socket from configuration: %v", err)
return
}
}()
for {
reply, err := nflog.Con.Receive()
if err != nil {
nflog.logger.Printf("Could not receive message: %v", err)
continue
}
for _, msg := range reply {
if msg.Header.Type == netlink.HeaderTypeDone {
// this is the last message of a batch
// continue to receive messages
break
}
m, err := parseMsg(nflog.logger, msg)
if err != nil {
nflog.logger.Printf("Could not parse message: %v", err)
continue
}
if ret := fn(m); ret != 0 {
return
}
}
select {
case <-ctx.Done():
return
default:
}
}
}()
return nil
}
// /include/uapi/linux/netfilter/nfnetlink.h:struct nfgenmsg{} res_id is Big Endian
func putExtraHeader(familiy, version uint8, resid uint16) []byte {
buf := make([]byte, 2)
binary.BigEndian.PutUint16(buf, resid)
return append([]byte{familiy, version}, buf...)
}
func (nflog *Nflog) setConfig(afFamily uint8, oseq uint32, resid uint16, attrs []netlink.Attribute) (uint32, error) {
cmd, err := netlink.MarshalAttributes(attrs)
if err != nil {
return 0, err
}
data := putExtraHeader(afFamily, unix.NFNETLINK_V0, resid)
data = append(data, cmd...)
req := netlink.Message{
Header: netlink.Header{
Type: netlink.HeaderType((nfnlSubSysUlog << 8) | nfUlnlMsgConfig),
Flags: netlink.HeaderFlagsRequest | netlink.HeaderFlagsAcknowledge,
Sequence: oseq,
},
Data: data,
}
return nflog.execute(req)
}
// ErrMsg as defined in nlmsgerr
type ErrMsg struct {
Code int
Len uint32
Type uint16
Flags uint16
Seq uint32
Pid uint32
}
func unmarschalErrMsg(b []byte) (ErrMsg, error) {
var msg ErrMsg
msg.Code = int(nlenc.Uint32(b[0:4]))
msg.Len = nlenc.Uint32(b[4:8])
msg.Type = nlenc.Uint16(b[8:10])
msg.Flags = nlenc.Uint16(b[10:12])
msg.Seq = nlenc.Uint32(b[12:16])
msg.Pid = nlenc.Uint32(b[16:20])
return msg, nil
}
func (nflog *Nflog) execute(req netlink.Message) (uint32, error) {
var seq uint32
reply, e := nflog.Con.Execute(req)
if e != nil {
return 0, e
}
if e := netlink.Validate(req, reply); e != nil {
return 0, e
}
for _, msg := range reply {
if seq != 0 {
return 0, fmt.Errorf("Received more than one message from the kernel")
}
seq = msg.Header.Sequence
}
return seq, nil
}
func htonsU32(i uint32) []byte {
buf := make([]byte, 4)
nlenc.PutUint32(buf, i)
return buf
}
func parseMsg(logger *log.Logger, msg netlink.Message) (Msg, error) {
if msg.Header.Type&netlink.HeaderTypeError == netlink.HeaderTypeError {
errMsg, err := unmarschalErrMsg(msg.Data)
if err != nil {
return nil, err
}
return nil, fmt.Errorf("%#v", errMsg)
}
m, err := extractAttributes(logger, msg.Data)
if err != nil {
return nil, err
}
return m, nil
}