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
Acquire the handle. handle, _ := ipset.NewHandle()
Start the session. This is the point where ipset binary is executed and stdin/stdout are attached. _ = handle.Start()
Call Add/Delete/etc methods of handle. newSet, _ = ipset.NewSet("mynewset", SetHashNetIface, SetWithComment()) _ = handle.Create(newSet)
When you are done shut down the session. This will send shutdown signal to the ipset binary which should exit. _ = handle.Quit()
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
- Variables
- func Add(set *Set, options ...OptFunc) ([]byte, error)
- func Create(set *Set, options ...OptFunc) ([]byte, error)
- func Delete(set *Set, options ...OptFunc) ([]byte, error)
- func Destroy(set *Set, options ...OptFunc) ([]byte, error)
- func Flush(set *Set, options ...OptFunc) ([]byte, error)
- func MemberWithNomatch(m *Member) error
- func Rename(set1, set2 *Set, options ...OptFunc) ([]byte, error)
- func Swap(set1, set2 *Set, options ...OptFunc) ([]byte, error)
- func Test(set1 *Set, options ...OptFunc) ([]byte, error)
- type Error
- type Handle
- func (h *Handle) Add(s renderer) error
- func (h *Handle) Create(s renderer) error
- func (h *Handle) Delete(s renderer) error
- func (h *Handle) Destroy(s renderer) error
- func (h *Handle) Flush(s renderer) error
- func (h *Handle) IsSuccessful() bool
- func (h *Handle) Quit() error
- func (h *Handle) Read(p []byte) (int, error)
- func (h *Handle) Start() error
- func (h *Handle) StdErr() (io.Reader, error)
- func (h *Handle) Swap(s1, s2 *Set) error
- func (h *Handle) Wait(ctx context.Context) error
- func (h *Handle) Write(p []byte) (int, error)
- type Header
- type Ipset
- type IpsetVersion
- type Member
- type MemberOpt
- type OptFunc
- type RenderType
- type Set
- type SetOpt
- func SetWithComment(comment string) SetOpt
- func SetWithCounters(counters string) SetOpt
- func SetWithFamily(family string) SetOpt
- func SetWithForceadd() SetOpt
- func SetWithHashsize(hashsize int) SetOpt
- func SetWithMaxelem(maxelem int) SetOpt
- func SetWithNetmask(netmask int) SetOpt
- func SetWithRange(srange string) SetOpt
- func SetWithReferences(references int) SetOpt
- func SetWithRevision(revision int) SetOpt
- func SetWithSKBInfo(skbinfo string) SetOpt
- func SetWithSize(size int) SetOpt
- func SetWithTimeout(timeout int) SetOpt
- type SetType
Constants ¶
const ( SupportedVersionMajor int = 6 SupportedVersionMinor int = 29 SupportVersionProto = 6 )
Minimal ipset version supported by this package.
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.
const ( MemberFamilyInet = "inet" MemberFamilyInet6 = "inet6" )
Acceptable values for SetWithFamily.
Variables ¶
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 MemberWithNomatch ¶
MemberWithNomatch is an option to create member with nomatch.
Types ¶
type Error ¶
type Error string
Error represents errors.
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 ¶
NewHandle takes a variable amount of option functions and returns configured *Handle.
func (*Handle) Destroy ¶
Destroy sets in ipset through the open handle. Warning. Will destroy everything in ipset if no sets are given.
func (*Handle) Flush ¶
Flush sets in ipset through the open handle. Warning. Will flush all sets if no sets are given.
func (*Handle) IsSuccessful ¶
IsSuccessful returns true if process has exited with exit code=0.
func (*Handle) Start ¶
Start interactive session, normally transfers the Handle into the open state.
type Header ¶
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 LoadFromFile ¶
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.
type IpsetVersion ¶
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.
type MemberOpt ¶
MemberOpt is a signature of for option function that can be used with NewMember() to produce a member with desired config.
func MemberWithBytes ¶
MemberWithBytes is an option to create member with bytes field initialized.
func MemberWithComment ¶
MemberWithComment is an option to create member with comment.
func MemberWithPackets ¶
MemberWithPackets is an option to create member with packets field initialized.
func MemberWithSKBMark ¶
MemberWithSKBMark is an option to create member with skbmark field initialized.
func MemberWithSKBPrio ¶
MemberWithSKBPrio is an option to create member with skbprio field initialized.
func MemberWithTimeout ¶
MemberWithTimeout is an option to create member with timeout.
type OptFunc ¶
OptFunc is a signature for option functions that change configuration of handle.
func HandleAppendArgs ¶
HandleAppendArgs is an options that adds more args after HandleWithArgs was used.
func HandleWithArgs ¶
HandleWithArgs is an options for to use non default arguments for call to ipset binary.
func HandleWithBin ¶
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 (*Set) Render ¶
func (s *Set) Render(rType RenderType) string
Render Set for use with interactive functions of handler.
type SetOpt ¶
SetOpt is a signature of option function that can be used with NewSet() to produce a Set with desired config.
func SetWithComment ¶
SetWithComment is an option to create Set with comments.
func SetWithCounters ¶
SetWithCounters is an option to create Set with counters.
func SetWithFamily ¶
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 ¶
SetWithHashsize is an option to create Set with hashsize field initialized.
func SetWithMaxelem ¶
SetWithMaxelem is an option to create Set with maxelem field initialized.
func SetWithNetmask ¶
SetWithNetmask is an option to create Set with netmask reference initialized.
func SetWithRange ¶
SetWithRange is an option to create Set with range field initialized.
func SetWithReferences ¶
SetWithReferences is an option to create Set with maxelem reference initialized.
func SetWithRevision ¶
SetWithRevision is an option to create Set with revision field initialized.
func SetWithSKBInfo ¶
SetWithSKBInfo is an option to create Set with skbinfo.
func SetWithSize ¶
SetWithSize is an option to create Set with size field initialized.
func SetWithTimeout ¶
SetWithTimeout is an option to create Set with timeout reference initialized.