-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmain.go
66 lines (54 loc) · 1.26 KB
/
main.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
package main
import (
"context"
"encoding/binary"
"fmt"
"net"
"github.com/florianl/go-nfqueue"
)
type packet []byte
func (p packet) srcIP() net.IP {
return net.IP(p[12:16])
}
func (p packet) dstIP() net.IP {
return net.IP(p[16:20])
}
func (p packet) srcPort() uint16 {
tcphdr := p[20:]
return binary.BigEndian.Uint16(tcphdr[:2])
}
func (p packet) dstPort() uint16 {
tcphdr := p[20:]
return binary.BigEndian.Uint16(tcphdr[2:4])
}
func handlePacket(q *nfqueue.Nfqueue, a nfqueue.Attribute) int {
if a.Payload != nil && len(*a.Payload) != 0 {
pkt := packet(*a.Payload)
fmt.Printf("tcp connect: %s:%d -> %s:%d\n", pkt.srcIP(), pkt.srcPort(), pkt.dstIP(), pkt.dstPort())
}
_ = q.SetVerdict(*a.PacketID, nfqueue.NfAccept)
return 0
}
func main() {
cfg := nfqueue.Config{
NfQueue: 1,
MaxQueueLen: 2,
Copymode: nfqueue.NfQnlCopyPacket,
}
nfq, err := nfqueue.Open(&cfg)
if err != nil {
fmt.Println("failed to open nfqueue, err:", err)
return
}
ctx, stop := context.WithCancel(context.Background())
defer stop()
if err := nfq.RegisterWithErrorFunc(ctx, func(a nfqueue.Attribute) int {
return handlePacket(nfq, a)
}, func(e error) int {
return 0
}); err != nil {
fmt.Println("failed to register handlers, err:", err)
return
}
select {}
}