conntrack

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Jan 24, 2023 License: MIT Imports: 13 Imported by: 16

README

go-conntrack PkgGoDev Go Report Card Go

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

Example

func main() {
	nfct, err := ct.Open(&ct.Config{})
	if err != nil {
		fmt.Println("could not create nfct:", err)
		return
	}
    defer nfct.Close()

    // Get all IPv4 entries of the expected table.
	sessions, err := nfct.Dump(ct.Expected, ct.IPv4)
	if err != nil {
		fmt.Println("could not dump sessions:", err)
		return
	}

    // Print out all expected sessions.
	for _, session := range sessions {
		fmt.Printf("%#v\n", session)
	}
}

Requirements

Documentation

Overview

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

Example:

package main
import (
	"fmt"
	ct "github.com/florianl/go-conntrack"
)
func main(){
	nfct, err := ct.Open(&ct.Config{})
	if err != nil {
		fmt.Println("Could not create nfct:", err)
		return
	}
	defer nfct.Close()
	sessions, err := nfct.Dump(ct.Conntrack, ct.IPv4)
	if err != nil {
		fmt.Println("Could not dump sessions:", err)
		return
	}
	for _, session := range sessions {
		fmt.Printf("[%2d] %s - %s\n", session.Origin.Proto.Number, session.Origin.Src, session.Origin.Dst)
	}
}

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

This section is empty.

Variables

View Source
var (
	ErrFilterLength                  = errors.New("number of filtering instructions are too high")
	ErrFilterAttributeLength         = errors.New("incorrect length of filter attribute")
	ErrFilterAttributeMaskLength     = errors.New("incorrect length of filter mask")
	ErrFilterAttributeNotImplemented = errors.New("filter attribute not implemented")
	ErrFilterAttributeNegateMix      = errors.New("can not mix negation for attribute of the same type")
)

Various errors which may occur when processing filters

View Source
var (
	ErrAttrLength         = errors.New("incorrect length of attribute")
	ErrAttrNotImplemented = errors.New("attribute not implemented")
	ErrAttrNotExist       = errors.New("type of attribute does not exist")
	ErrDataLength         = errors.New("incorrect length of provided data")
)

Various errors which may occur when processing attributes

View Source
var (
	ErrFilterAttrLength = errors.New("incorrect length of filter attribute")
)

Error which may occur when processing the filter attribute

View Source
var ErrUnknownCtTable = errors.New("not supported for this subsystem")

ErrUnknownCtTable will be return, if the function can not be performed on this subsystem

Functions

This section is empty.

Types

type CPUStat added in v0.2.0

type CPUStat struct {
	// ID of the CPU
	ID uint32

	// Values from the conntrack table
	Found         *uint32
	Invalid       *uint32
	Ignore        *uint32
	Insert        *uint32
	InsertFailed  *uint32
	Drop          *uint32
	EarlyDrop     *uint32
	Error         *uint32
	SearchRestart *uint32

	// Values from the expect table
	ExpNew    *uint32
	ExpCreate *uint32
	ExpDelete *uint32
}

CPUStat contains various conntrack related per CPU statistics

type Con added in v0.2.0

type Con struct {
	Info *InfoSource

	Origin        *IPTuple
	Reply         *IPTuple
	ProtoInfo     *ProtoInfo
	CounterOrigin *Counter
	CounterReply  *Counter
	Helper        *Helper
	NatSrc        *Nat
	SeqAdjOrig    *SeqAdj
	SeqAdjRepl    *SeqAdj
	ID            *uint32
	Status        *uint32
	StatusMask    *uint32
	Use           *uint32
	Mark          *uint32
	MarkMask      *uint32
	Timeout       *uint32
	Zone          *uint16
	Timestamp     *Timestamp
	SecCtx        *SecCtx
	Exp           *Exp
}

Con contains all the information of a connection

func ParseAttributes

func ParseAttributes(logger *log.Logger, data []byte) (Con, error)

ParseAttributes extracts all the attributes from the given data

type Config added in v0.2.0

type Config struct {
	// NetNS specifies the network namespace the Conn will operate in.
	//
	// If set (non-zero), Conn will enter the specified network namespace and
	// an error will occur in Dial if the operation fails.
	//
	// If not set (zero), a best-effort attempt will be made to enter the
	// network namespace of the calling thread: this means that any changes made
	// to the calling thread's network namespace will also be reflected in Conn.
	// If this operation fails (due to lack of permissions or because network
	// namespaces are disabled by kernel configuration), Dial will not return
	// an error, and the Conn will operate in the default network namespace of
	// the process. This enables non-privileged use of Conn in applications
	// which do not require elevated privileges.
	NetNS int

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

	// Time till a write action times out - only available for Go >= 1.12
	WriteTimeout time.Duration

	// Interface to log internals.
	Logger *log.Logger

	// DisableNSLockThread disables package netlink's default goroutine thread
	// locking behavior.
	//
	// By default, the library will lock the processing goroutine to its
	// corresponding OS thread in order to enable communication over netlink to
	// a different network namespace.
	//
	// If the caller already knows that the netlink socket is in the same
	// namespace as the calling thread, this can introduce a performance
	// impact. This option disables the OS thread locking behavior if
	// performance considerations are of interest.
	//
	// If disabled, it is the responsibility of the caller to make sure that all
	// threads are running in the correct namespace.
	//
	// When DisableNSLockThread is set, the caller cannot set the NetNS value.
	DisableNSLockThread bool

	// AddConntrackInformation enriches Con and provides additional information of
	// the Netlink/Conntrack origin.
	AddConntrackInformation bool
}

Config contains options for a Conn.

type ConnAttr

type ConnAttr struct {
	Type ConnAttrType
	Data []byte
	// Mask is required for specific attributes, if you want to filter for them
	Mask []byte
	// Negates this attribute for filtering
	Negate bool
}

ConnAttr represents the type and value of a attribute of a connection

func (ConnAttr) String added in v0.2.0

func (ca ConnAttr) String() string

type ConnAttrType

type ConnAttrType uint16

ConnAttrType specifies the attribute of a connection

const (
	AttrOrigIPv4Src             ConnAttrType = iota /* u32 bits, requires a mask if applied as filter */
	AttrOrigIPv4Dst             ConnAttrType = iota /* u32 bits, requires a mask if applied as filter */
	AttrReplIPv4Src             ConnAttrType = iota /* u32 bits, requires a mask if applied as filter */
	AttrReplIPv4Dst             ConnAttrType = iota /* u32 bits, requires a mask if applied as filter */
	AttrOrigIPv6Src             ConnAttrType = iota /* u128 bits */
	AttrOrigIPv6Dst             ConnAttrType = iota /* u128 bits */
	AttrReplIPv6Src             ConnAttrType = iota /* u128 bits */
	AttrReplIPv6Dst             ConnAttrType = iota /* u128 bits */
	AttrOrigPortSrc             ConnAttrType = iota /* u16 bits */
	AttrOrigPortDst             ConnAttrType = iota /* u16 bits */
	AttrReplPortSrc             ConnAttrType = iota /* u16 bits */
	AttrReplPortDst             ConnAttrType = iota /* u16 bits */
	AttrIcmpType                ConnAttrType = iota /* u8 bits */
	AttrIcmpCode                ConnAttrType = iota /* u8 bits */
	AttrIcmpID                  ConnAttrType = iota /* u16 bits */
	AttrOrigL3Proto             ConnAttrType = iota /* u8 bits */
	AttrReplL3Proto             ConnAttrType = iota /* u8 bits */
	AttrOrigL4Proto             ConnAttrType = iota /* u8 bits */
	AttrReplL4Proto             ConnAttrType = iota /* u8 bits */
	AttrTCPState                ConnAttrType = iota /* u8 bits */
	AttrSNatIPv4                ConnAttrType = iota /* u32 bits */
	AttrDNatIPv4                ConnAttrType = iota /* u32 bits */
	AttrSNatPort                ConnAttrType = iota /* u16 bits */
	AttrDNatPort                ConnAttrType = iota /* u16 bits */
	AttrTimeout                 ConnAttrType = iota /* u32 bits */
	AttrMark                    ConnAttrType = iota /* u32 bits, requires a mask if applied as filter */
	AttrMarkMask                ConnAttrType = iota /* u32 bits */
	AttrOrigCounterPackets      ConnAttrType = iota /* u64 bits */
	AttrReplCounterPackets      ConnAttrType = iota /* u64 bits */
	AttrOrigCounterBytes        ConnAttrType = iota /* u64 bits */
	AttrReplCounterBytes        ConnAttrType = iota /* u64 bits */
	AttrUse                     ConnAttrType = iota /* u32 bits */
	AttrID                      ConnAttrType = iota /* u32 bits */
	AttrStatus                  ConnAttrType = iota /* u32 bits  */
	AttrTCPFlagsOrig            ConnAttrType = iota /* u8 bits */
	AttrTCPFlagsRepl            ConnAttrType = iota /* u8 bits */
	AttrTCPMaskOrig             ConnAttrType = iota /* u8 bits */
	AttrTCPMaskRepl             ConnAttrType = iota /* u8 bits */
	AttrMasterIPv4Src           ConnAttrType = iota /* u32 bits */
	AttrMasterIPv4Dst           ConnAttrType = iota /* u32 bits */
	AttrMasterIPv6Src           ConnAttrType = iota /* u128 bits */
	AttrMasterIPv6Dst           ConnAttrType = iota /* u128 bits */
	AttrMasterPortSrc           ConnAttrType = iota /* u16 bits */
	AttrMasterPortDst           ConnAttrType = iota /* u16 bits */
	AttrMasterL3Proto           ConnAttrType = iota /* u8 bits */
	AttrMasterL4Proto           ConnAttrType = iota /* u8 bits */
	AttrSecmark                 ConnAttrType = iota /* u32 bits */
	AttrOrigNatSeqCorrectionPos ConnAttrType = iota /* u32 bits */
	AttrOrigNatSeqOffsetBefore  ConnAttrType = iota /* u32 bits */
	AttrOrigNatSeqOffsetAfter   ConnAttrType = iota /* u32 bits */
	AttrReplNatSeqCorrectionPos ConnAttrType = iota /* u32 bits */
	AttrReplNatSeqOffsetBefore  ConnAttrType = iota /* u32 bits */
	AttrReplNatSeqOffsetAfter   ConnAttrType = iota /* u32 bits */
	AttrSctpState               ConnAttrType = iota /* u8 bits */
	AttrSctpVtagOrig            ConnAttrType = iota /* u32 bits */
	AttrSctpVtagRepl            ConnAttrType = iota /* u32 bits */
	AttrHelperName              ConnAttrType = iota /* string (30 bytes max) */
	AttrDccpState               ConnAttrType = iota /* u8 bits */
	AttrDccpRole                ConnAttrType = iota /* u8 bits */
	AttrDccpHandshakeSeq        ConnAttrType = iota /* u64 bits */
	AttrTCPWScaleOrig           ConnAttrType = iota /* u8 bits */
	AttrTCPWScaleRepl           ConnAttrType = iota /* u8 bits */
	AttrZone                    ConnAttrType = iota /* u16 bits */
	AttrSecCtx                  ConnAttrType = iota /* string */
	AttrTimestampStart          ConnAttrType = iota /* u64 bits linux >= 2.6.38 */
	AttrTimestampStop           ConnAttrType = iota /* u64 bits linux >= 2.6.38 */
	AttrHelperInfo              ConnAttrType = iota /* variable length */
	AttrConnlabels              ConnAttrType = iota /* variable length */
	AttrConnlabelsMask          ConnAttrType = iota /* variable length */
	AttrOrigzone                ConnAttrType = iota /* u16 bits */
	AttrReplzone                ConnAttrType = iota /* u16 bits */
	AttrSNatIPv6                ConnAttrType = iota /* u128 bits */
	AttrDNatIPv6                ConnAttrType = iota /* u128 bits */

	AttrIcmpv6Type ConnAttrType = iota /* u8 bits */
	AttrIcmpv6Code ConnAttrType = iota /* u8 bits */
	AttrIcmpv6ID   ConnAttrType = iota /* u16 bits */

	AttrExpID     ConnAttrType = iota /* u32 bits */
	AttrExpFlags  ConnAttrType = iota /* u32 bits */
	AttrExpClass  ConnAttrType = iota /* u32 bits */
	AttrExpNATDir ConnAttrType = iota /* u32 bits */

)

Attributes of a connection based on libnetfilter_conntrack.h

type Counter added in v0.2.0

type Counter struct {
	Packets   *uint64
	Bytes     *uint64
	Packets32 *uint32
	Bytes32   *uint32
}

Counter contains additional information about the traffic

type DCCPInfo added in v0.2.0

type DCCPInfo struct {
	State        *uint8
	Role         *uint8
	HandshakeSeq *uint64
}

DCCPInfo contains additional information for DCCP sessions

type ErrMsg

type ErrMsg struct {
	Code  int
	Len   uint32
	Type  uint16
	Flags uint16
	Seq   uint32
	Pid   uint32
}

ErrMsg as defined in nlmsgerr

type Exp added in v0.2.0

type Exp struct {
	Master     *IPTuple
	Tuple      *IPTuple
	Mask       *IPTuple
	Flags      *uint32
	Class      *uint32
	ID         *uint32
	Timeout    *uint32
	Zone       *uint16
	HelperName *string
	Fn         *string
	Nat        *NatInfo
}

Exp extends the information of a connection by information from the expected table

type Family added in v0.2.0

type Family uint8

Family specifies the network family

const (
	IPv6 Family = unix.AF_INET6
	IPv4 Family = unix.AF_INET
)

Supported family types

type FilterAttr

type FilterAttr struct {
	Mark, MarkMask []byte
}

FilterAttr represents a very basic filter

type Helper added in v0.2.0

type Helper struct {
	Name *string
	Info *string
}

Helper contains additional information

type HookFunc

type HookFunc func(c Con) int

HookFunc is a function, that receives events from a Netlinkgroup. Return something different than 0, to stop receiving messages.

type IPTuple added in v0.2.0

type IPTuple struct {
	Src   *net.IP
	Dst   *net.IP
	Proto *ProtoTuple
	Zone  *uint16
}

IPTuple contains the source and destination IP

type InfoSource added in v0.4.0

type InfoSource struct {
	// Conntrack table this information originates from.
	Table Table

	// NetlinkGroup this information originates from.
	NetlinkGroup NetlinkGroup
}

InfoSource provides further information from Netlink about a connection.

type Nat added in v0.4.0

type Nat struct {
	IPMin *net.IP
	IPMax *net.IP
	Proto *ProtoTuple
}

Nat contains information for source/destination NAT

type NatInfo added in v0.2.0

type NatInfo struct {
	Dir   *uint32
	Tuple *IPTuple
}

NatInfo contains addition NAT information of a connection

type NetlinkGroup

type NetlinkGroup uint32

NetlinkGroup represents a Netlink multicast group

const (
	NetlinkCtNew             NetlinkGroup = 1 << iota
	NetlinkCtUpdate          NetlinkGroup = 1 << iota
	NetlinkCtDestroy         NetlinkGroup = 1 << iota
	NetlinkCtExpectedNew     NetlinkGroup = 1 << iota
	NetlinkCtExpectedUpdate  NetlinkGroup = 1 << iota
	NetlinkCtExpectedDestroy NetlinkGroup = 1 << iota
)

Supported Netlink groups

type Nfct

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

Nfct represents a conntrack handler

func Open

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

Open a connection to the conntrack subsystem

func (*Nfct) AttachErrChan added in v0.2.0

func (nfct *Nfct) AttachErrChan() <-chan error

AttachErrChan creates and attaches an error channel to the Nfct object. If an unexpected error is received this error will be reported via this channel. A call of (*Nfct).Close() will also close this channel.

func (*Nfct) Close

func (nfct *Nfct) Close() error

Close the connection to the conntrack subsystem.

func (*Nfct) Create

func (nfct *Nfct) Create(t Table, f Family, attributes Con) error

Create a new entry in the conntrack subsystem with certain attributes

func (*Nfct) Delete

func (nfct *Nfct) Delete(t Table, f Family, filters Con) error

Delete elements from the conntrack subsystem with certain attributes

func (*Nfct) Dump

func (nfct *Nfct) Dump(t Table, f Family) ([]Con, error)

Dump a conntrack subsystem

Example
package main

import (
	"fmt"

	ct "github.com/florianl/go-conntrack"
)

func main() {
	nfct, err := ct.Open(&ct.Config{})
	if err != nil {
		fmt.Println("could not create nfct:", err)
		return
	}
	defer nfct.Close()
	sessions, err := nfct.Dump(ct.Expected, ct.IPv4)
	if err != nil {
		fmt.Println("could not dump sessions:", err)
		return
	}

	for _, session := range sessions {
		fmt.Printf("%#v\n", session)
	}
}
Output:

func (*Nfct) DumpCPUStats

func (nfct *Nfct) DumpCPUStats(t Table) ([]CPUStat, error)

DumpCPUStats dumps per CPU statistics

Example
package main

import (
	"fmt"

	ct "github.com/florianl/go-conntrack"
)

func main() {
	nfct, err := ct.Open(&ct.Config{})
	if err != nil {
		fmt.Println("could not create nfct:", err)
		return
	}
	defer nfct.Close()
	stats, err := nfct.DumpCPUStats(ct.Conntrack)
	if err != nil {
		fmt.Println("could not dump CPU stats:", err)
		return
	}

	fmt.Printf("ID\tIgnore\tInvalid\tError\n")
	for _, stat := range stats {
		fmt.Printf("%2d\t%4d\t%4d\t%4d\n", stat.ID, *stat.Ignore, *stat.Invalid, *stat.Error)
	}
}
Output:

func (*Nfct) Flush

func (nfct *Nfct) Flush(t Table, f Family) error

Flush a conntrack subsystem

func (*Nfct) Get

func (nfct *Nfct) Get(t Table, f Family, match Con) ([]Con, error)

Get returns matching conntrack entries with certain attributes

func (*Nfct) Query

func (nfct *Nfct) Query(t Table, f Family, filter FilterAttr) ([]Con, error)

Query conntrack subsystem with certain attributes

func (*Nfct) Register

func (nfct *Nfct) Register(ctx context.Context, t Table, group NetlinkGroup, fn HookFunc) error

Register your function to receive events from a Netlinkgroup. If an unexpected error is received it will stop from processing further events. If your function returns something different than 0, it will stop.

Example
package main

import (
	"context"
	"fmt"
	"time"

	ct "github.com/florianl/go-conntrack"
)

func main() {
	nfct, err := ct.Open(&ct.Config{})
	if err != nil {
		fmt.Println("could not create nfct:", err)
		return
	}
	defer nfct.Close()

	monitor := func(c ct.Con) int {
		fmt.Printf("%#v\n", c)
		return 0
	}

	if err := nfct.Register(context.Background(), ct.Expected, ct.NetlinkCtExpectedNew|ct.NetlinkCtExpectedUpdate|ct.NetlinkCtExpectedDestroy, monitor); err != nil {
		fmt.Println("could not register callback:", err)
		return
	}

	time.Sleep(10 * time.Second)

}
Output:

func (*Nfct) RegisterFiltered

func (nfct *Nfct) RegisterFiltered(ctx context.Context, t Table, group NetlinkGroup, filter []ConnAttr, fn HookFunc) error

RegisterFiltered registers your function to receive events from a Netlinkgroup and applies a filter. If an unexpected error is received it will stop from processing further events. If your function returns something different than 0, it will stop. ConnAttr of the same ConnAttrType will be linked by an OR operation. Otherwise, ConnAttr of different ConnAttrType will be connected by an AND operation for the filter.

func (*Nfct) Update

func (nfct *Nfct) Update(t Table, f Family, attributes Con) error

Update an existing conntrack entry

type ProtoInfo added in v0.2.0

type ProtoInfo struct {
	TCP  *TCPInfo
	DCCP *DCCPInfo
	SCTP *SCTPInfo
}

ProtoInfo contains additional information to certain protocols

type ProtoTuple added in v0.2.0

type ProtoTuple struct {
	Number     *uint8
	SrcPort    *uint16
	DstPort    *uint16
	IcmpID     *uint16
	IcmpType   *uint8
	IcmpCode   *uint8
	Icmpv6ID   *uint16
	Icmpv6Type *uint8
	Icmpv6Code *uint8
}

ProtoTuple contains information about the used protocol

type SCTPInfo added in v0.2.0

type SCTPInfo struct {
	State        *uint8
	VTagOriginal *uint32
	VTagReply    *uint32
}

SCTPInfo contains additional information for SCTP sessions

type SecCtx added in v0.2.0

type SecCtx struct {
	Name *string
}

SecCtx contains additional information about the security context

type SeqAdj added in v0.2.0

type SeqAdj struct {
	CorrectionPos *uint32
	OffsetBefore  *uint32
	OffsetAfter   *uint32
}

SeqAdj contains additional information about corrections

type TCPFlags added in v0.3.0

type TCPFlags struct {
	Flags *uint8
	Mask  *uint8
}

TCPFlags contains additional information for TCP flags

type TCPInfo added in v0.2.0

type TCPInfo struct {
	State      *uint8
	WScaleOrig *uint8
	WScaleRepl *uint8
	FlagsOrig  *TCPFlags
	FlagsReply *TCPFlags
}

TCPInfo contains additional information for TCP sessions

type Table added in v0.2.0

type Table int

Table specifies the subsystem of conntrack

const (
	// Conntrack is the default table containing a list of all tracked connections
	Conntrack Table = unix.NFNL_SUBSYS_CTNETLINK

	// Expected is a table containing information about related connections to existing ones
	Expected Table = unix.NFNL_SUBSYS_CTNETLINK_EXP
)

Supported conntrack subsystems

type Timestamp added in v0.2.0

type Timestamp struct {
	Start *time.Time
	Stop  *time.Time
}

Timestamp contains start and/or stop times

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