NFTables.Expr.Sets (NFTables v0.8.2)

View Source

Named set matching functions for firewall rules.

This module provides functions to match packets against named sets. Sets are collections of IP addresses, ports, or other values that can be efficiently matched against. Sets must be created separately using the NFTables Builder API.

Common Use Cases

  • IP blocklists and allowlists
  • Port whitelisting
  • Dynamic blacklisting
  • Efficient multi-value matching

Import

import NFTables.Expr.Sets

For more information, see the nftables sets wiki.

Summary

Functions

set(builder \\ Expr.expr(), set_name, match_type)

@spec set(NFTables.Expr.t(), String.t(), atom()) :: NFTables.Expr.t()

Match against a named set.

The set must already exist in the table. Use NFTables.add/2 with set: option to create sets before using them in rules.

Set Types

  • :saddr - Source IP address (supports IPv4 and IPv6 based on family)
  • :daddr - Destination IP address (supports IPv4 and IPv6 based on family)
  • :sport - Source port (requires protocol context: tcp/udp/sctp/dccp)
  • :dport - Destination port (requires protocol context: tcp/udp/sctp/dccp)

Protocol Context

Port matching (:sport, :dport) requires protocol context from tcp(), udp(), sctp(), or dccp(). IP matching (:saddr, :daddr) uses the rule's family to determine IPv4 ("ip") or IPv6 ("ip6") protocol.

Examples

# IPv4 blocklist
set("@ipv4_blocklist", :saddr) |> drop()

# IPv6 blocklist - automatically uses ip6 protocol
expr(family: :inet6)
|> set("@ipv6_blocklist", :saddr)
|> drop()

# TCP port set - requires tcp() for protocol context
tcp()
|> set("@allowed_ports", :dport)
|> accept()

# UDP port set
udp()
|> set("@dns_ports", :sport)
|> accept()

# Whitelist specific IPs for SSH
tcp()
|> dport(22)
|> set("@ssh_allowed", :saddr)
|> accept()

Creating Sets

Sets must be created before use:

NFTables.add(table: "filter")
|> NFTables.add(set: "ipv4_blocklist", type: :ipv4_addr)
|> NFTables.add(element: ["1.2.3.4", "5.6.7.8"], set: "ipv4_blocklist")
|> NFTables.submit(pid: pid)

Error Handling

This function will raise an ArgumentError if:

  • Port matching is used without protocol context
  • Invalid match type is specified