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 ¶
- Variables
- type CPUStat
- type Con
- type Config
- type ConnAttr
- type ConnAttrType
- type Counter
- type DCCPInfo
- type ErrMsg
- type Exp
- type Family
- type FilterAttr
- type Helper
- type HookFunc
- type IPTuple
- type InfoSource
- type Nat
- type NatInfo
- type NetlinkGroup
- type Nfct
- func (nfct *Nfct) AttachErrChan() <-chan error
- func (nfct *Nfct) Close() error
- func (nfct *Nfct) Create(t Table, f Family, attributes Con) error
- func (nfct *Nfct) Delete(t Table, f Family, filters Con) error
- func (nfct *Nfct) Dump(t Table, f Family) ([]Con, error)
- func (nfct *Nfct) DumpCPUStats(t Table) ([]CPUStat, error)
- func (nfct *Nfct) Flush(t Table, f Family) error
- func (nfct *Nfct) Get(t Table, f Family, match Con) ([]Con, error)
- func (nfct *Nfct) Query(t Table, f Family, filter FilterAttr) ([]Con, error)
- func (nfct *Nfct) Register(ctx context.Context, t Table, group NetlinkGroup, fn HookFunc) error
- func (nfct *Nfct) RegisterFiltered(ctx context.Context, t Table, group NetlinkGroup, filter []ConnAttr, ...) error
- func (nfct *Nfct) Update(t Table, f Family, attributes Con) error
- type ProtoInfo
- type ProtoTuple
- type SCTPInfo
- type SecCtx
- type SeqAdj
- type TCPFlags
- type TCPInfo
- type Table
- type Timestamp
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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
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
var (
ErrFilterAttrLength = errors.New("incorrect length of filter attribute")
)
Error which may occur when processing the filter attribute
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
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
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 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 FilterAttr ¶
type FilterAttr struct {
Mark, MarkMask []byte
}
FilterAttr represents a very basic filter
type HookFunc ¶
HookFunc is a function, that receives events from a Netlinkgroup. Return something different than 0, to stop receiving messages.
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 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 (*Nfct) AttachErrChan ¶ added in v0.2.0
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) Dump ¶
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 ¶
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) Register ¶
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.
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 SecCtx ¶ added in v0.2.0
type SecCtx struct {
Name *string
}
SecCtx contains additional information about the security context
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