So I wanted to use RegisterFiltered method for filtration of traffic which is irrelevant for me. But I can't make it work.
I have created filters to remove traffic going from/to localhost in this example:
package main
import (
"context"
"github.com/florianl/go-conntrack"
"log"
"os"
"time"
)
func main() {
var err error
logger := log.Logger{}
logger.SetOutput(os.Stdout)
nfct, err := conntrack.Open(&conntrack.Config{
Logger: &logger,
AddConntrackInformation: true,
})
if err != nil {
logger.Fatalln("could not create nfct: %v", err)
}
var processor = func(c conntrack.Con) int {
if c.Origin.Proto.DstPort == nil {
logger.Printf("Port for %s is nil\n", c.Origin.Dst.String())
return 0
}
logger.Printf("Conntrack connection: src: %s - dest: %s:%d\n", c.Origin.Src.String(), c.Origin.Dst.String(), *c.Origin.Proto.DstPort)
return 0
}
filters := make([]conntrack.ConnAttr, 0)
filterLocalhostSrc := conntrack.ConnAttr{Type: conntrack.AttrOrigIPv4Src, Data: []byte{0x7f, 0x0, 0x0, 0x1}, Mask: []byte{0xff, 0xff, 0xff, 0xff}, Negate: true}
filterLocalhostDst := conntrack.ConnAttr{Type: conntrack.AttrOrigIPv4Dst, Data: []byte{0x7f, 0x0, 0x0, 0x1}, Mask: []byte{0xff, 0xff, 0xff, 0xff}, Negate: true}
filters = append(filters, filterLocalhostSrc, filterLocalhostDst)
err = nfct.RegisterFiltered(context.Background(), conntrack.Conntrack, conntrack.NetlinkCtNew|conntrack.NetlinkCtUpdate|conntrack.NetlinkCtDestroy, filters, processor)
if err != nil {
logger.Printf("could not register callback: %v\n", err)
}
time.Sleep(2 * time.Second)
err = nfct.Close()
if err != nil {
logger.Printf("nfct close error: %v\n", err)
}
time.Sleep(1 * time.Second)
logger.Println("closing")
}
But it doesn't work for me. This traffic is still forwarder to the userspace. Example from console:
Conntrack connection: src: 127.0.0.1 - dest: 127.0.0.1:8125
Conntrack connection: src: 127.0.0.1 - dest: 127.0.0.1:8125
Conntrack connection: src: 127.0.0.1 - dest: 127.0.0.1:55586
receiving error: netlink receive: use of closed file
could not remove filter: netlink remove-bpf: setsockopt: bad file descriptor
could not unsubscribe from group: netlink leave-group: setsockopt: bad file descriptor
But I'm not sure if it is relevant.
I have also noticed that if I use positive filter (for example to get just traffic from localhost}, it seems that it works:
filterLocalhostSrc := conntrack.ConnAttr{Type: conntrack.AttrOrigIPv4Src, Data: []byte{0x7f, 0x0, 0x0, 0x1}, Mask: []byte{0xff, 0xff, 0xff, 0xff}, Negate: false}
So probably just negative filters don't work.
Any suggestion would be appreciated.