PF(4)

πŸ“¦
version 15.1 Β· 4 versions
, in freebsd 15.1, nixpkgs unstable

PF(4) β€” from the Kernel Interfaces Manual β€” okay bestie, buckle up, because this is the packet filter page and it is a whole saga. πŸ’…βœ¨

πŸ¦‹ NAME πŸ¦‹

pf β€” packet filter. that’s the whole name, no cap. πŸŽ€

🌸 SYNOPSIS 🌸

device pf
options PF_DEFAULT_TO_DROP

In rc.conf(5):

pf_enable="YES"

In loader.conf(5):

net.pf.states_hashsize
net.pf.source_nodes_hashsize
net.pf.rule_tag_hashsize
net.pf.udpendpoint_hashsize
net.pf.default_to_drop

In sysctl.conf(5):

net.pf.request_maxcount
net.pf.filter_local

✨ DESCRIPTION ✨

Okay so packet filtering happens in the kernel. There’s this pseudo-device, /dev/pf, and it lets userland processes control how the packet filter behaves through an ioctl(2) interface. There are commands to enable and disable the filter, load rulesets, add and remove individual rules or state table entries, and retrieve statistics. The functions people actually use most are covered by pfctl(8) β€” icon behavior, honestly. πŸ‘‘

Manipulations like loading a ruleset that involve more than a single ioctl(2) call require a so-called ticket, and that ticket prevents multiple concurrent manipulations from stepping on each other. no chaos allowed. πŸ’…

Fields of ioctl(2) parameter structures that refer to packet data (like addresses and ports) are generally expected in network byte-order. yes, network byte-order. it’s giving β€œrespect the endianness.” πŸ¦‹

Rules and address tables live in so-called anchors. When the kernel is servicing an ioctl(2) request, if the anchor field of the argument structure is empty, the kernel will use the default anchor (i.e., the main ruleset) in operations. Anchors are specified by name and may be nested, with components separated by / characters, similar to how file system hierarchies are laid out. The final component of the anchor path is the anchor under which operations will be performed. nested anchors are lowkey iconic. 🌸


πŸŽ€ SYSCTL VARIABLES πŸŽ€

The following variables can be entered at the loader(8) prompt, set in loader.conf(5), sysctl.conf(5), or changed at runtime with sysctl(8):

  • net.pf.filter_local β€” this tells pf to also filter on the loopback output hook. it’s typically used to allow redirect rules to adjust the source address. πŸ’«
  • net.pf.request_maxcount β€” the maximum number of items in a single ioctl call. cap it, bestie. 🧒

🧚 LOADER TUNABLES 🧚

The following tunables can be entered at the loader(8) prompt, or set in loader.conf(5):

  • net.pf.states_hashsize β€” size of the hash table that stores states. should be power of 2. default value is 131072. ✨
  • net.pf.source_nodes_hashsize β€” size of the hash table that stores source nodes. should be power of 2. default value is 32768. 🌈
  • net.pf.rule_tag_hashsize β€” size of the hash table that stores tags. that’s it, that’s the description. πŸŽ€
  • net.pf.udpendpoint_hashsize β€” size of the hash table that stores UDP endpoint mappings. should be power of 2. default value is 32768. 🫢
  • net.pf.default_to_drop β€” this value overrides options PF_DEFAULT_TO_DROP from the kernel configuration file. spicy override energy. 🌢️
  • net.pf.filter_local β€” this tells pf to also filter on the loopback output hook. this is typically used to allow redirect rules to adjust the source address. (yes, it’s here too β€” main character appears twice.) πŸ‘‘
  • net.pf.request_maxcount β€” the maximum number of items in a single ioctl call. same queen, different section. πŸ’…

Read only sysctl(8) variables with matching names are provided to obtain current values at runtime. handy. πŸ¦‹


⭐ KERNEL OPTIONS ⭐

The following options in the kernel configuration file are related to pf operation:

  • PF_DEFAULT_TO_DROP β€” change default policy to drop by default. bold move, but make it. πŸ’€

πŸ’– IOCTL INTERFACE πŸ’–

pf supports the following ioctl(2) commands, available through <net/pfvar.h>:

  • DIOCSTART β€” start the packet filter. let’s gooo. πŸ”₯
  • DIOCSTOP β€” stop the packet filter. okay we’re done here. βœ‹
  • DIOCSTARTALTQ β€” start the ALTQ bandwidth control system (see altq(9)). ✨
  • DIOCSTOPALTQ β€” stop the ALTQ bandwidth control system. πŸ›‘
  • DIOCBEGINADDRS struct pfioc_pooladdr *pp β€” clear the buffer address pool and get a ticket for subsequent DIOCADDADDR, DIOCADDRULE, and DIOCCHANGERULE calls.
struct pfioc_pooladdr {
        u_int32_t               action;
        u_int32_t               ticket;
        u_int32_t               nr;
        u_int32_t               r_num;
        u_int8_t                r_action;
        u_int8_t                r_last;
        u_int8_t                af;
        char                    anchor[MAXPATHLEN];
        struct pf_pooladdr      addr;
};
  • DIOCADDADDR struct pfioc_pooladdr *pp β€” add the pool address addr to the buffer address pool to be used in the following DIOCADDRULE or DIOCCHANGERULE call. all other members of the structure are ignored. πŸ™ˆ
  • DIOCADDRULE struct pfioc_rule *pr β€” add rule at the end of the inactive ruleset. this call requires a ticket obtained through a preceding DIOCXBEGIN call and a pool_ticket obtained through a DIOCBEGINADDRS call. DIOCADDADDR must also be called if any pool addresses are required. the optional anchor name indicates the anchor in which to append the rule. nr and action are ignored.
struct pfioc_rule {
        u_int32_t       action;
        u_int32_t       ticket;
        u_int32_t       pool_ticket;
        u_int32_t       nr;
        char            anchor[MAXPATHLEN];
        char            anchor_call[MAXPATHLEN];
        struct pf_rule  rule;
};
  • DIOCADDALTQ struct pfioc_altq *pa β€” add an ALTQ discipline or queue. 🌈
struct pfioc_altq {
        u_int32_t       action;
        u_int32_t       ticket;
        u_int32_t       nr;
        struct pf_altq  altq;
};
  • DIOCGETRULES struct pfioc_rule *pr β€” get a ticket for subsequent DIOCGETRULE calls and the number nr of rules in the active ruleset. 🎟️
  • DIOCGETRULE struct pfioc_rule *pr β€” get a rule by its number nr using the ticket obtained through a preceding DIOCGETRULES call. if action is set to PF_GET_CLR_CNTR, the per-rule statistics on the requested rule are cleared. πŸ’…
  • DIOCGETADDRS struct pfioc_pooladdr *pp β€” get a ticket for subsequent DIOCGETADDR calls and the number nr of pool addresses in the rule specified with r_action, r_num, and anchor. πŸŽ€
  • DIOCGETADDR struct pfioc_pooladdr *pp β€” get the pool address addr by its number nr from the rule specified with r_action, r_num, and anchor using the ticket obtained through a preceding DIOCGETADDRS call. πŸ¦‹
  • DIOCGETALTQS struct pfioc_altq *pa β€” get a ticket for subsequent DIOCGETALTQ calls and the number nr of queues in the active list. ✨
  • DIOCGETALTQ struct pfioc_altq *pa β€” get the queueing discipline altq by its number nr using the ticket obtained through a preceding DIOCGETALTQS call. πŸ’«
  • DIOCGETQSTATS struct pfioc_qstats *pq β€” get the statistics on a queue.
struct pfioc_qstats {
        u_int32_t        ticket;
        u_int32_t        nr;
        void            *buf;
        int              nbytes;
        u_int8_t         scheduler;
};

This call fills in a pointer to the buffer of statistics buf, of length nbytes, for the queue specified by nr. stats queen. πŸ“Š

  • DIOCGETRULESETS struct pfioc_ruleset *pr β€” get the number nr of rulesets (i.e., anchors) directly attached to the anchor named by path for use in subsequent DIOCGETRULESET calls. nested anchors, since they are not directly attached to the given anchor, will not be included. this ioctl returns ENOENT if the parent anchor given at path does not exist. πŸ’…
struct pfioc_ruleset {
        u_int32_t        nr;
        char             path[MAXPATHLEN];
        char             name[PF_ANCHOR_NAME_SIZE];
};
  • DIOCGETRULESET struct pfioc_ruleset *pr β€” get a ruleset (i.e., an anchor) name by its number nr from the given anchor path, the maximum number of which can be obtained from a preceding DIOCGETRULESETS call. this ioctl returns ENOENT if the parent anchor given by path does not exist or EBUSY if the index passed in by nr is greater than the number of anchors. 😭
  • DIOCADDSTATE struct pfioc_state *ps β€” add a state entry.
struct pfioc_state {
        struct pfsync_state     state;
};
  • DIOCGETSTATENV struct pfioc_nv *nv β€” extract the entry identified by the id and creatorid fields of the state nvlist from the state table. πŸ”
  • DIOCKILLSTATESNV struct pfioc_nv nv β€” remove matching entries from the state table. this ioctl returns the number of killed states in killed. πŸ’€
nvlist pf_state_cmp {
        number                  id;
        number                  creatorid;
        number                  direction;
};

nvlist pf_kill {
        nvlist pf_state_cmp     cmp;
        number                  af;
        number                  proto;
        nvlist pf_rule_addr     src;
        nvlist pf_rule_addr     dst;
        string                  ifname[IFNAMSIZ];
        string                  label[PF_RULE_LABEL_SIZE];
};
  • DIOCCLRSTATESNV struct pfioc_nv nv β€” clear all states. it works like DIOCKILLSTATESNV, but ignores the af, proto, src, and dst fields of the pf_kill nvlist. 🧹
  • DIOCSETSTATUSIF struct pfioc_if *pi β€” specify the interface for which statistics are accumulated.
struct pfioc_if {
        char             ifname[IFNAMSIZ];
};
  • DIOCGETSTATUS struct pf_status *s β€” get the internal packet filter statistics. πŸ“ˆ
struct pf_status {
        u_int64_t       counters[PFRES_MAX];
        u_int64_t       lcounters[LCNT_MAX];
        u_int64_t       fcounters[FCNT_MAX];
        u_int64_t       scounters[SCNT_MAX];
        u_int64_t       pcounters[2][2][3];
        u_int64_t       bcounters[2][2];
        u_int32_t       running;
        u_int32_t       states;
        u_int32_t       src_nodes;
        u_int32_t       since;
        u_int32_t       debug;
        u_int32_t       hostid;
        char            ifname[IFNAMSIZ];
        u_int8_t        pf_chksum[MD5_DIGEST_LENGTH];
};
  • DIOCCLRSTATUS β€” clear the internal packet filter statistics. fresh start, bestie. ✨

Okay so we’re still deep in the ioctl era of this page, and this is where the structs start showing off their whole personality. πŸ’… Grab a snack, bestie β€” these are the calls that poke at states, rules, timeouts, limits, and radix tables. No cap, every field stays exactly where it was.

  • DIOCNATLOOK struct pfioc_natlook *pnl β€” Look up a state table entry by source and destination addresses and ports. This is the β€œwhere’s my state?” button, lowkey. πŸ¦‹
struct pfioc_natlook {
        struct pf_addr   saddr;
        struct pf_addr   daddr;
        struct pf_addr   rsaddr;
        struct pf_addr   rdaddr;
        u_int16_t        sport;
        u_int16_t        dport;
        u_int16_t        rsport;
        u_int16_t        rdport;
        sa_family_t      af;
        u_int8_t         proto;
        u_int8_t         direction;
};
  • DIOCSETDEBUG u_int32_t *level β€” Set the debug level. The enum values are the whole vibe check:
enum    { PF_DEBUG_NONE, PF_DEBUG_URGENT, PF_DEBUG_MISC,
          PF_DEBUG_NOISY };
  • DIOCGETSTATESV2 struct pfioc_states_v2 *ps β€” Get state table entries. Yes, V2. She’s upgraded and she has the receipts. ✨
struct pfioc_states_v2 {
        int             ps_len;
        uint64_t        ps_req_version;
        union {
                void                    *ps_buf;
                struct pf_state_export  *ps_states;
        };
};
struct pf_state_export {
        uint64_t         version;
        uint64_t         id;
        char             ifname[IFNAMSIZ];
        char             orig_ifname[IFNAMSIZ];
        struct pf_state_key_export       key[2];
        struct pf_state_peer_export      src;
        struct pf_state_peer_export      dst;
        struct pf_addr   rt_addr;
        uint32_t         rule;
        uint32_t         anchor;
        uint32_t         nat_rule;
        uint32_t         creation;
        uint32_t         expire;
        uint32_t         spare0;
        uint64_t         packets[2];
        uint64_t         bytes[2];
        uint32_t         creatorid;
        uint32_t         spare1;
        sa_family_t      af;
        uint8_t          proto;
        uint8_t          direction;
        uint8_t          log;
        uint8_t          state_flags_compat;
        uint8_t          timeout;
        uint8_t          sync_flags;
        uint8_t          updates;
        uint16_t         state_flags;
        uint16_t         qid;
        uint16_t         pqid;
        uint16_t         dnpipe;
        uint16_t         dnrpipe;
        int32_t          rtableid;
        uint8_t          min_ttl;
        uint8_t          set_tos;
        uint16_t         max_mss;
        uint8_t          set_prio[2];
        uint8_t          rt;
        char             rt_ifname[IFNAMSIZ];
        uint8_t          spare[72];
};
  • DIOCCHANGERULE struct pfioc_rule *pcr β€” Add or remove the rule in the ruleset specified by rule.action. The operation type lives in action, and it can be any of the following:
enum    { PF_CHANGE_NONE, PF_CHANGE_ADD_HEAD, PF_CHANGE_ADD_TAIL,
          PF_CHANGE_ADD_BEFORE, PF_CHANGE_ADD_AFTER,
          PF_CHANGE_REMOVE, PF_CHANGE_GET_TICKET };

ticket must be set to the value obtained with PF_CHANGE_GET_TICKET for all actions except PF_CHANGE_GET_TICKET. pool_ticket must be set to the value obtained with the DIOCBEGINADDRS call for all actions except PF_CHANGE_REMOVE and PF_CHANGE_GET_TICKET. anchor indicates to which anchor the operation applies. nr indicates the rule number against which PF_CHANGE_ADD_BEFORE, PF_CHANGE_ADD_AFTER, or PF_CHANGE_REMOVE actions are applied.

  • DIOCCHANGEADDR struct pfioc_pooladdr *pca β€” Add or remove the pool address addr from the rule specified by r_action, r_num, and anchor.
  • DIOCSETTIMEOUT struct pfioc_tm *pt β€” Set the state timeout of timeout to seconds. The old value will be placed into seconds, which is giving β€œnew value in, old value out.” πŸ”
struct pfioc_tm {
        int              timeout;
        int              seconds;
};

For possible values of timeout, consult the PFTM_* values in ⟨net/pfvar.h⟩. Not me guessing β€” the header is the source. πŸ“š

  • DIOCGETTIMEOUT struct pfioc_tm *pt β€” Get the state timeout of timeout. The value will be placed into the seconds field. Simple, iconic, done. πŸŽ€
  • DIOCCLRRULECTRS β€” Clear per-rule statistics. Stats? Gone. Reset. Periodt. 🧹
  • DIOCSETLIMIT struct pfioc_limit *pl β€” Set the hard limits on the memory pools used by the packet filter. Here’s the struct and the limit enum, bestie:
struct pfioc_limit {
        int             index;
        unsigned        limit;
};

enum    { PF_LIMIT_STATES, PF_LIMIT_SRC_NODES, PF_LIMIT_FRAGS,
          PF_LIMIT_TABLE_ENTRIES, PF_LIMIT_MAX };
  • DIOCGETLIMIT struct pfioc_limit *pl β€” Get the hard limit for the memory pool indicated by index.
  • DIOCRCLRTABLES struct pfioc_table *io β€” Clear all tables. All the ioctls that manipulate radix tables use the same structure described below. For DIOCRCLRTABLES, pfrio_ndel contains on exit the number of tables deleted. The shared pfioc_table struct and its alias macros are:
struct pfioc_table {
        struct pfr_table         pfrio_table;
        void                    *pfrio_buffer;
        int                      pfrio_esize;
        int                      pfrio_size;
        int                      pfrio_size2;
        int                      pfrio_nadd;
        int                      pfrio_ndel;
        int                      pfrio_nchange;
        int                      pfrio_flags;
        u_int32_t                pfrio_ticket;
};
#define pfrio_exists    pfrio_nadd
#define pfrio_nzero     pfrio_nadd
#define pfrio_nmatch    pfrio_nadd
#define pfrio_naddr     pfrio_size2
#define pfrio_setflag   pfrio_size2
#define pfrio_clrflag   pfrio_nadd
  • DIOCRADDTABLES struct pfioc_table *io β€” Create one or more tables. On entry, pfrio_buffer must point to an array of struct pfr_table containing at least pfrio_size elements. pfrio_esize must be the size of struct pfr_table. On exit, pfrio_nadd contains the number of tables effectively created. The pfr_table struct is:
struct pfr_table {
        char            pfrt_anchor[MAXPATHLEN];
        char            pfrt_name[PF_TABLE_NAME_SIZE];
        u_int32_t       pfrt_flags;
        u_int8_t        pfrt_fback;
};
  • DIOCRDELTABLES struct pfioc_table *io β€” Delete one or more tables. On entry, pfrio_buffer must point to an array of struct pfr_table containing at least pfrio_size elements. pfrio_esize must be the size of struct pfr_table. On exit, pfrio_ndel contains the number of tables effectively deleted.
  • DIOCRGETTABLES struct pfioc_table *io β€” Get the list of all tables. On entry, pfrio_buffer[pfrio_size] contains a valid writeable buffer for pfr_table structures. On exit, pfrio_size contains the number of tables written into the buffer. If the buffer is too small, the kernel does not store anything but just returns the required buffer size, without error. Iconic β€œtell me how much room I need” behaviour. πŸ“
  • DIOCRGETTSTATS struct pfioc_table *io β€” This call is like DIOCRGETTABLES but is used to get an array of pfr_tstats structures. The stats struct is a whole mood:
struct pfr_tstats {
        struct pfr_table pfrts_t;
        u_int64_t        pfrts_packets
                             [PFR_DIR_MAX][PFR_OP_TABLE_MAX];
        u_int64_t        pfrts_bytes
                             [PFR_DIR_MAX][PFR_OP_TABLE_MAX];
        u_int64_t        pfrts_match;
        u_int64_t        pfrts_nomatch;
        time_t           pfrts_tzero;
        int              pfrts_cnt;
        int              pfrts_refcnt[PFR_REFCNT_MAX];
};
#define pfrts_name       pfrts_t.pfrt_name
#define pfrts_flags      pfrts_t.pfrt_flags
  • DIOCRCLRTSTATS struct pfioc_table *io β€” Clear the statistics of one or more tables. On entry, pfrio_buffer must point to an array of struct pfr_table containing at least pfrio_size elements. pfrio_esize must be the size of struct pfr_table. On exit, pfrio_nzero contains the number of tables effectively cleared.
  • DIOCRCLRADDRS struct pfioc_table *io β€” Clear all addresses in a table. On entry, pfrio_table contains the table to clear. On exit, pfrio_ndel contains the number of addresses removed.
  • DIOCRADDADDRS struct pfioc_table *io β€” Add one or more addresses to a table. On entry, pfrio_table contains the table ID and pfrio_buffer must point to an array of struct pfr_addr containing at least pfrio_size elements to add to the table. pfrio_esize must be the size of struct pfr_addr. On exit, pfrio_nadd contains the number of addresses effectively added. The pfr_addr struct keeps it cute with a union and some defines:
struct pfr_addr {
        union {
                struct in_addr   _pfra_ip4addr;
                struct in6_addr  _pfra_ip6addr;
        }                pfra_u;
        u_int8_t         pfra_af;
        u_int8_t         pfra_net;
        u_int8_t         pfra_not;
        u_int8_t         pfra_fback;
};
#define pfra_ip4addr    pfra_u._pfra_ip4addr
#define pfra_ip6addr    pfra_u._pfra_ip6addr
  • DIOCRDELADDRS struct pfioc_table *io β€” Delete one or more addresses from a table. On entry, pfrio_table contains the table ID and pfrio_buffer must point to an array of struct pfr_addr containing at least pfrio_size elements to delete from the table. pfrio_esize must be the size of struct pfr_addr. On exit, pfrio_ndel contains the number of addresses effectively deleted.
  • DIOCRSETADDRS struct pfioc_table *io β€” Replace the content of a table by a new address list. This is the most complicated command, which uses all the structure members. She ate and left no crumbs, but also she needs every single member. πŸ’€πŸ‘‘

Okay so this next chunk is all about the table-manipulation ioctls, and honestly? It's giving "kernel API appreciation post" πŸ’…


On entry, pfrio_table contains the table ID and pfrio_buffer must point to an array of struct pfr_addr containing at least pfrio_size elements which become the new contents of the table. pfrio_esize must be the size of struct pfr_addr. Additionally, if pfrio_size2 is non-zero, pfrio_buffer[pfrio_size..pfrio_size2] must be a writeable buffer, into which the kernel can copy the addresses that have been deleted during the replace operation. On exit, pfrio_ndel, pfrio_nadd, and pfrio_nchange contain the number of addresses deleted, added, and changed by the kernel. If pfrio_size2 was set on entry, pfrio_size2 will point to the size of the buffer used, exactly like DIOCRGETADDRS.

🌸 DIOCRGETADDRS struct pfioc_table *io

Get all the addresses of a table, bestie β€” every single one. On entry, pfrio_table contains the table ID and pfrio_buffer[pfrio_size] contains a valid writeable buffer for pfr_addr structures. On exit, pfrio_size contains the number of addresses written into the buffer. If the buffer was too small, the kernel does not store anything but just returns the required buffer size, without returning an error. (Iconic behavior tbh β€” it tells you how much room it needs instead of just being dramatic about it. 🫢)

🌈 DIOCRGETASTATS struct pfioc_table *io

This call is like DIOCRGETADDRS but is used to get an array of pfr_astats structures.

struct pfr_astats {
        struct pfr_addr  pfras_a;
        u_int64_t        pfras_packets
                             [PFR_DIR_MAX][PFR_OP_ADDR_MAX];
        u_int64_t        pfras_bytes
                             [PFR_DIR_MAX][PFR_OP_ADDR_MAX];
        time_t           pfras_tzero;
};

πŸŽ€ DIOCRCLRASTATS struct pfioc_table *io

Clear the statistics of one or more addresses. Fresh-start energy ✨. On entry, pfrio_table contains the table ID and pfrio_buffer must point to an array of struct pfr_addr containing at least pfrio_size elements to be cleared from the table. pfrio_esize must be the size of struct pfr_addr. On exit, pfrio_nzero contains the number of addresses effectively cleared.

πŸ¦‹ DIOCRTSTADDRS struct pfioc_table *io

Test if the given addresses match a table β€” like a vibe check but for addresses. On entry, pfrio_table contains the table ID and pfrio_buffer must point to an array of struct pfr_addr containing at least pfrio_size elements, each of which will be tested for a match in the table. pfrio_esize must be the size of struct pfr_addr. On exit, the kernel updates the pfr_addr array by setting the pfra_fback member appropriately.

πŸ’œ DIOCRSETTFLAGS struct pfioc_table *io

Change the PFR_TFLAG_CONST or PFR_TFLAG_PERSIST flags of a table. On entry, pfrio_buffer must point to an array of struct pfr_table containing at least pfrio_size elements. pfrio_esize must be the size of struct pfr_table. pfrio_setflag must contain the flags to add, while pfrio_clrflag must contain the flags to remove. On exit, pfrio_nchange and pfrio_ndel contain the number of tables altered or deleted by the kernel.

Yes, tables can be deleted if one removes the PFR_TFLAG_PERSIST flag of an unreferenced table. Not a drill, bestie β€” removing that flag can genuinely yeet the whole table. πŸ’€

🧚 DIOCRINADEFINE struct pfioc_table *io

Defines a table in the inactive set. On entry, pfrio_table contains the table ID and pfrio_buffer[pfrio_size] contains an array of pfr_addr structures to put in the table. A valid ticket must also be supplied to pfrio_ticket. On exit, pfrio_nadd contains 0 if the table was already defined in the inactive list or 1 if a new table has been created. pfrio_naddr contains the number of addresses effectively put in the table.

πŸ‘‘ DIOCXBEGIN struct pfioc_trans *io

struct pfioc_trans {
        int              size;  /* number of elements */
        int              esize; /* size of each element in bytes */
        struct pfioc_trans_e {
                int             rs_num;
                char            anchor[MAXPATHLEN];
                u_int32_t       ticket;
        }               *array;
};

Clear all the inactive rulesets specified in the pfioc_trans_e array. For each ruleset, a ticket is returned for subsequent "add rule" ioctls, as well as for the DIOCXCOMMIT and DIOCXROLLBACK calls.

Ruleset types, identified by rs_num, include the following:

  • PF_RULESET_SCRUB β€” Scrub (packet normalization) rules.
  • PF_RULESET_FILTER β€” Filter rules.
  • PF_RULESET_NAT β€” NAT (Network Address Translation) rules.
  • PF_RULESET_BINAT β€” Bidirectional NAT rules.
  • PF_RULESET_RDR β€” Redirect rules.
  • PF_RULESET_ALTQ β€” ALTQ disciplines.
  • PF_RULESET_TABLE β€” Address tables.

πŸ”₯ DIOCXCOMMIT struct pfioc_trans *io

Atomically switch a vector of inactive rulesets to the active rulesets. This call is implemented as a standard two-phase commit, which will either fail for all rulesets or completely succeed β€” all-or-nothing, main character energy fr fr. All tickets need to be valid. This ioctl returns EBUSY if another process is concurrently updating some of the same rulesets.

πŸ“ DIOCXROLLBACK struct pfioc_trans *io

Clean up the kernel by undoing all changes that have taken place on the inactive rulesets since the last DIOCXBEGIN. DIOCXROLLBACK will silently ignore rulesets for which the ticket is invalid. (Silently ignoring? She's so unbothered. πŸ™ˆ)

⭐ DIOCSETHOSTID u_int32_t *hostid

Set the host ID, which is used by pfsync(4) to identify which host created state table entries. Gotta know who's who, periodt.

πŸ’… DIOCOSFPFLUSH

Flush the passive OS fingerprint table. Bye-bye fingerprints, it's a clean slate ✨.

🌸 DIOCOSFPADD struct pf_osfp_ioctl *io

struct pf_osfp_ioctl {
        struct pf_osfp_entry {
                SLIST_ENTRY(pf_osfp_entry) fp_entry;
                pf_osfp_t               fp_os;
                char                    fp_class_nm[PF_OSFP_LEN];
                char                    fp_version_nm[PF_OSFP_LEN];
                char                    fp_subtype_nm[PF_OSFP_LEN];
        }                       fp_os;
        pf_tcpopts_t            fp_tcpopts;
        u_int16_t               fp_wsize;
        u_int16_t               fp_psize;
        u_int16_t               fp_mss;
        u_int16_t               fp_flags;
        u_int8_t                fp_optcnt;
        u_int8_t                fp_wscale;
        u_int8_t                fp_ttl;
        int                     fp_getnum;
};

Add a passive OS fingerprint to the table. Set fp_os.fp_os to the packed fingerprint, fp_os.fp_class_nm to the name of the class (Linux, Windows, etc), fp_os.fp_version_nm to the name of the version (NT, 95, 98), and fp_os.fp_subtype_nm to the name of the subtype or patchlevel. The members fp_mss, fp_wsize, fp_psize, fp_ttl, fp_optcnt, and fp_wscale are set to the TCP MSS, the TCP window size, the IP length, the IP TTL, the number of TCP options, and the TCP window scaling constant of the TCP SYN packet, respectively.

The fp_flags member is filled according to the ⟨net/pfvar.h⟩ include file PF_OSFP_* defines. The fp_tcpopts member contains packed TCP options. Each option uses PF_OSFP_TCPOPT_BITS bits in the packed value. Options include any of PF_OSFP_TCPOPT_NOP, PF_OSFP_TCPOPT_SACK, PF_OSFP_TCPOPT_WSCALE, PF_OSFP_TCPOPT_MSS, or PF_OSFP_TCPOPT_TS.

The fp_getnum member is not used with this ioctl.

The structure's slack space must be zeroed for correct operation; memset(3) the whole structure to zero before filling and sending to the kernel. No skipping this step, bestie β€” zero it out first or it's not gonna work. πŸ’€

πŸ¦‹ DIOCOSFPGET struct pf_osfp_ioctl *io

Get the passive OS fingerprint number fp_getnum from the kernel's fingerprint list. The rest of the structure members will come back filled. Get the whole list by repeatedly incrementing the fp_getnum number until the ioctl returns EBUSY. Lowkey a little loop-until-it-says-no situation, iykyk.

🌈 DIOCGETSRCNODES struct pfioc_src_nodes *psn

struct pfioc_src_nodes {
        int     psn_len;
        union {
                caddr_t         psu_buf;
                struct pf_src_node      *psu_src_nodes;
        } psn_u;
#define psn_buf         psn_u.psu_buf
#define psn_src_nodes   psn_u.psu_src_nodes
};

Get the list of source nodes kept by sticky addresses and source tracking. The ioctl must be called once with psn_len set to 0. If the ioctl returns without error, psn_len will be set to the size of the buffer required to hold all the pf_src_node structures held in the table. A buffer of this size should then be allocated, and a pointer to this buffer placed in psn_buf. The ioctl must then be called again to fill this buffer with the actual source node data. After that call, psn_len will be set to the length of the buffer actually used. Two-step process, bestie β€” measure first, then grab the goods. 🫢

πŸŽ€ DIOCCLRSRCNODES

Clear the tree of source tracking nodes. Marie Kondo that tree ✨.

πŸ’œ DIOCIGETIFACES struct pfioc_iface *io

Get the list of interfaces and interface groups known to pf. All the ioctls that manipulate interfaces use the same structure described below:

struct pfioc_iface {
        char                     pfiio_name[IFNAMSIZ];
        void                    *pfiio_buffer;
        int                      pfiio_esize;
        int                      pfiio_size;
        int                      pfiio_nzero;
        int                      pfiio_flags;
};

If not empty, pfiio_name can be used to restrict the search to a specific interface or group. pfiio_buffer[pfiio_size] is the user-supplied buffer for returning the data. On entry, pfiio_size contains the number of pfi_kif entries that can fit into the buffer. The kernel will replace this value by the real number of entries it wants to return. pfiio_esize should be set to sizeof(struct pfi_kif).

The data is returned in the pfi_kif structure described below:

struct pfi_kif {
        char                             pfik_name[IFNAMSIZ];
        union {
                RB_ENTRY(pfi_kif)        pfik_tree;
                LIST_ENTRY(pfi_kif)      pfik_list;
        };
        u_int64_t                        pfik_packets[2][2][2];
        u_int64_t                        pfik_bytes[2][2][2];
        u_int32_t                        pfik_tzero;
        u_int                            pfik_flags;
        struct ifnet                    *pfik_ifp;
        struct ifg_group                *pfik_group;
        u_int                            pfik_rulerefs;
        TAILQ_HEAD(, pfi_dynaddr)        pfik_dynaddrs;
};

That's the whole record, bestie β€” no notes, no extra fields, that's the roster πŸ‘‘. The way it's holding a char name array sized IFNAMSIZ, a union that's either an RB_ENTRY(pfi_kif) tree link or a LIST_ENTRY(pfi_kif) list link (pick a lane, king), nested pfik_packets[2][2][2] and pfik_bytes[2][2][2] counters that are giving very thorough, plus pfik_tzero, pfik_flags, a struct ifnet *pfik_ifp, a struct ifg_group *pfik_group, pfik_rulerefs, and a TAILQ_HEAD(, pfi_dynaddr) of dynamic addresses. Literally all of it, nothing skipped πŸ’…


  • DIOCSETIFFLAG struct pfioc_iface *io β€” sets the user settable flags (the ones described above, up in the ioctl section) on pf's internal interface description. And the filtering process? Same as for DIOCIGETIFACES, exactly.
#define PFI_IFLAG_SKIP  0x0100  /* skip filtering on interface */
  • DIOCCLRIFFLAG struct pfioc_iface *io β€” the opposite twin 🫢 works just like DIOCSETIFFLAG above but clears the flags.
  • DIOCKILLSRCNODES struct pfioc_iface *io β€” explicitly removes source tracking nodes. Like, be gone πŸ‘‹πŸ”ͺ

🌸 FILES 🌸

  • /dev/pf β€” the packet filtering device. That's the door you knock on, girlie πŸšͺ✨

πŸ’– EXAMPLES πŸ’–

Okay so the example below is the moment you've all been waiting for β€” it shows you how to use the DIOCNATLOOK command to find the internal host/port of a NATed connection πŸ”πŸ¦‹

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/fcntl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <net/pfvar.h>
#include <err.h>
#include <stdio.h>
#include <stdlib.h>

u_int32_t
read_address(const char *s)
{
        int a, b, c, d;

        sscanf(s, "%i.%i.%i.%i", &a, &b, &c, &d);
        return htonl(a << 24 | b << 16 | c << 8 | d);
}

void
print_address(u_int32_t a)
{
        a = ntohl(a);
        printf("%d.%d.%d.%d", a >> 24 & 255, a >> 16 & 255,
            a >> 8 & 255, a & 255);
}

int
main(int argc, char *argv[])
{
        struct pfioc_natlook nl;
        int dev;

        if (argc != 5) {
                printf("%s <gwy addr> <gwy port> <ext addr> <ext port>\n",
                    argv[0]);
                return 1;
        }

        dev = open("/dev/pf", O_RDWR);
        if (dev == -1)
                err(1, "open(\"/dev/pf\") failed");

        memset(&nl, 0, sizeof(struct pfioc_natlook));
        nl.saddr.v4.s_addr      = read_address(argv[1]);
        nl.sport                = htons(atoi(argv[2]));
        nl.daddr.v4.s_addr      = read_address(argv[3]);
        nl.dport                = htons(atoi(argv[4]));
        nl.af                   = AF_INET;
        nl.proto                = IPPROTO_TCP;
        nl.direction            = PF_IN;

        if (ioctl(dev, DIOCNATLOOK, &nl))
                err(1, "DIOCNATLOOK");

        printf("internal host ");
        print_address(nl.rsaddr.v4.s_addr);
        printf(":%u\n", ntohs(nl.rsport));
        return 0;
}

Let me walk you through the vibe check 🧚

There's a little read_address() helper that sscanfs a "%i.%i.%i.%i" dotted quad into four ints and returns htonl of them shifted into place β€” and its bestie print_address(), which untangles one with ntohl and printfs it back out as "%d.%d.%d.%d" with all the & 255 masking πŸŽ€

Then main() takes exactly four arguments in argc != 5 land (argv[0] counts, she's the main character too), and if you don't feed her right she prints:

%s <gwy addr> <gwy port> <ext addr> <ext port>

...and bails with return 1. Then she opens "/dev/pf" with O_RDWR, and if that fails it's err(1, "open(\"/dev/pf\") failed") β€” no cap, you'll know 😭

After that she zeroes out the struct pfioc_natlook nl with memset, fills nl.saddr.v4.s_addr and nl.daddr.v4.s_addr from argv[1]/argv[3] via read_address(), sets nl.sport and nl.dport from argv[2]/argv[4] through htons(atoi(...)), sets nl.af = AF_INET, nl.proto = IPPROTO_TCP, nl.direction = PF_IN β€” and hits the ioctl(dev, DIOCNATLOOK, &nl) 🎯 if that fails it's err(1, "DIOCNATLOOK") πŸ’€

Finally: printf("internal host "), print_address(nl.rsaddr.v4.s_addr), printf(":%u\n", ntohs(nl.rsport)), return 0. Iconic. Ate. Periodt πŸ“πŸ‘‘

🌈 SEE ALSO 🌈

ioctl(2), altq(4), if_bridge(4), pflog(4), pfsync(4), pfctl(8), altq(9) β€” go read the whole family, they're all in the group chat 🫢

How it all started: the pf packet filtering mechanism first appeared in OpenBSD 3.0 and then FreeBSD 5.2 ⭐ And this implementation? It's derived from OpenBSD 4.5, with a bunch of individual features, improvements, bug fixes and security fixes ported over from later versions of OpenBSD ✨ It's also been heavily modified so it can run in the multithreaded FreeBSD kernel and scale its performance across multiple CPUs β€” multi-core main character energy fr fr πŸ”₯πŸ‘‘


Okay that's the whole page bestie, you made it to the end πŸŽ€ This one's from the Debian edition, dated July 2, 2025, and the page itself is PF(4) β€” love her, read her again, mwah πŸ’‹πŸ’–

πŸ“¦ where this page comes from