nflog

package module
v2.0.0-...-2fa747e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 24, 2025 License: MIT Imports: 11 Imported by: 0

README

go-nflog PkgGoDev Go Report Card Go

This is go-nflog and it is written in golang. It provides a C-binding free API to the netfilter based log subsystem of the Linux kernel.

Example

func main() {
	// Send outgoing pings to nflog group 100
	// # sudo iptables -I OUTPUT -p icmp -j NFLOG --nflog-group 100

	//Set configuration parameters
	config := nflog.Config{
		Group:       100,
		Copymode:    nflog.CopyPacket,
	}

	nf, err := nflog.Open(&config)
	if err != nil {
		fmt.Fprintln(os.Stderr, "could not open nflog socket:", err)
		return
	}
	defer nf.Close()

	// Avoid receiving ENOBUFS errors.
	if err := nf.SetOption(netlink.NoENOBUFS, true); err != nil {
		fmt.Fprintf(os.Stderr, "failed to set netlink option %v: %v",
			netlink.NoENOBUFS, err)
		return
	}

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// hook that is called for every received packet by the nflog group
	hook := func(attrs nflog.Attribute) int {
		// Just print out the payload of the nflog packet
		fmt.Fprintf(os.Stdout, "%#v\n", attrs.Payload)
		return 0
	}

	// errFunc that is called for every error on the registered hook
	errFunc := func(e error) int {
		// Just log the error and return 0 to continue receiving packets
		fmt.Fprintf(os.Stderr, "received error on hook: %v", e)
		return 0
	}

	// Register your function to listen on nflog group 100
	err = nf.RegisterWithErrorFunc(ctx, hook, errFunc)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to register hook function: %v", err)
		return
	}

	// Block till the context expires
	<-ctx.Done()
}

Privileges

This package processes information directly from the kernel and therefore it requires special privileges. You can provide this privileges by adjusting the CAP_NET_ADMIN capabilities.

	setcap 'cap_net_admin=+ep' /your/executable

For documentation and more examples please take a look at PkgGoDev

Requirements

Documentation

Overview

Package nflog provides an API to interact with the log subsystem of the netfilter family from the linux kernel.

This package processes information directly from the kernel and therefore it requires special privileges. You can provide this privileges by adjusting the CAP_NET_ADMIN capabilities.

setcap 'cap_net_admin=+ep' /your/executable

Index

Examples

Constants

View Source
const (
	// Available copy modes for Config.Copymode.
	CopyNone byte = 0x00
	CopyMeta byte = 0x01
	// Provides a complete copy of the packet in the Msg map.
	// But can be limited by setting Config.Bufsize.
	CopyPacket byte = 0x02

	// Flags that can be set on a connection
	FlagSeq    uint16 = 0x0001
	FlagGlobal uint16 = 0x0002
	// Requires Kernel configuration of CONFIG_NETFILTER_NETLINK_GLUE_CT
	FlagConntrack uint16 = 0x0004
)

Various constants

View Source
const (
	GenericGroup uint16 = 0x1
)

Various optional settings

Variables

View Source
var (
	ErrCopyMode    = errors.New("unsupported copy mode")
	ErrUnknownFlag = errors.New("unsupported flag")
)

Various errors

Functions

This section is empty.

Types

type Attribute

type Attribute struct {
	Hook       *uint8
	Mark       *uint32
	Timestamp  *time.Time
	InDev      *uint32
	PhysInDev  *uint32
	OutDev     *uint32
	PhysOutDev *uint32
	Payload    *[]byte
	Prefix     *string
	UID        *uint32
	Seq        *uint32
	SeqGlobal  *uint32
	GID        *uint32
	HwType     *uint16
	HwAddr     *[]byte
	HwHeader   *[]byte
	HwLen      *uint16
	HwProtocol *uint16
	CtInfo     *uint32
	Ct         *[]byte
	Layer2Hdr  *[]byte
	VLAN       *VLAN
}

Attribute contains various elements for nflog elements. As not every value is contained in every nflog message, the elements inside Attribute are pointers to these values or nil, if not present.

type Config

type Config struct {
	// Network namespace the Nflog needs to operate in. If set to 0 (default),
	// no network namespace will be entered.
	NetNS int

	// Optional flags for the nflog communication
	Flags uint16

	// Specifies the number of packets in the group,
	// until they will be pushed to userspace.
	QThresh uint32

	// Maximum time in 1/100s that a packet in the nflog group will be queued,
	// until it is pushed to userspace.
	Timeout uint32

	// Nflog group this socket will be assigned to.
	Group uint16

	// Specifies how the kernel handles a packet in the nflog group.
	Copymode uint8

	// If NfUlnlCopyPacket is set as CopyMode,
	// this parameter specifies the maximum number of bytes,
	// that will be copied to userspace.
	Bufsize uint32

	// Optional settings to enable/disable features
	Settings uint16

	// Time till a read action times out - only available for Go >= 1.12
	//
	// Deprecated: Cancel the context passed to RegisterWithErrorFunc() or Register()
	// to remove the hook from the nfloq gracefully. Setting this value does no longer
	// have an effect on nflog.
	ReadTimeout time.Duration

	// Interface to log internals.
	Logger Logger
}

Config contains options for a Conn.

type ErrorFunc

type ErrorFunc func(e error) int

ErrorFunc is a function that receives all errors that happen while reading from a Netlinkgroup. To stop receiving messages return something different than 0.

type HookFunc

type HookFunc func(a Attribute) int

HookFunc is a function, that receives events from a Netlinkgroup To stop receiving messages on this HookFunc, return something different than 0

type Logger

type Logger interface {
	Debugf(format string, args ...interface{})
	Errorf(format string, args ...interface{})
}

Logger provides logging functionality.

type Nflog

type Nflog struct {
	// Con is the pure representation of a netlink socket
	Con *netlink.Conn
	// contains filtered or unexported fields
}

Nflog represents a netfilter log handler

func Open

func Open(config *Config) (*Nflog, error)

Open a connection to the netfilter log subsystem

func (*Nflog) Close

func (nflog *Nflog) Close() error

Close the connection to the netfilter log subsystem

func (*Nflog) Register deprecated

func (nflog *Nflog) Register(ctx context.Context, fn HookFunc) error

Register your own function as callback for a netfilter log group. Errors other than net.Timeout() will be reported via the provided log interface and the receiving of netfilter log messages will be stopped.

To handle errors and continue receiving data with the registered callback use RegisterWithErrorFunc() instead.

Deprecated: Use RegisterWithErrorFunc() instead.

Example
// Send outgoing pings to nflog group 100
// # sudo iptables -I OUTPUT -p icmp -j NFLOG --nflog-group 100

// Set configuration parameters
config := nflog.Config{
	Group:    100,
	Copymode: nflog.CopyPacket,
}

nf, err := nflog.Open(&config)
if err != nil {
	fmt.Println("could not open nflog socket:", err)
	return
}
defer nf.Close()

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

// hook that is called for every received packet by the nflog group
hook := func(attrs nflog.Attribute) int {
	// Just print out the payload of the nflog packet
	fmt.Fprintf(os.Stdout, "%#v\n", attrs.Payload)
	return 0
}

// errFunc that is called for every error on the registered hook
errFunc := func(e error) int {
	// Just log the error and return 0 to continue receiving packets
	fmt.Fprintf(os.Stderr, "received error on hook: %v", e)
	return 0
}

// Register your function to listen on nflog group 100
err = nf.RegisterWithErrorFunc(ctx, hook, errFunc)
if err != nil {
	fmt.Fprintf(os.Stderr, "failed to register hook function: %v", err)
	return
}

// Block till the context expires
<-ctx.Done()
Output:

func (*Nflog) RegisterWithErrorFunc

func (nflog *Nflog) RegisterWithErrorFunc(ctx context.Context, fn HookFunc, errfn ErrorFunc) error

RegisterWithErrorFunc attaches a callback function to a callback to a netfilter log group and allows custom error handling for errors encountered when reading from the underlying netlink socket.

func (*Nflog) SetOption

func (nflog *Nflog) SetOption(o netlink.ConnOption, enable bool) error

SetOption allows to enable or disable netlink socket options.

type VLAN

type VLAN struct {
	Proto uint16
	TCI   uint16
}

VLAN holds the VLAN information.

Directories

Path Synopsis
internal
unix
Package unix maps constants from golang.org/x/sys/unix to local constants and makes them available for other platforms as well.
Package unix maps constants from golang.org/x/sys/unix to local constants and makes them available for other platforms as well.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL