ipset

package module
Version: v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2017 License: Apache-2.0 Imports: 10 Imported by: 0

README

Bindings for ipset userspace utility

License ReportCard GoDoc

For documentation check the godoc

Documentation

Overview

Package ipset provides bindings for linux userspace ipset utility http://ipset.netfilter.org/ipset.man.html

Ipset allows for managing iptables rules in complex environments where otherwise iptables rules would become too huge or would have to be updated too often.

Similarly, this package provides bindings to configure ipset programmatically.

Because ipset is typically used in environment with large ipset configurations it is not practical ro rely on simple command lines like `ipset add` or `ipset create` since thousands of `create` calls would result in thousands of forks.

Instead, this package utilizes interactive mode provided by `ipset -` to execute bulks of create/delete/add/flush/swap calls in one session. The internal object to start and control interactive session is called `Handle` which implements `io.Writer` and writes directly into ipset stdin.

However, some commands still make more sense when executed one by one like `test`, for that reason this package also provides a set of functions called `oneshots` (Add/Delete/etc...) which can be used when exit code is needed.

Since ipset can export its configuration as xml this package provides structures to that can be used to parse ipset xml config.

Logging: this package is mostly silent to avoid messing with ipset stderr, but some debug loggin can be enabled using RLOG_TRACE_LEVEL=3 environment variable.

Typical session starts as

iset, _ := ipset.Load(context.Background())
for _, set := range iset.Sets {
	fmt.Printf("Set %s of type %s has %d members\n", set.Name, set.Type, len(set.Members))
}

Output:
Set host of type hash:net has 2 members
Set host2 of type hash:net has 12 members
Set timeoutSet of type hash:ip has 0 members
Set commentSet of type hash:ip has 1 members
Set countersSet of type hash:ip has 1 members
Set skbSet of type hash:ip has 1 members
Set host3 of type hash:net has 1 members
Set super of type list:set has 2 members

Interactive sessions workflow Pros: useful to create/delete large sets Cons: no error handling

1. Acquire the handle.
handle, _ := ipset.NewHandle()

2. Start the session.
   This is the point where ipset binary is executed and stdin/stdout are attached.
_ = handle.Start()

3. Call Add/Delete/etc methods of handle.
newSet, _ = ipset.NewSet("mynewset", SetHashNetIface, SetWithComment())
_ = handle.Create(newSet)

4. When you are done shut down the session.
   This will send shutdown signal to the ipset binary which should exit.
_ = handle.Quit()

5. And cleanup the resources.
   After successful Quit() call ipset binary should be terminated, but
   resources allocated for handler might still be in use, like stdin/our/err pipes.
ctx, cancel := context.WithTimeout(...)
_ = handle.Wait(ctx)

that's it.

And non-interactive session might be useful for commands that require distict error code. Pros: clear error and output Cons: fork per call

# ipset save
Output:
create super list:set size 8
add super host

testSet, _ = ipset.NewSet("super", SetListSet)
testMember, _ = ipset.NewMember("host", newSet)
_, err := ipset.Test(testSet)

Options

This package uses options functions as a way to specify desired configuration. This is done to keep default signatures simple like `NewHandle()` while allowing flexible configuration when needed

`NewHandle(HandleWithBin("/root/ipset"), HandleWithArgs("-"))

Learn more about options functions https://commandcenter.blogspot.co.nz/2014/01/self-referential-functions-and-design.html

Index

Constants

View Source
const (
	SupportedVersionMajor int = 6
	SupportedVersionMinor int = 29
	SupportVersionProto       = 6
)

Minimal ipset version supported by this package.

View Source
const (
	SetBitmapIP       = "bitmap:ip"
	SetBitmapIPMac    = "bitmap:ip,mac"
	SetBitmapPort     = "bitmap:port"
	SetHashIP         = "hash:ip"
	SetHashMac        = "hash:mac"
	SetHashNet        = "hash:net"
	SetHashNetNet     = "hash:net,net"
	SetHashIPPort     = "hash:ip,port"
	SetHashNetPort    = "hash:net,port"
	SetHashIPPortIP   = "hash:ip,port,ip"
	SetHashIPPortNet  = "hash:ip,port,net"
	SetHashIPMark     = "hash:ip,mark"
	SetHashNetPortNet = "hash:net,port,net"
	SetHashNetIface   = "hash:net,iface"
	SetListSet        = "list:set"
)

see http://ipset.netfilter.org/ipset.man.html for types description.

View Source
const (
	MemberFamilyInet  = "inet"
	MemberFamilyInet6 = "inet6"
)

Acceptable values for SetWithFamily.

Variables

View Source
var (
	// NoVal used in Header and Member structs as a value for fields
	// which don't have value. Like Header.Comment or Member.NoMatch.
	// This is the artifact of xml parsing.
	NoVal = new(string)
)

Functions

func Add

func Add(set *Set, options ...OptFunc) ([]byte, error)

Add members of sets to ipset.

func Create

func Create(set *Set, options ...OptFunc) ([]byte, error)

Create sets and members in ipset.

func Delete

func Delete(set *Set, options ...OptFunc) ([]byte, error)

Delete memebers from ipset.

func Destroy

func Destroy(set *Set, options ...OptFunc) ([]byte, error)

Destroy sets in ipset. Destroys everything if no sets are given.

func Flush

func Flush(set *Set, options ...OptFunc) ([]byte, error)

Flush sets in ipset. Flushes everythin if no sets are given.

func MemberWithNomatch

func MemberWithNomatch(m *Member) error

MemberWithNomatch is an option to create member with nomatch.

func Rename

func Rename(set1, set2 *Set, options ...OptFunc) ([]byte, error)

Rename set.

func Swap

func Swap(set1, set2 *Set, options ...OptFunc) ([]byte, error)

Swap contents of 2 sets.

func Test

func Test(set1 *Set, options ...OptFunc) ([]byte, error)

Test tests existence of a set or existence of member in a set.

Types

type Error

type Error string

Error represents errors.

const (
	ErrorNotStarted       Error = "Process not started"
	ErrorUnexpectedNil    Error = "function does not accept nil"
	ErrorIncompatibleSwap Error = "swaped sets must be of the same type"
)

Errors

func (Error) Error

func (e Error) Error() string

type Handle

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

Handle for an ipset session, it keeps state and allocated resources together. Handle is open when underlying process initizlized and started and hasn't exited yet.

func NewHandle

func NewHandle(options ...OptFunc) (*Handle, error)

NewHandle takes a variable amount of option functions and returns configured *Handle.

func (*Handle) Add

func (h *Handle) Add(s renderer) error

Add members of sets to ipset through the open handle.

func (*Handle) Create

func (h *Handle) Create(s renderer) error

Create sets and members in ipset through the open handle.

func (*Handle) Delete

func (h *Handle) Delete(s renderer) error

Delete memebers of sets from ipset through the open handle.

func (*Handle) Destroy

func (h *Handle) Destroy(s renderer) error

Destroy sets in ipset through the open handle. Warning. Will destroy everything in ipset if no sets are given.

func (*Handle) Flush

func (h *Handle) Flush(s renderer) error

Flush sets in ipset through the open handle. Warning. Will flush all sets if no sets are given.

func (*Handle) IsSuccessful

func (h *Handle) IsSuccessful() bool

IsSuccessful returns true if process has exited with exit code=0.

func (*Handle) Quit

func (h *Handle) Quit() error

Quit interactive session.

func (*Handle) Read

func (h *Handle) Read(p []byte) (int, error)

Read from the open handle.

func (*Handle) Start

func (h *Handle) Start() error

Start interactive session, normally transfers the Handle into the open state.

func (*Handle) StdErr

func (h *Handle) StdErr() (io.Reader, error)

StdErr provides access to stderr of running process.

func (*Handle) Swap

func (h *Handle) Swap(s1, s2 *Set) error

Swap contents of 2 sets through the open handle.

func (*Handle) Wait

func (h *Handle) Wait(ctx context.Context) error

Wait for handle to stop interactive session and deallocate resources.

func (*Handle) Write

func (h *Handle) Write(p []byte) (int, error)

Write into the open handle.

type Header struct {
	Family     string  `xml:" family,omitempty" json:"family,omitempty"`
	Range      string  `xml:" range,omitempty" json:"range,omitempty"`
	Hashsize   int     `xml:" hashsize,omitempty" json:"hashsize,omitempty"`
	Maxelem    int     `xml:" maxelem,omitempty" json:"maxelem,omitempty"`
	Memsize    int     `xml:" memsize,omitempty" json:"memsize,omitempty"`
	References int     `xml:" references,omitempty" json:"references,omitempty"`
	Timeout    int     `xml:" timeout,omitempty" json:"timeout,omitempty"`
	Netmask    int     `xml:" netmask,omitempty" json:"netmask,omitempty"`
	Size       int     `xml:" size,omitempty" json:"size,omitempty"`
	Counters   *string `xml:" counters,omitempty" json:"counters,omitempty"`
	Comment    *string `xml:" comment,omitempty" json:"comment,omitempty"`
	SKBInfo    *string `xml:" skbinfo,omitempty" json:"skbinfo,omitempty"`
	Forceadd   *string `xml:" forceadd,omitempty" json:"forceadd,omitempty"`
}

Header is a representation of ipset Set header. Header of a set indicates which what additional fields could be used in members of the set and how much resources the set is using.

Ipset configuration consists of collection of Sets, every Set has a Type, a Header and a collection of Members.

type Ipset

type Ipset struct {
	Sets []*Set `xml:" ipset,omitempty" json:"ipset,omitempty"`
}

Ipset represents ipset configuration that consists of list of sets.

func Load

func Load(ctx context.Context, options ...OptFunc) (*Ipset, error)

Load ipset config from system.

func LoadFromFile

func LoadFromFile(filename string) (*Ipset, error)

LoadFromFile loads ipset config from xml file produced with ipset save -o xml.

func (*Ipset) Render

func (s *Ipset) Render(rType RenderType) string

Render collection of sets for usage with interactive functions of handle.

func (*Ipset) SetByName

func (s *Ipset) SetByName(name string) *Set

SetByName searches set by names.

type IpsetVersion

type IpsetVersion struct {
	Major int
	Minor int
	Proto int
}

IpsetVersion prepresents ipset version.

func Version

func Version(options ...OptFunc) (*IpsetVersion, error)

Version captures version of ipset and parses it for later verification.

func (*IpsetVersion) Check

func (v *IpsetVersion) Check() bool

Check that given version is supported.

type Member

type Member struct {
	Elem     string  `xml:" elem" json:"elem"`
	Comment  string  `xml:" comment,omitempty" json:"comment,omitempty"`
	NoMatch  *string `xml:" nomatch,omitempty" json:"nomatch,omitempty"`
	Timeout  int     `xml:" timeout,omitempty" json:"timeout,omitempty"`
	Packets  int     `xml:" packets,omitempty" json:"packets,omitempty"`
	Bytes    int     `xml:" bytes,omitempty" json:"bytes,omitempty"`
	SKBMark  string  `xml:" skbmark,omitempty" json:"skbmark,omitempty"`
	SKBPrio  string  `xml:" skbprio,omitempty" json:"skbprio,omitempty"`
	SKBQueue string  `xml:" skbqueue,omitempty" json:"skbqueue,omitempty"`
	// contains filtered or unexported fields
}

Member is a representation of ipset member which is a minimal item of ipset configuration that describes rule for matching packets.

Ipset configuration consists of collection of Sets, every Set has a Type, a Header and a collection of Members.

func NewMember

func NewMember(elem string, set *Set, opts ...MemberOpt) (*Member, error)

NewMember creates a new member. Some member options can't be used with certain Set type, to assert that requested member can be used with a desired set you can provide a pointer to the desired Set. Pointer to the Set is allowed to be nil in which case no type assertion performed.

type MemberOpt

type MemberOpt func(*Member) error

MemberOpt is a signature of for option function that can be used with NewMember() to produce a member with desired config.

func MemberWithBytes

func MemberWithBytes(bytes int) MemberOpt

MemberWithBytes is an option to create member with bytes field initialized.

func MemberWithComment

func MemberWithComment(comment string) MemberOpt

MemberWithComment is an option to create member with comment.

func MemberWithPackets

func MemberWithPackets(packets int) MemberOpt

MemberWithPackets is an option to create member with packets field initialized.

func MemberWithSKBMark

func MemberWithSKBMark(skbmark string) MemberOpt

MemberWithSKBMark is an option to create member with skbmark field initialized.

func MemberWithSKBPrio

func MemberWithSKBPrio(skbprio string) MemberOpt

MemberWithSKBPrio is an option to create member with skbprio field initialized.

func MemberWithTimeout

func MemberWithTimeout(timeout int) MemberOpt

MemberWithTimeout is an option to create member with timeout.

type OptFunc

type OptFunc func(*Handle) error

OptFunc is a signature for option functions that change configuration of handle.

func HandleAppendArgs

func HandleAppendArgs(args ...string) OptFunc

HandleAppendArgs is an options that adds more args after HandleWithArgs was used.

func HandleWithArgs

func HandleWithArgs(args ...string) OptFunc

HandleWithArgs is an options for to use non default arguments for call to ipset binary.

func HandleWithBin

func HandleWithBin(bin string) OptFunc

HandleWithBin is an options to use non default location of ipset binary.

type RenderType

type RenderType int

RenderType indicates how to render a Set.

const (
	// RenderSave renders all sets with headers as create commands
	// and all members with headers as add commands.
	// Same as regular save.
	RenderSave RenderType = iota

	// RenderCreate renders all sets as create commands with headers.
	RenderCreate

	// RenderAdd renders all members as add commands with headers.
	RenderAdd

	// RenderDelete renders all members as del commands.
	RenderDelete

	// RenderFlush renders all sets as flush commands.
	RenderFlush

	// RenderDestroy renders all sets as destroy commands.
	RenderDestroy

	// RenderSwap renders 2 sets as swap command.
	RenderSwap

	// RenderTest renders set (and one member if present) as test command.
	RenderTest

	// RenderRename renders 2 sets as rename command.
	RenderRename
)

type Set

type Set struct {
	Name     string   `xml:" name,attr"  json:",omitempty"`
	Header   Header   `xml:" header,omitempty" json:"header,omitempty"`
	Members  []Member `xml:" members>member,omitempty" json:"members,omitempty"`
	Revision int      `xml:" revision,omitempty" json:"revision,omitempty"`
	Type     SetType  `xml:" type,omitempty" json:"type,omitempty"`
}

Set is a representation of ipset Set which is a named collection of ipset members of specific type.

Ipset configuration consists of collection of Sets, every Set has a Type, a Header and a collection of Members.

func NewSet

func NewSet(name string, sType SetType, options ...SetOpt) (*Set, error)

NewSet creates new Set of a given type.

func (*Set) AddMember

func (s *Set) AddMember(m *Member) error

AddMember to the set.

func (*Set) Render

func (s *Set) Render(rType RenderType) string

Render Set for use with interactive functions of handler.

type SetOpt

type SetOpt func(*Set) error

SetOpt is a signature of option function that can be used with NewSet() to produce a Set with desired config.

func SetWithComment

func SetWithComment(comment string) SetOpt

SetWithComment is an option to create Set with comments.

func SetWithCounters

func SetWithCounters(counters string) SetOpt

SetWithCounters is an option to create Set with counters.

func SetWithFamily

func SetWithFamily(family string) SetOpt

SetWithFamily is an option to create Set with family field initialized.

func SetWithForceadd

func SetWithForceadd() SetOpt

SetWithForceadd is an option to create Set with forceadd.

func SetWithHashsize

func SetWithHashsize(hashsize int) SetOpt

SetWithHashsize is an option to create Set with hashsize field initialized.

func SetWithMaxelem

func SetWithMaxelem(maxelem int) SetOpt

SetWithMaxelem is an option to create Set with maxelem field initialized.

func SetWithNetmask

func SetWithNetmask(netmask int) SetOpt

SetWithNetmask is an option to create Set with netmask reference initialized.

func SetWithRange

func SetWithRange(srange string) SetOpt

SetWithRange is an option to create Set with range field initialized.

func SetWithReferences

func SetWithReferences(references int) SetOpt

SetWithReferences is an option to create Set with maxelem reference initialized.

func SetWithRevision

func SetWithRevision(revision int) SetOpt

SetWithRevision is an option to create Set with revision field initialized.

func SetWithSKBInfo

func SetWithSKBInfo(skbinfo string) SetOpt

SetWithSKBInfo is an option to create Set with skbinfo.

func SetWithSize

func SetWithSize(size int) SetOpt

SetWithSize is an option to create Set with size field initialized.

func SetWithTimeout

func SetWithTimeout(timeout int) SetOpt

SetWithTimeout is an option to create Set with timeout reference initialized.

type SetType

type SetType string

SetType represents type of ipset set.

Directories

Path Synopsis
internal
cmd

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