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
|
//go:build integration && linux
// +build integration,linux
package nfqueue
import (
"context"
"os/exec"
"testing"
"time"
)
func startDummyPingTraffic(t *testing.T, ctx context.Context) {
t.Helper()
if err := exec.CommandContext(ctx, "ping6", "2606:4700:4700::1111").Start(); err != nil {
t.Fatalf("failed to start IPv6 ping: %v", err)
}
if err := exec.CommandContext(ctx, "ping", "1.1.1.1").Start(); err != nil {
t.Fatalf("failed to start IPv4 ping: %v", err)
}
}
func TestLinuxNfqueue(t *testing.T) {
pingCtx, pingCancel := context.WithCancel(context.Background())
defer pingCancel()
startDummyPingTraffic(t, pingCtx)
// Set configuration options for nfqueue
config := Config{
NfQueue: 100,
MaxPacketLen: 0xFFFF,
MaxQueueLen: 0xFF,
Copymode: NfQnlCopyPacket,
}
// Open a socket to the netfilter log subsystem
nfq, err := Open(&config)
if err != nil {
t.Fatalf("failed to open nfqueue socket: %v", err)
}
defer nfq.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
fn := func(a Attribute) int {
id := *a.PacketID
// Just print out the id and payload of the nfqueue packet
t.Logf("[%d]\t%v\n", id, *a.Payload)
nfq.SetVerdict(id, NfAccept)
return 0
}
// Register your function to listen on nflog group 100
err = nfq.Register(ctx, fn)
if err != nil {
t.Fatalf("failed to register hook function: %v", err)
}
// Block till the context expires
<-ctx.Done()
}
func TestTimeout(t *testing.T) {
// Set configuration options for nfqueue
config := Config{
NfQueue: 123,
MaxPacketLen: 0xFFFF,
MaxQueueLen: 0xFF,
Copymode: NfQnlCopyPacket,
}
nfq, err := Open(&config)
if err != nil {
t.Fatalf("failed to open nfqueue socket: %v", err)
}
defer nfq.Close()
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
fn := func(a Attribute) int {
id := *a.PacketID
// Just print out the id and payload of the nfqueue packet
t.Logf("[%d]\t%v\n", id, *a.Payload)
nfq.SetVerdict(id, NfAccept)
return 0
}
// Register your function to listen on nflog group 123
// This also does a reading on the netlink socket
err = nfq.Register(ctx, fn)
if err != nil {
t.Fatalf("failed to register hook function: %v", err)
}
// cancel the context to remove the registered hook from the nfqueue.
cancel()
// Block till the context expires
<-ctx.Done()
}
|