ipset

package module
Version: v0.0.0-...-ae3e85b Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2021 License: Apache-2.0 Imports: 14 Imported by: 0

README

ipset-go - ipset library for go

GoDoc

The ipset-go package provides a simple ipset library for go. IP sets are a framework inside the Linux kernel, which can be administered by the ipset utility. Depending on the type, an IP set may store IP addresses, networks, (TCP/UDP) port numbers, MAC addresses, interface names or combinations of them in a way, which ensures lightning speed when matching an entry against a set.This library began its life as a fork of the vishvananda/netlink.

Examples

Create a new set and add 10.0.0.1 into it:

package main

import (
	"log"
	"net"

	"github.com/lrh3321/ipset-go"
)

func main() {
	var setname = "hash01"
	err := ipset.Create(setname, ipset.TypeHashIP, ipset.CreateOptions{})
	if err != nil {
		log.Fatal(err)
	}

	err = ipset.Add(setname, &ipset.Entry{IP: net.IPv4(10, 0, 0, 1).To4()})
	if err != nil {
		log.Fatal(err)
	}
}

Destroy a set:

package main

import (
	"log"
	"net"

	"github.com/lrh3321/ipset-go"
)

func main() {
	var setname = "hash01"
	err := ipset.Destroy(setname)
	if err != nil {
		log.Fatal(err)
	}
}

Documentation

Index

Examples

Constants

View Source
const (
	IPSET_ERR_PRIVATE = 4096 + iota
	IPSET_ERR_PROTOCOL
	IPSET_ERR_FIND_TYPE
	IPSET_ERR_MAX_SETS
	IPSET_ERR_BUSY
	IPSET_ERR_EXIST_SETNAME2
	IPSET_ERR_TYPE_MISMATCH
	IPSET_ERR_EXIST
	IPSET_ERR_INVALID_CIDR
	IPSET_ERR_INVALID_NETMASK
	IPSET_ERR_INVALID_FAMILY
	IPSET_ERR_TIMEOUT
	IPSET_ERR_REFERENCED
	IPSET_ERR_IPADDR_IPV4
	IPSET_ERR_IPADDR_IPV6
	IPSET_ERR_COUNTER
	IPSET_ERR_COMMENT
	IPSET_ERR_INVALID_MARKMASK
	IPSET_ERR_SKBINFO

	/* Type specific error codes */
	IPSET_ERR_TYPE_SPECIFIC = 4352
)
View Source
const (
	/* The element is out of the range of the set */
	IPSET_ERR_BITMAP_RANGE = IPSET_ERR_TYPE_SPECIFIC + 1 + iota
	/* The range exceeds the size limit of the set type */
	IPSET_ERR_BITMAP_RANGE_SIZE
)

Bitmap type specific error codes

View Source
const (
	/* Hash is full */
	IPSET_ERR_HASH_FULL = IPSET_ERR_TYPE_SPECIFIC + 1 + iota
	/* Null-valued element */
	IPSET_ERR_HASH_ELEM
	/* Invalid protocol */
	IPSET_ERR_INVALID_PROTO
	/* Protocol missing but must be specified */
	IPSET_ERR_MISSING_PROTO
	/* Range not supported */
	IPSET_ERR_HASH_RANGE_UNSUPPORTED
	/* Invalid range */
	IPSET_ERR_HASH_RANGE
)

Hash type specific error codes

View Source
const (
	/* list:set type is not permitted to add */
	IPSET_ERR_LOOP = IPSET_ERR_TYPE_SPECIFIC + 1 + iota
	/* Missing reference set */
	IPSET_ERR_BEFORE
	/* Reference set does not exist */
	IPSET_ERR_NAMEREF
	/* Set is full */
	IPSET_ERR_LIST_FULL
	/* Reference set is not added to the set */
	IPSET_ERR_REF_EXIST
)

List type specific error codes

View Source
const (
	// ErrSetNotExist The set with the given name does not exist
	ErrSetNotExist = IPSetError(syscall.ENOENT)
	// ErrInvalidMessage Kernel error received: message could not be created
	ErrInvalidMessage = IPSetError(syscall.EMSGSIZE)
	// ErrInvalidProtocol Kernel error received: ipset protocol error
	ErrInvalidProtocol = IPSetError(IPSET_ERR_PROTOCOL)
)

Generic error codes

View Source
const (
	// ErrInvalidCIDR The value of the CIDR parameter of the IP address is invalid
	ErrInvalidCIDR = IPSetError(IPSET_ERR_INVALID_CIDR)
	// ErrTimeout Timeout cannot be used: set was created without timeout support
	ErrTimeout = IPSetError(IPSET_ERR_TIMEOUT)
	// ErrInvalidIPv4Address An IPv4 address is expected, but not received
	ErrInvalidIPv4Address = IPSetError(IPSET_ERR_IPADDR_IPV4)
	// ErrInvalidIPv6Address An IPv6 address is expected, but not received
	ErrInvalidIPv6Address = IPSetError(IPSET_ERR_IPADDR_IPV6)
	// ErrInvalidCounter Packet/byte counters cannot be used: set was created without counter support
	ErrInvalidCounter = IPSetError(IPSET_ERR_COUNTER)
	// ErrInvalidComment Comment cannot be used: set was created without comment support
	ErrInvalidComment = IPSetError(IPSET_ERR_COMMENT)
	// ErrSkbInfo Skbinfo mapping cannot be used: set was created without skbinfo support
	ErrSkbInfo = IPSetError(IPSET_ERR_SKBINFO)
)

Generic (CADT) error codes

View Source
const (
	// ErrSetExist Set cannot be created: set with the same name already exists
	ErrSetExist = IPSetError(syscall.EEXIST)
	// ErrInvalidType Kernel error received: set type not supported
	ErrInvalidType = IPSetError(IPSET_ERR_FIND_TYPE)
	// ErrTypeMaxSetsReached Kernel error received: maximal number of sets reached,
	// cannot create more.
	ErrTypeMaxSetsReached = IPSetError(IPSET_ERR_MAX_SETS)
	// ErrInvalidNetmask The value of the netmask parameter is invalid
	ErrInvalidNetmask = IPSetError(IPSET_ERR_INVALID_NETMASK)
	// ErrInvalidMarkmask The value of the markmask parameter is invalid
	ErrInvalidMarkmask = IPSetError(IPSET_ERR_INVALID_MARKMASK)
	// ErrInvalidFamily Protocol family not supported by the set type
	ErrInvalidFamily = IPSetError(IPSET_ERR_INVALID_FAMILY)
)

CREATE specific error codes

View Source
const (
	// ErrNewNameAlreadyExist Set cannot be renamed: a set with the new name already exists
	ErrNewNameAlreadyExist = IPSetError(IPSET_ERR_EXIST_SETNAME2)
	// ErrReferenced Set cannot be renamed: it is in use by another system
	ErrReferenced = IPSetError(IPSET_ERR_REFERENCED)
)

RENAME specific error codes

View Source
const (
	// ErrSecondSetNotExist Sets cannot be swapped: the second set does not exist
	ErrSecondSetNotExist = IPSetError(IPSET_ERR_EXIST_SETNAME2)
	// ErrTypeMismatch The sets cannot be swapped: their type does not match
	ErrTypeMismatch = IPSetError(IPSET_ERR_TYPE_MISMATCH)
)

SWAP specific error codes

View Source
const (
	TypeListSet = "list:set"

	TypeHashMac        = "hash:mac"
	TypeHashIPMac      = "hash:ip,mac"
	TypeHashNetIface   = "hash:net,iface"
	TypeHashNetPort    = "hash:net,port"
	TypeHashNetPortNet = "hash:net,port,net"
	TypeHashNetNet     = "hash:net,net"
	TypeHashNet        = "hash:net"
	TypeHashIPPortNet  = "hash:ip,port,net"
	TypeHashIPPortIP   = "hash:ip,port,ip"
	TypeHashIPMark     = "hash:ip,mark"
	TypeHashIPPort     = "hash:ip,port"
	TypeHashIP         = "hash:ip"

	TypeBitmapPort  = "bitmap:port"
	TypeBitmapIPMac = "bitmap:ip,mac"
	TypeBitmapIP    = "bitmap:ip"
)
View Source
const (
	/* The protocol version */
	IPSET_PROTOCOL = 6

	/* The max length of strings including NUL: set and type identifiers */
	IPSET_MAXNAMELEN = 32

	/* The maximum permissible comment length we will accept over netlink */
	IPSET_MAX_COMMENT_SIZE = 255
)
View Source
const (
	IPSET_CMD_PROTOCOL /* 1: Return protocol version */
	IPSET_CMD_CREATE   /* 2: Create a new (empty) set */
	IPSET_CMD_DESTROY  /* 3: Destroy a (empty) set */
	IPSET_CMD_FLUSH    /* 4: Remove all elements from a set */
	IPSET_CMD_RENAME   /* 5: Rename a set */
	IPSET_CMD_SWAP     /* 6: Swap two sets */
	IPSET_CMD_LIST     /* 7: List sets */
	IPSET_CMD_SAVE     /* 8: Save sets */
	IPSET_CMD_ADD      /* 9: Add an element to a set */
	IPSET_CMD_DEL      /* 10: Delete an element from a set */
	IPSET_CMD_TEST     /* 11: Test an element in a set */
	IPSET_CMD_HEADER   /* 12: Get set header data only */
	IPSET_CMD_TYPE     /* 13: Get set type */
)
View Source
const (
	IPSET_ATTR_PROTOCOL     /* 1: Protocol version */
	IPSET_ATTR_SETNAME      /* 2: Name of the set */
	IPSET_ATTR_TYPENAME     /* 3: Typename */
	IPSET_ATTR_REVISION     /* 4: Settype revision */
	IPSET_ATTR_FAMILY       /* 5: Settype family */
	IPSET_ATTR_FLAGS        /* 6: Flags at command level */
	IPSET_ATTR_DATA         /* 7: Nested attributes */
	IPSET_ATTR_ADT          /* 8: Multiple data containers */
	IPSET_ATTR_LINENO       /* 9: Restore lineno */
	IPSET_ATTR_PROTOCOL_MIN /* 10: Minimal supported version number */

	IPSET_ATTR_SETNAME2     = IPSET_ATTR_TYPENAME     /* Setname at rename/swap */
	IPSET_ATTR_REVISION_MIN = IPSET_ATTR_PROTOCOL_MIN /* type rev min */
)

Attributes at command level

View Source
const (
	IPSET_ATTR_IP          = 1
	IPSET_ATTR_IP_FROM     = 1
	IPSET_ATTR_IP_TO       = 2
	IPSET_ATTR_CIDR        = 3
	IPSET_ATTR_PORT        = 4
	IPSET_ATTR_PORT_FROM   = 4
	IPSET_ATTR_PORT_TO     = 5
	IPSET_ATTR_TIMEOUT     = 6
	IPSET_ATTR_PROTO       = 7
	IPSET_ATTR_CADT_FLAGS  = 8
	IPSET_ATTR_CADT_LINENO = IPSET_ATTR_LINENO /* 9 */
	IPSET_ATTR_MARK        = 10
	IPSET_ATTR_MARKMASK    = 11

	/* Reserve empty slots */
	IPSET_ATTR_CADT_MAX = 16

	/* Create-only specific attributes */
	IPSET_ATTR_GC = 3 + iota
	IPSET_ATTR_HASHSIZE
	IPSET_ATTR_MAXELEM
	IPSET_ATTR_NETMASK
	IPSET_ATTR_PROBES
	IPSET_ATTR_RESIZE
	IPSET_ATTR_SIZE

	/* Kernel-only */
	IPSET_ATTR_ELEMENTS
	IPSET_ATTR_REFERENCES
	IPSET_ATTR_MEMSIZE

	SET_ATTR_CREATE_MAX
)

CADT specific attributes

View Source
const (
	IPSET_ATTR_ETHER = IPSET_ATTR_CADT_MAX + iota + 1
	IPSET_ATTR_NAME
	IPSET_ATTR_NAMEREF
	IPSET_ATTR_IP2
	IPSET_ATTR_CIDR2
	IPSET_ATTR_IP2_TO
	IPSET_ATTR_IFACE
	IPSET_ATTR_BYTES
	IPSET_ATTR_PACKETS
	IPSET_ATTR_COMMENT
	IPSET_ATTR_SKBMARK
	IPSET_ATTR_SKBPRIO
	IPSET_ATTR_SKBQUEUE
)

ADT specific attributes

View Source
const (
	IPSET_FLAG_BIT_BEFORE        = 0
	IPSET_FLAG_BEFORE            = (1 << IPSET_FLAG_BIT_BEFORE)
	IPSET_FLAG_BIT_PHYSDEV       = 1
	IPSET_FLAG_PHYSDEV           = (1 << IPSET_FLAG_BIT_PHYSDEV)
	IPSET_FLAG_BIT_NOMATCH       = 2
	IPSET_FLAG_NOMATCH           = (1 << IPSET_FLAG_BIT_NOMATCH)
	IPSET_FLAG_BIT_WITH_COUNTERS = 3
	IPSET_FLAG_WITH_COUNTERS     = (1 << IPSET_FLAG_BIT_WITH_COUNTERS)
	IPSET_FLAG_BIT_WITH_COMMENT  = 4
	IPSET_FLAG_WITH_COMMENT      = (1 << IPSET_FLAG_BIT_WITH_COMMENT)
	IPSET_FLAG_BIT_WITH_FORCEADD = 5
	IPSET_FLAG_WITH_FORCEADD     = (1 << IPSET_FLAG_BIT_WITH_FORCEADD)
	IPSET_FLAG_BIT_WITH_SKBINFO  = 6
	IPSET_FLAG_WITH_SKBINFO      = (1 << IPSET_FLAG_BIT_WITH_SKBINFO)
	IPSET_FLAG_CADT_MAX          = 15
)

Flags at CADT attribute level, upper half of cmdattrs

View Source
const (
	FamilyUnspec = uint8(unix.AF_UNSPEC)
	// FamilyIPV4 represents IPv4 protocol.
	FamilyIPV4 = uint8(unix.AF_INET)
	// FamilyIPV6 represents IPv6 protocol.
	FamilyIPV6 = uint8(unix.AF_INET6)

	// ProtocolTCP represents TCP protocol.
	ProtocolTCP = uint16(unix.IPPROTO_TCP)
	// ProtocolUDP represents UDP protocol.
	ProtocolUDP = uint16(unix.IPPROTO_UDP)
	// ProtocolSCTP represents SCTP protocol.
	ProtocolSCTP = uint16(unix.IPPROTO_SCTP)
)
View Source
const (
	// ErrBusy Set cannot be destroyed: it is in use by a kernel component
	ErrBusy = IPSetError(IPSET_ERR_BUSY)
)

DESTROY specific error codes

View Source
const (
	// ErrEntryExist Element cannot be added to the set: it's already added
	ErrEntryExist = IPSetError(IPSET_ERR_EXIST)
)

ADD specific error codes

View Source
const (
	// ErrEntryNotExist Element cannot be deleted from the set: it's not added
	ErrEntryNotExist = IPSetError(IPSET_ERR_EXIST)
)

DEL specific error codes

Variables

This section is empty.

Functions

func Add

func Add(setname string, entry *Entry) error

Add adds an entry to an existing ipset.

func Create

func Create(setname, typename string, options CreateOptions) error

Create creates a new ipset

func Del

func Del(setname string, entry *Entry) error

Del deletes an entry from an existing ipset.

func Destroy

func Destroy(setname string) error

Destroy destroys an existing ipset

Example
var setname = "hash01"
err := Destroy(setname)
if err != nil {
	if os.IsNotExist(err) {
		fmt.Printf("no such set: %s\n", setname)
	} else {
		log.Fatal(err)
	}
}

// destroy a  not exist one
err = Destroy(setname + "2")
if err != nil {
	if os.IsNotExist(err) {
		fmt.Printf("no such set: %s\n", setname)
	} else {
		log.Fatal(err)
	}
}
Output:

no such set: hash012

func Flush

func Flush(setname string) error

Flush flushes an existing ipset

func ForceDestroy

func ForceDestroy(setname string) error

ForceDestroy destroys a ipset return nil if not exist

func GetCommandFlags

func GetCommandFlags(cmd int) int

func GetSocketTimeout

func GetSocketTimeout() time.Duration

GetSocketTimeout returns the timeout value used by default netlink sockets

func Protocol

func Protocol() (uint8, uint8, error)

Protocol returns the ipset protocol version from the kernel

func Rename

func Rename(from string, to string) error

Rename rename a set. Set identified by SETNAME-TO must not exist.

func SetSocketTimeout

func SetSocketTimeout(to time.Duration) error

SetSocketTimeout configures timeout for default netlink sockets

func Swap

func Swap(from string, to string) error

Swap swap the content of two sets, or in another words, exchange the name of two sets. The referred sets must exist and compatible type of sets can be swapped only.

func Uint16Ptr

func Uint16Ptr(v uint16) *uint16

func Uint32Ptr

func Uint32Ptr(v uint32) *uint32

func Uint8Ptr

func Uint8Ptr(v uint8) *uint8

Types

type CreateOptions

type CreateOptions struct {
	Family   uint8
	Protocol uint8
	Size     uint32 // size/hashsize

	Replace  bool // replace existing ipset
	Timeout  uint32
	Counters bool
	Comments bool
	Skbinfo  bool

	Revision uint8
	IPFrom   net.IP
	IPTo     net.IP
	NetMask  uint32
	PortFrom uint16
	PortTo   uint16
}

CreateOptions is the options struct for creating a new ipset

func (*CreateOptions) CadtFlags

func (opts *CreateOptions) CadtFlags() uint32

type Entry

type Entry struct {
	Name     string
	Comment  string
	MAC      net.HardwareAddr
	IP       net.IP
	CIDR     uint8
	Timeout  *uint32
	Packets  *uint64
	Bytes    *uint64
	Protocol *uint8
	Port     *uint16
	IP2      net.IP
	CIDR2    uint8
	IFace    string
	Mark     *uint32

	Replace bool // replace existing entry
}

Entry is used for adding, updating, retreiving and deleting entries

type Handle

type Handle struct {
	// contains filtered or unexported fields
}

Handle is an handle for the netlink requests on a specific network namespace. All the requests on the same netlink family share the same netlink socket, which gets released when the handle is deleted.

func HandleFromNetlinkHandle

func HandleFromNetlinkHandle(h *netlink.Handle) *Handle

func NewHandle

func NewHandle() (*Handle, error)

NewHandle returns a netlink handle on the current network namespace.

func NewHandleAt

func NewHandleAt(ns netns.NsHandle) (*Handle, error)

NewHandleAt returns a netlink handle on the network namespace specified by ns. If ns=netns.None(), current network namespace will be assumed

func NewHandleAtFrom

func NewHandleAtFrom(newNs, curNs netns.NsHandle) (*Handle, error)

NewHandleAtFrom works as NewHandle but allows client to specify the new and the origin netns Handle.

func (*Handle) Add

func (h *Handle) Add(setname string, entry *Entry) error

Add adds an entry to an existing ipset.

func (*Handle) Close

func (h *Handle) Close()

Close releases the resources allocated to this handle

func (*Handle) Create

func (h *Handle) Create(setname, typename string, options CreateOptions) error

func (*Handle) Del

func (h *Handle) Del(setname string, entry *Entry) error

Del deletes an entry from an existing ipset.

func (*Handle) Delete deprecated

This method has been deprecated.
func (h *Handle) Delete()

Deprecated: Use Close instead.

func (*Handle) Destroy

func (h *Handle) Destroy(setname string) error

func (*Handle) Flush

func (h *Handle) Flush(setname string) error

func (*Handle) ForceDestroy

func (h *Handle) ForceDestroy(setname string) error

func (*Handle) GetSocketReceiveBufferSize

func (h *Handle) GetSocketReceiveBufferSize() ([]int, error)

GetSocketReceiveBufferSize gets the receiver buffer size for each socket in the netlink handle. The retrieved value should be the double to the one set for SetSocketReceiveBufferSize.

func (*Handle) List

func (h *Handle) List(name string) (*Sets, error)

func (*Handle) ListAll

func (h *Handle) ListAll() ([]Sets, error)

func (*Handle) Protocol

func (h *Handle) Protocol() (protocol uint8, minVersion uint8, err error)

func (*Handle) Rename

func (h *Handle) Rename(from string, to string) error

Rename rename a set. Set identified by SETNAME-TO must not exist.

func (*Handle) SetSocketReceiveBufferSize

func (h *Handle) SetSocketReceiveBufferSize(size int, force bool) error

SetSocketReceiveBufferSize sets the receive buffer size for each socket in the netlink handle. The maximum value is capped by /proc/sys/net/core/rmem_max.

func (*Handle) SetSocketTimeout

func (h *Handle) SetSocketTimeout(to time.Duration) error

SetSocketTimeout sets the send and receive timeout for each socket in the netlink handle. Although the socket timeout has granularity of one microsecond, the effective granularity is floored by the kernel timer tick, which default value is four milliseconds.

func (*Handle) Swap

func (h *Handle) Swap(from string, to string) error

Swap swap the content of two sets, or in another words, exchange the name of two sets. The referred sets must exist and compatible type of sets can be swapped only.

type IPSetError

type IPSetError uintptr

func (IPSetError) Error

func (e IPSetError) Error() string

type Sets

type Sets struct {
	Nfgenmsg           *nl.Nfgenmsg
	Protocol           uint8
	ProtocolMinVersion uint8
	Revision           uint8
	Family             uint8
	Flags              uint8
	SetName            string
	TypeName           string
	Comment            string
	MarkMask           uint32

	IPFrom   net.IP
	IPTo     net.IP
	PortFrom uint16
	PortTo   uint16

	Size         uint32
	HashSize     uint32
	NumEntries   uint32
	MaxElements  uint32
	References   uint32
	SizeInMemory uint32
	CadtFlags    uint32
	Timeout      *uint32
	LineNo       uint32

	Entries []Entry
}

Sets is the result of a dump request for a set

func List

func List(setname string) (*Sets, error)

List dumps an specific ipset.

func ListAll

func ListAll() ([]Sets, error)

ListAll dumps all ipsets.

type TypeName

type TypeName string

func (TypeName) Method

func (t TypeName) Method() string

Directories

Path Synopsis
expample

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL