util

package
v0.0.0-...-501ccff Latest Latest
Warning

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

Go to latest
Published: Apr 25, 2023 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// KernelModuleIPVS is the kernel module "ip_vs"
	KernelModuleIPVS string = "ip_vs"
	// KernelModuleIPVSRR is the kernel module "ip_vs_rr"
	KernelModuleIPVSRR string = "ip_vs_rr"
	// KernelModuleIPVSWRR is the kernel module "ip_vs_wrr"
	KernelModuleIPVSWRR string = "ip_vs_wrr"
	// KernelModuleIPVSSH is the kernel module "ip_vs_sh"
	KernelModuleIPVSSH string = "ip_vs_sh"
	// KernelModuleNfConntrackIPV4 is the module "nf_conntrack_ipv4"
	KernelModuleNfConntrackIPV4 string = "nf_conntrack_ipv4"
	// KernelModuleNfConntrack is the kernel module "nf_conntrack"
	KernelModuleNfConntrack string = "nf_conntrack"
)

IPVS required kernel modules.

View Source
const (
	// ProtocolFamilyIPV4 represents IPv4 protocol.
	ProtocolFamilyIPV4 = "inet"
	// ProtocolFamilyIPV6 represents IPv6 protocol.
	ProtocolFamilyIPV6 = "inet6"
	// ProtocolTCP represents TCP protocol.
	ProtocolTCP = "tcp"
	// ProtocolUDP represents UDP protocol.
	ProtocolUDP = "udp"
	// ProtocolSCTP represents SCTP protocol.
	ProtocolSCTP = "sctp"
)
View Source
const DefaultPortRange string = "0-65535"

DefaultPortRange defines the default bitmap:port valid port range.

View Source
const IPSetCmd = "ipset"

IPSetCmd represents the ipset util. We use ipset command for ipset execute.

View Source
const LockfilePath14x = "@xtables"

LockfilePath14x is the iptables 1.4.x lock file acquired by any process that's making any change in the iptable rule

View Source
const LockfilePath16x = "/run/xtables.lock"

LockfilePath16x is the iptables 1.6.x lock file acquired by any process that's making any change in the iptable rule

View Source
const WaitIntervalString = "-W"

WaitIntervalString a constant for specifying the wait interval flag

View Source
const WaitIntervalUsecondsValue = "100000"

WaitIntervalUsecondsValue a constant for specifying the default wait interval useconds

View Source
const WaitSecondsValue = "5"

WaitSecondsValue a constant for specifying the default wait seconds

View Source
const WaitString = "-w"

WaitString a constant for specifying the wait flag

Variables

View Source
var EntryMemberPattern = "(?m)^(.*\n)*Members:\n"

EntryMemberPattern is the regular expression pattern of ipset member list. The raw output of ipset command `ipset list {set}` is similar to, Name: foobar Type: hash:ip,port Revision: 2 Header: family inet hashsize 1024 maxelem 65536 Size in memory: 16592 References: 0 Members: 192.168.1.2,tcp:8080 192.168.1.1,udp:53

View Source
var MinCheckVersion = utilversion.MustParseGeneric("1.4.11")

MinCheckVersion minimum version to be checked Versions of iptables less than this do not support the -C / --check flag (test whether a rule exists).

View Source
var RandomFullyMinVersion = utilversion.MustParseGeneric("1.6.2")

RandomFullyMinVersion is the minimum version from which the --random-fully flag is supported, used for port mapping to be fully randomized

ValidIPSetTypes defines the supported ip set type.

View Source
var VersionPattern = "v[0-9]+\\.[0-9]+"

VersionPattern is the regular expression pattern of ipset version string. ipset version output is similar to "v6.10".

View Source
var WaitIntervalMinVersion = utilversion.MustParseGeneric("1.6.1")

WaitIntervalMinVersion a minimum iptables versions supporting the wait interval useconds

View Source
var WaitMinVersion = utilversion.MustParseGeneric("1.4.20")

WaitMinVersion a minimum iptables versions supporting the -w and -w<seconds> flags

View Source
var WaitRestoreMinVersion = utilversion.MustParseGeneric("1.6.2")

WaitRestoreMinVersion a minimum iptables versions supporting the wait restore seconds

View Source
var WaitSecondsMinVersion = utilversion.MustParseGeneric("1.4.22")

WaitSecondsMinVersion a minimum iptables versions supporting the wait seconds

Functions

func EnsureSysctl

func EnsureSysctl(sysctl sysInterface, name string, newVal int) error

EnsureSysctl sets a kernel sysctl to a given numeric value.

func GetChainLines

func GetChainLines(table Table, save []byte) map[Chain][]byte

GetChainLines parses a table's iptables-save data to find chains in the table. It returns a map of iptables.Chain to []byte where the []byte is the chain line from save (with counters etc.). Note that to avoid allocations memory is SHARED with save.

func GetRequiredIPVSModules

func GetRequiredIPVSModules(kernelVersion *version.Version) []string

GetRequiredIPVSModules returns the required ipvs modules for the given linux kernel version.

func MakeChainLine

func MakeChainLine(chain Chain) string

MakeChainLine return an iptables-save/restore formatted chain line given a Chain

func NewSysInterface

func NewSysInterface() sysInterface

New returns a new Interface for accessing sysctl

Types

type Chain

type Chain string

Chain represents the different rules

const (
	// ChainPostrouting used for source NAT in nat table
	ChainPostrouting Chain = "POSTROUTING"
	// ChainPrerouting used for DNAT (destination NAT) in nat table
	ChainPrerouting Chain = "PREROUTING"
	// ChainOutput used for the packets going out from local
	ChainOutput Chain = "OUTPUT"
	// ChainInput used for incoming packets
	ChainInput Chain = "INPUT"
	// ChainForward used for the packets for another NIC
	ChainForward Chain = "FORWARD"
)

type Entry

type Entry struct {
	// IP is the entry's IP.  The IP address protocol corresponds to the HashFamily of IPSet.
	// All entries' IP addresses in the same ip set has same the protocol, IPv4 or IPv6.
	IP string
	// Port is the entry's Port.
	Port int
	// Protocol is the entry's Protocol.  The protocols of entries in the same ip set are all
	// the same.  The accepted protocols are TCP, UDP and SCTP.
	Protocol string
	// Net is the entry's IP network address.  Network address with zero prefix size can NOT
	// be stored.
	Net string
	// IP2 is the entry's second IP.  IP2 may not be empty for `hash:ip,port,ip` type ip set.
	IP2 string
	// SetType is the type of ipset where the entry exists.
	SetType Type
}

Entry represents a ipset entry.

func (*Entry) String

func (e *Entry) String() string

String returns the string format for ipset entry.

func (*Entry) Validate

func (e *Entry) Validate(set *IPSet) bool

Validate checks if a given ipset entry is valid or not. The set parameter is the ipset that entry belongs to.

type FlushFlag

type FlushFlag bool

FlushFlag an option flag for Flush

const FlushTables FlushFlag = true

FlushTables a boolean true constant for option flag FlushFlag

const NoFlushTables FlushFlag = false

NoFlushTables a boolean false constant for option flag FlushFlag

type IPSet

type IPSet struct {
	// Name is the set name.
	Name string
	// SetType specifies the ipset type.
	SetType Type
	// HashFamily specifies the protocol family of the IP addresses to be stored in the set.
	// The default is inet, i.e IPv4.  If users want to use IPv6, they should specify inet6.
	HashFamily string
	// HashSize specifies the hash table size of ipset.
	HashSize int
	// MaxElem specifies the max element number of ipset.
	MaxElem int
	// PortRange specifies the port range of bitmap:port type ipset.
	PortRange string
	// comment message for ipset
	Comment string
}

IPSet implements an Interface to a set.

func (*IPSet) Validate

func (set *IPSet) Validate() bool

Validate checks if a given ipset is valid or not.

type IPTableInterface

type IPTableInterface interface {
	// EnsureChain checks if the specified chain exists and, if not, creates it.  If the chain existed, return true.
	EnsureChain(table Table, chain Chain) (bool, error)
	// FlushChain clears the specified chain.  If the chain did not exist, return error.
	FlushChain(table Table, chain Chain) error
	// DeleteChain deletes the specified chain.  If the chain did not exist, return error.
	DeleteChain(table Table, chain Chain) error
	// ChainExists tests whether the specified chain exists, returning an error if it
	// does not, or if it is unable to check.
	ChainExists(table Table, chain Chain) (bool, error)
	// EnsureRule checks if the specified rule is present and, if not, creates it.  If the rule existed, return true.
	EnsureRule(position RulePosition, table Table, chain Chain, args ...string) (bool, error)
	// DeleteRule checks if the specified rule is present and, if so, deletes it.
	DeleteRule(table Table, chain Chain, args ...string) error
	// IsIPv6 returns true if this is managing ipv6 tables.
	IsIPv6() bool
	// Protocol returns the IP family this instance is managing,
	Protocol() Protocol
	// SaveInto calls `iptables-save` for table and stores result in a given buffer.
	SaveInto(table Table, buffer *bytes.Buffer) error
	// Restore runs `iptables-restore` passing data through []byte.
	// table is the Table to restore
	// data should be formatted like the output of SaveInto()
	// flush sets the presence of the "--noflush" flag. see: FlushFlag
	// counters sets the "--counters" flag. see: RestoreCountersFlag
	Restore(table Table, data []byte, flush FlushFlag, counters RestoreCountersFlag) error
	// RestoreAll is the same as Restore except that no table is specified.
	RestoreAll(data []byte, flush FlushFlag, counters RestoreCountersFlag) error
	// Monitor detects when the given iptables tables have been flushed by an external
	// tool (e.g. a firewall reload) by creating canary chains and polling to see if
	// they have been deleted. (Specifically, it polls tables[0] every interval until
	// the canary has been deleted from there, then waits a short additional time for
	// the canaries to be deleted from the remaining tables as well. You can optimize
	// the polling by listing a relatively empty table in tables[0]). When a flush is
	// detected, this calls the reloadFunc so the caller can reload their own iptables
	// rules. If it is unable to create the canary chains (either initially or after
	// a reload) it will log an error and stop monitoring.
	// (This function should be called from a goroutine.)
	Monitor(canary Chain, tables []Table, reloadFunc func(), interval time.Duration, stopCh <-chan struct{})
	// HasRandomFully reveals whether `-j MASQUERADE` takes the
	// `--random-fully` option.  This is helpful to work around a
	// Linux kernel bug that sometimes causes multiple flows to get
	// mapped to the same IP:PORT and consequently some suffer packet
	// drops.
	HasRandomFully() bool

	// Present checks if the kernel supports the iptable interface
	Present() bool
}

Interface is an injectable interface for running iptables commands. Implementations must be goroutine-safe.

func NewIPTableExec

func NewIPTableExec(exec exec.Interface, protocol Protocol) IPTableInterface

NewIPTableExec returns a new Interface which will exec iptables.

func NewIPTableInterface

func NewIPTableInterface(exec exec.Interface, protocol Protocol) IPTableInterface

New returns a new Interface which will exec iptables.

type Interface

type Interface interface {
	// FlushSet deletes all entries from a named set.
	FlushSet(set string) error
	// DestroySet deletes a named set.
	DestroySet(set string) error
	// DestroyAllSets deletes all sets.
	DestroyAllSets() error
	// CreateSet creates a new set.  It will ignore error when the set already exists if ignoreExistErr=true.
	CreateSet(set *IPSet, ignoreExistErr bool) error
	// AddEntry adds a new entry to the named set.  It will ignore error when the entry already exists if ignoreExistErr=true.
	AddEntry(entry string, set *IPSet, ignoreExistErr bool) error
	// DelEntry deletes one entry from the named set
	DelEntry(entry string, set string) error
	// Test test if an entry exists in the named set
	TestEntry(entry string, set string) (bool, error)
	// ListEntries lists all the entries from a named set
	ListEntries(set string) ([]string, error)
	// ListSets list all set names from kernel
	ListSets() ([]string, error)
	// GetVersion returns the "X.Y" version string for ipset.
	GetVersion() (string, error)
}

Interface is an injectable interface for running ipset commands. Implementations must be goroutine-safe.

func New

func New(exec exec.Interface) Interface

New returns a new Interface which will exec ipset.

type KernelHandler

type KernelHandler interface {
	GetModules() ([]string, error)
	GetKernelVersion() (string, error)
}

KernelHandler can handle the current installed kernel modules.

type LinuxKernelHandler

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

LinuxKernelHandler implements KernelHandler interface.

func NewLinuxKernelHandler

func NewLinuxKernelHandler() *LinuxKernelHandler

NewLinuxKernelHandler initializes LinuxKernelHandler with exec.

func (*LinuxKernelHandler) GetKernelVersion

func (handle *LinuxKernelHandler) GetKernelVersion() (string, error)

GetKernelVersion returns currently running kernel version.

func (*LinuxKernelHandler) GetModules

func (handle *LinuxKernelHandler) GetModules() ([]string, error)

GetModules returns all installed kernel modules.

type Protocol

type Protocol string

Protocol defines the ip protocol either ipv4 or ipv6

const (
	// ProtocolIPv4 represents ipv4 protocol in iptables
	ProtocolIPv4 Protocol = "IPv4"
	// ProtocolIPv6 represents ipv6 protocol in iptables
	ProtocolIPv6 Protocol = "IPv6"
)

type RestoreCountersFlag

type RestoreCountersFlag bool

RestoreCountersFlag is an option flag for Restore

const NoRestoreCounters RestoreCountersFlag = false

NoRestoreCounters a boolean false constant for the option flag RestoreCountersFlag

const RestoreCounters RestoreCountersFlag = true

RestoreCounters a boolean true constant for the option flag RestoreCountersFlag

type RulePosition

type RulePosition string

RulePosition holds the -I/-A flags for iptable

const (
	// Prepend is the insert flag for iptable
	Prepend RulePosition = "-I"
	// Append is the append flag for iptable
	Append RulePosition = "-A"
)

type Table

type Table string

Table represents different iptable like filter,nat, mangle and raw

const (
	// TableNAT represents the built-in nat table
	TableNAT Table = "nat"
	// TableFilter represents the built-in filter table
	TableFilter Table = "filter"
	// TableMangle represents the built-in mangle table
	TableMangle Table = "mangle"
)

type Type

type Type string

Type represents the ipset type

const (
	// HashIPPort represents the `hash:ip,port` type ipset.  The hash:ip,port is similar to hash:ip but
	// you can store IP address and protocol-port pairs in it.  TCP, SCTP, UDP, UDPLITE, ICMP and ICMPv6 are supported
	// with port numbers/ICMP(v6) types and other protocol numbers without port information.
	HashIPPort Type = "hash:ip,port"
	// HashIPPortIP represents the `hash:ip,port,ip` type ipset.  The hash:ip,port,ip set type uses a hash to store
	// IP address, port number and a second IP address triples.  The port number is interpreted together with a
	// protocol (default TCP) and zero protocol number cannot be used.
	HashIPPortIP Type = "hash:ip,port,ip"
	// HashIPPortNet represents the `hash:ip,port,net` type ipset.  The hash:ip,port,net set type uses a hash to store IP address, port number and IP network address triples.  The port
	// number is interpreted together with a protocol (default TCP) and zero protocol number cannot be used.   Network address
	// with zero prefix size cannot be stored either.
	HashIPPortNet Type = "hash:ip,port,net"
	// BitmapPort represents the `bitmap:port` type ipset.  The bitmap:port set type uses a memory range, where each bit
	// represents one TCP/UDP port.  A bitmap:port type of set can store up to 65535 ports.
	BitmapPort Type = "bitmap:port"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL