[go: up one dir, main page]

nftables

package
v2.0.0-beta.0 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2025 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package nftables provides methods to create an nftables table and manage its maps, sets, chains, and rules.

To use it, the first step is to create a Table using NewTable. Then, retrieve a Modifier, add commands to it, and apply the updates.

For example:

t, _ := NewTable(...)
tm := t.Modifier()
// Then a sequence of ...
tm.Create(<object>)
tm.Delete(<object>)
// Apply the updates with ...
err := tm.Apply(ctx)

The objects are any of: BaseChain, Chain, Rule, VMap, VMapElement, Set, SetElement

The modifier can be reused to apply the same set of commands again or, more usefully, reversed in order to revert its changes. See Modifier.Reverse.

[Modifier.Apply] can only be called after Enable, and only if Enable returns true (meaning an "nft" executable was found). Enabled can be called to check whether nftables has been enabled.

Be aware:

  • The implementation is far from complete, only functionality needed so-far has been included. Currently, there's only a limited set of chain/map/set types, there's no way to delete sets/maps etc.
  • This is a thin layer between code and "nft", it doesn't do much error checking. So, for example, if you get the syntax of a rule wrong the issue won't be reported until Apply is called.
  • Also in the category of no-error-checking, there's no reference checking. If you delete a chain that's still referred to by a map, set or another chain, "nft" will report an error when Apply is called.
  • Error checking here is meant to help spot logical errors in the code, like adding a rule twice, which would be fine by "nft" as it'd just create a duplicate rule.
  • The existing state of a table in the ruleset is irrelevant, once a Table is created by this package it will be flushed. Putting it another way, this package is write-only, it does not load any state from the host.
  • Errors from "nft" are logged along with the line-numbered command that failed, that's the place to look when things go wrong.

Index

Constants

View Source
const (
	BaseChainPriorityRaw      = -300
	BaseChainPriorityMangle   = -150
	BaseChainPriorityDstNAT   = -100
	BaseChainPriorityFilter   = 0
	BaseChainPrioritySecurity = 50
	BaseChainPrioritySrcNAT   = 100
)

Standard priority values for base chains. (Not for the bridge family, those are different.)

Variables

This section is empty.

Functions

func Disable

func Disable()

Disable undoes Enable. Intended for unit testing.

func Enable

func Enable() error

Enable tries once to initialise nftables.

func Enabled

func Enabled() bool

Enabled returns true if the "nft" tool is available and Enable has been called.

Types

type BaseChain

type BaseChain struct {
	Name      string
	ChainType BaseChainType
	Hook      BaseChainHook
	Priority  int
	Policy    BaseChainPolicy // Defaults to BaseChainPolicyAccept
}

BaseChain constructs a new nftables base chain and returns a [ChainRef].

See https://wiki.nftables.org/wiki-nftables/index.php/Configuring_chains#Adding_base_chains

It is an error to create a base chain that already exists. If the underlying chain already exists, it will be flushed by the next Table.Apply before new rules are added.

type BaseChainHook

type BaseChainHook string

BaseChainHook enumerates the base chain hook types. See https://wiki.nftables.org/wiki-nftables/index.php/Configuring_chains#Base_chain_hooks

const (
	BaseChainHookIngress     BaseChainHook = "ingress"
	BaseChainHookPrerouting  BaseChainHook = "prerouting"
	BaseChainHookInput       BaseChainHook = "input"
	BaseChainHookForward     BaseChainHook = "forward"
	BaseChainHookOutput      BaseChainHook = "output"
	BaseChainHookPostrouting BaseChainHook = "postrouting"
)

type BaseChainPolicy

type BaseChainPolicy string

BaseChainPolicy enumerates base chain policies. See https://wiki.nftables.org/wiki-nftables/index.php/Configuring_chains#Base_chain_policy

const (
	BaseChainPolicyAccept BaseChainPolicy = "accept"
	BaseChainPolicyDrop   BaseChainPolicy = "drop"
)

type BaseChainType

type BaseChainType string

BaseChainType enumerates the base chain types. See https://wiki.nftables.org/wiki-nftables/index.php/Configuring_chains#Base_chain_types

const (
	BaseChainTypeFilter BaseChainType = "filter"
	BaseChainTypeRoute  BaseChainType = "route"
	BaseChainTypeNAT    BaseChainType = "nat"
)

type Chain

type Chain struct {
	Name string
}

Chain implements the Obj interface, it can be passed to a Modifier to create or delete a chain.

type Family

type Family string

Family enumerates address families.

const (
	IPv4 Family = "ip"
	IPv6 Family = "ip6"
)

type Modifier

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

Modifier is used to apply changes to a Table.

func (*Modifier) Create

func (tm *Modifier) Create(o Obj)

Create enqueues creation of object o, to be applied by tm.Apply.

func (*Modifier) Delete

func (tm *Modifier) Delete(o Obj)

Delete enqueues deletion of object o, to be applied by tm.Apply.

func (*Modifier) Reverse

func (tm *Modifier) Reverse() Modifier

Reverse returns a Modifier that will undo the actions of tm. Its operations are performed in reverse order, creates become deletes, and deletes become creates.

Most operations are fully reversible (chains/maps/sets must be empty before they're deleted, so no information is lost). But, there are exceptions, noted in comments in the object definitions.

Applying the updates in a reversed modifier may not work if any of the objects have been removed or modified since they were added. For example, if a Modifier creates a chain then another Modifier adds rules, the reversed Modifier will not be able to delete the chain as it is not empty.

type NftType

type NftType string

NftType enumerates nft types that can be used to define maps/sets etc.

const (
	NftTypeIPv4Addr    NftType = "ipv4_addr"
	NftTypeIPv6Addr    NftType = "ipv6_addr"
	NftTypeEtherAddr   NftType = "ether_addr"
	NftTypeInetProto   NftType = "inet_proto"
	NftTypeInetService NftType = "inet_service"
	NftTypeMark        NftType = "mark"
	NftTypeIfname      NftType = "ifname"
)

type Obj

type Obj interface {
	// contains filtered or unexported methods
}

Obj is an object that can be given to a Modifier, representing an nftables object for it to create or delete.

type Rule

type Rule struct {
	Chain string
	Group RuleGroup
	Rule  []string
	// IgnoreExist suppresses errors about deleting a rule that does not exist
	// or creating a rule that does already exist.
	//
	// Note that, when set, reversing the [Modifier] may not do what you want! For
	// example, if the original modifier deleted a rule that did not exist, the
	// reversed modifier will create that rule.
	IgnoreExist bool
}

Rule implements the Obj interface, it can be passed to a Modifier to create or delete a rule in a chain.

type RuleGroup

type RuleGroup int

RuleGroup is used to allocate rules within a chain to a group. These groups are purely an internal construct, nftables knows nothing about them. Within groups rules retain the order in which they were added, and groups are ordered from lowest to highest numbered group.

type Set

type Set struct {
	Name        string
	ElementType NftType
	Flags       []string
}

Set implements the Obj interface, it can be passed to a Modifier to create or delete a set.

type SetElement

type SetElement struct {
	SetName string
	Element string
}

SetElement implements the Obj interface, it can be passed to a Modifier to create or delete an entry in a set.

type Table

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

Table is a handle for an nftables table.

func NewTable

func NewTable(family Family, name string) (Table, error)

NewTable creates a new nftables table and returns a Table

See https://wiki.nftables.org/wiki-nftables/index.php/Configuring_tables

To modify the table, instantiate a Modifier, add commands to it, and call Table.Apply.

It's flushed in case it already exists in the host's nftables - when that happens, rules in its chains will be deleted but not the chains themselves, maps, sets, or elements of maps or sets. But, those un-flushed items can't do anything disruptive unless referred to by rules, and they will be flushed if they get re-created via the Table, when Table.Apply is next called (so, before they can be used by a new rule).

To fully delete an underlying nftables table, if one already exists, use Table.Reload after creating the table.

func (*Table) Apply

func (t *Table) Apply(ctx context.Context, tm Modifier) (retErr error)

Apply makes incremental updates to nftables. If there's a validation error in any of the enqueued objects, or an error applying the updates to the underlying nftables, the Table will be unmodified.

func (Table) Family

func (t Table) Family() Family

Family returns the address family of the nftables table described by [TableRef].

func (Table) IsValid

func (t Table) IsValid() bool

IsValid returns true if t is a valid reference to a table.

func (Table) Name

func (t Table) Name() string

Name returns the name of the table, or an empty string if t is not valid.

func (Table) Reload

func (t Table) Reload(ctx context.Context) error

Reload deletes the table, then re-creates it, atomically.

func (Table) SetBaseChainPolicy

func (t Table) SetBaseChainPolicy(ctx context.Context, chainName string, policy BaseChainPolicy) error

SetBaseChainPolicy sets the default policy for a base chain. The update is applied immediately, unlike creation/deletion of objects via a Modifier which are not applied until [Modifier.Apply] is called.

type VMap

type VMap struct {
	Name        string
	ElementType NftType
	Flags       []string
}

VMap implements the Obj interface, it can be passed to a Modifier to create or delete a verdict map.

type VMapElement

type VMapElement struct {
	VmapName string
	Key      string
	Verdict  string
}

VMapElement implements the Obj interface, it can be passed to a Modifier to create or delete an entry in a verdict map.

Jump to

Keyboard shortcuts

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