1

On nftables config logging is set with some group number in a rule:

table inet filter {
    chain INPUT {
        type filter hook input priority 0; policy drop;
        # Log all
        counter packets 0 bytes 0 log group 1 prefix "input drop"
    }
}

you can see these logs with ulogd default syslog config.

Is this correct way to listen on nftables ULOG rule logs?

fd, err := unix.Socket(syscall.AF_NETLINK, syscall.SOCK_RAW, unix.NFNL_SUBSYS_ULOG)
if err != nil {
    panic(fmt.Errorf(`socket: %w`, err))
}

err = unix.Bind(fd, &unix.SockaddrNetlink{
    Family: unix.NFNL_SUBSYS_ULOG,
    Groups: 1, // ?? Rule group?
    Pid:    0,
})
if err != nil {
    panic(fmt.Errorf(`bind: %w`, err))
}

buffer := make([]byte, os.Getpagesize())

for {
    for {
        // Peek for new messages
        n, _, err := unix.Recvfrom(fd, buffer, unix.MSG_PEEK)
        if err != nil {
            log.Printf(`could not peek: %v`, err)
            continue
        }

        if n == 0 {
            continue
        }

        if n < len(buffer) {
            // We have new message(s), break loop and handle them
            break
        }

        // Make buffer larger if needed
        buffer = make([]byte, len(buffer)*2)
    }

    // Read out all available messages
    n, _, err := unix.Recvfrom(fd, buffer, 0)
    if err != nil {
        log.Printf(`could not read messages: %v`, err)
        continue
    }

    if n == 0 {
        // Data length is zero, so go back to peeking new messages
        continue
    }

    msgs, err := syscall.ParseNetlinkMessage(buffer[:n])
    if err != nil {
        log.Printf(`could not parse message: %v`, err)
        continue
    }

    for _, msg := range msgs {
        // Hex dump
        spew.Dump(msg)
        fmt.Println(strings.Repeat("-", 80))
    }
}

Are these correct parameters on unix.Socket(...) and unix.Bind(..)? When data arrives from the kernel is the syscall.ParseNetlinkMessage() the correct way? Since changing almost any of the mentioned types the kernel message(s) also change radically since then you might be listening on wrong packet type.

I tried to read ulogd source but couldn't figure out if I have the correct parameters.

raspi
  • 5,962
  • 3
  • 34
  • 51

0 Answers0