google/nftables

repository·main·Indexed 23 days ago

https://github.com/google/nftables

A third-party pure Go package for programmatic interaction with Linux nftables. It provides data types and functions to manage tables, chains, rules, and flowtables without dependencies on libnftnl. Key features include support for lasting netlink connections, ruleset generation tracking, and an event-based Monitor for receiving notifications about changes to nftables objects.

Tokens
7.2K
Snippets
6
Records
45
Agent score
79%

What's inside google-nftables

  1. Overview of the nftables Go package

    main

    This repository provides a third-party Go package designed to programmatically interact with Linux nftables (the successor to iptables).

    Key characteristics:

    • Pure Go Implementation: The package is implemented entirely in Go and does not wrap libnftnl.
    • Scope: Currently in early stages, providing basic data types and functions for installing fundamental nftables rules.

    Note: This is NOT the official repository for the Linux nftables project. For official information, visit https://wiki.nftables.org/.

  2. How lasting connections work in nftables

    main

    A lasting connection is a Conn that maintains an open netlink socket across multiple operations, improving efficiency for repeated tasks.

    • Creation: Enabled via the AsLasting() option in New().
    • Lifecycle: You must call CloseLasting() to close the underlying connection and cancel pending operations.
    • Fallback: If you call CloseLasting(), the Conn does not become invalid; instead, it reverts to using on-demand transient netlink connections for subsequent operations.
  3. Use the Obj interface and NamedObj type

    main

    An Obj represents a netfilter stateful object. While Obj is an interface, the NamedObj struct is the standard implementation used to represent object attributes like the table, name, type, and underlying data.

    When working with the API, it is recommended to use NamedObj instead of legacy types like CounterObj or QuotaObj to ensure compatibility with modern retrieval methods like GetNamedObjects or ResetNamedObjects.

  4. Define Set and SetElement structures

    main

    To interact with nftables sets, you must use the Set and SetElement types.

    Set

    Represents the set configuration. Key fields include:

    • Table: The parent Table.
    • Name: The name of the set (empty for anonymous sets).
    • KeyType: The SetDatatype of the set's keys.
    • DataType: The SetDatatype of the set's values (if it is a map).
    • IsMap: Indicates if the set is a map.
    • Concatenation: Indicates if the key is a concatenated type.
    • HasTimeout: Indicates if elements can have individual timeouts.
    • Dynamic: Indicates if the set contains flags dynamic.

    SetElement

    Represents a single entry in a set.

    • Key: The byte slice representing the key.
    • Val: The byte slice representing the value (for maps).
    • KeyEnd: Used for defining the end of an interval in concatenated types.
    • Timeout: The duration before the element expires.
    • Expires: The remaining life of the element.
    • IntervalEnd: Boolean indicating if this is the end of an interval.
  5. Configure TableFlags

    main

    The TableFlags type allows you to set specific behaviors when creating a table:

    • TableFlagDormant: Creates the table in a dormant state. A dormant table does not process packets until it is explicitly activated.
    • TableFlagOwner: Sets the owner of the table to the port ID of the creating connection. The table's lifetime is bound to the lifetime of that connection unless TableFlagPersist is also set.
    • TableFlagPersist: When used with TableFlagOwner, ensures the table is not automatically removed when the creating connection is closed.
  6. Manage nftables rules using the Rule struct

    main
    The Rule struct represents an nftables rule that performs actions on packets. To create or modify rules, you interact with a Conn instance using methods like AddRule, InsertRule, or ReplaceRule.
  7. Configure and use an nftables Monitor

    main

    A Monitor is an event-based mechanism used to receive notifications about changes to nftables objects (tables, chains, rules, sets, etc.).

    To use a monitor, you must follow two steps:

    1. Initialize the monitor using NewMonitor with desired options.
    2. Install the monitor by calling Conn.AddMonitor(monitor) or Conn.AddGenerationalMonitor(monitor).

    Monitoring is filtered by MonitorAction (what happens) and MonitorObject (what is affected).

  8. Use SetDatatype for nftables sets

    main

    A SetDatatype defines the type of data stored in an nftables set (e.g., IP addresses, integers, strings). The package provides several pre-defined datatypes that correspond to standard nft types.

    Commonly used datatypes include:

    • TypeIPAddr: IPv4 addresses (4 bytes)
    • TypeIP6Addr: IPv6 addresses (16 bytes)
    • TypeInteger: Integers (4 bytes)
    • TypeString: Strings
    • TypeEtherAddr: MAC addresses (6 bytes)
    • TypeTCPFlag: TCP flags
    • TypeVerdict: Verdict types (used in maps)

    You can also create concatenated datatypes using ConcatSetType or MustConcatSetType.

  9. Reset stateful expressions with ResetRule

    main

    ResetRule and ResetRules reset stateful expressions (such as counters) within rules. This operation is applied immediately in the kernel and does not require a Flush() to take effect.

    • ResetRule(t *Table, c *Chain, handle uint64) (*Rule, error): Resets the state for a single rule identified by its handle. Returns the rule reflecting its state prior to the reset.
    • ResetRules(t *Table, c *Chain) ([]*Rule, error): Resets the state for all rules in the specified table and chain.
  10. Convert QuotaObj to an expression using data()

    main
    The data() method on a QuotaObj converts the quota object into an expr.Any type. This is used to represent the quota as an nftables expression, specifically wrapping the values into an expr.Quota object containing the Bytes, Consumed, and Over fields.
  11. Manage nftables stateful objects with Conn

    main

    The Conn type provides methods to manage netfilter stateful objects (like counters, quotas, and connection limits) within a table. You can add, delete, retrieve, and reset these objects using the Obj interface.

    Key Operations

    • Add: Use AddObject(o Obj) or its alias AddObj(o Obj) to create a new object.
    • Delete: Use DeleteObject(o Obj) to remove an existing object.
    • Retrieve:
      • GetObject(o Obj): Gets a specific object. Returns the concrete type (e.g., NamedObj).
      • GetNamedObjects(t *Table): Gets all objects in a table as NamedObj types. This is the preferred way to avoid legacy types.
      • GetObjects(t *Table): A legacy method that returns objects as legacy types (e.g., CounterObj).
    • Reset:
      • ResetObject(o Obj): Resets the state of a specific object.
      • ResetNamedObjects(t *Table): Resets all objects in a table using NamedObj types.
  12. Create concatenated datatypes

    main

    In nftables, you can create a set key that is a concatenation of multiple types. Use ConcatSetType to construct a new SetDatatype from a slice of existing datatypes. This is useful for sets that match on multiple fields (e.g., an IP and a port).

    ConcatSetType returns an error if the resulting magic value would overflow (limited to approximately 5 types based on SetConcatTypeBits).

    MustConcatSetType is a helper that panics if the concatenation fails, useful for global variable initialization.