SkillPilotAI

pfctl / pf.conf (2/2)

pf.conf part 2 covers the rules that actually clean, queue, translate and filter packets on macOS, FreeBSD and OpenBSD: scrub, ALTQ, nat/rdr/binat, block/pass with their parameters, state options, routing options, antispoof and anchors.

111.1 The order of pf.conf

  1. Options (set ...)
  2. Normalization (scrub)
  3. Queueing (altq, queue)
  4. Translation (nat, rdr, binat)
  5. Filtering (block, pass)
  • Statements must follow this fixed order; filtering always takes the final decision.
  • pfctl/pf.conf run only on macOS/BSD, so the lab does the same jobs on Linux with nft, iptables and ip rule.

111.2 How nat and rdr work

Output
nat on en0 from 192.168.1.0/24 -> (en0)rdr on en0 proto tcp to port 80 -> 192.168.1.10 port 8080
nat (outbound) and rdr (inbound) on a pf gateway
  1. 1.Office laptop 192.168.1.20 sends HTTPS to 1.1.1.1

  2. 2.pf gateway: nat rewrites src to en0 public IP 203.0.113.10

  3. 3.Packet reaches the internet as src 203.0.113.10

  4. 4.Internet user 198.51.100.7 sends TCP 80 to 203.0.113.10

  5. 5.pf gateway: rdr rewrites dst to 192.168.1.10 port 8080

  6. 6.Request reaches the internal web server

nat changes the source, rdr changes the destination

111.3 Traffic normalization (scrub)

  • Scrub reassembles fragments and cleans odd packets so inside hosts get normal packets.
  • max-mss limits the TCP segment size: very useful on VPN links (avoids fragmentation).
  • no scrub excludes a host from normalization.
Output
scrub in on $ext_if all        # normalize inboundscrub ... fragment reassemble  # buffer + reassemble (also: fragment crop, fragment drop-ovl)scrub ... no-df random-id      # clear DF bit, random IP idscrub ... min-ttl 64 max-mss 1440scrub ... reassemble tcp       # TCP normalizationno scrub from 192.168.1.10     # exclude a host

111.4 Queueing (ALTQ)

  • altq picks a scheduler on the interface: cbq, priq or hfsc, with a total bandwidth.
  • queue lines give each queue its bandwidth and priority; a pass rule assigns traffic with queue(...).
  • hfsc realtime = minimum bandwidth, upperlimit = maximum, linkshare = share under backlog.
Output
altq on en0 cbq bandwidth 5Mb queue { std }   # also priq / hfsc; qlimit 256, tbrsize 3000queue std bandwidth 10% cbq(default)queue ssh on en0 { ssh_interactive, ssh_bulk }queue ... priority 2           # cbq/hfsc 0-7, priq 0-15cbq(borrow) cbq(red) cbq(ecn)  # borrow from parent, RED, ECNhfsc(realtime 5Mb) hfsc(upperlimit 40Mb) hfsc(linkshare (m1 d m2))pass ... queue(ssh_bulk, ssh_interactive)   # use the queue in a rule

111.5 Translation (nat, rdr, binat)

  • nat rewrites the source of outgoing packets; ($ext_if) in brackets follows IP changes.
  • rdr redirects incoming packets to another address or port.
  • binat maps one internal IP to one public IP in both directions (1:1).
  • nat pass / rdr pass skip the filter rules; newer OpenBSD uses nat-to and rdr-to on pass rules instead.
Output
nat on $ext_if from $lan -> ($ext_if)       # (brackets) follow IP changesnat pass log ...                            # skip filter rules (+ log)no nat on $ext_if proto ah                  # no translationnat ... -> ($ext_if) port 500 | static-port # fixed / keep source portrdr on $ext_if proto tcp to port 80 -> 127.0.0.1 port 8080rdr ... port 2000:2999 -> port 4000         # range to one portrdr ... port 2000:2999 -> port 4000:*       # range shiftbinat on $ext_if from 10.1.2.150 -> 203.0.113.150   # 1:1, both directions

111.6 Pool options

OptionWhat it does
bitmaskApply the pool's network part to the address
randomRandom address from the pool
source-hashSame source always gets the same address
round-robinLoop through addresses (required for lists): simple load balancing
sticky-addressKeep a client on the same address
Output
nat on $ext_if from any to any -> 192.0.2.16/28 source-hashrdr on $ext_if proto tcp to port 80 -> { 10.1.2.155, 10.1.2.160 } round-robin

111.7 Filter actions: block drop vs block return

Output
block all                      # default: dropblock drop in all              # silent dropblock return in ...            # TCP RST / ICMP unreachableblock return-rst in proto tcp  # RST only, return-rst (ttl 64)block return-icmp(net-unr) ... # given ICMP code, also return-icmp6pass in proto tcp to port 22   # allow + keep state
ActionWhat the sender seesUse when
block dropNothing, waits until timeoutHide from scanners on the internet side
block return (TCP)RST: Connection refused at onceInside networks, fail fast
block return (UDP)ICMP unreachableInside networks
passPacket allowed, state createdAllowed services

111.8 Rule parameters (50)

  • Basic: in/out, log, quick (stop at this match), on <if>, inet/inet6, proto, from SRC port P to DST port P, all/any.
  • Addresses: ranges (10.1.1.10 - 10.1.1.12), en0:network, en0:broadcast, ppp0:peer, ($ext_if).
  • Ports: = != < <= > >=, ranges 2000:2004, >< (inside), <> (outside).
  • Matching: flags S/SA (default for stateful), icmp-type, os fingerprint, user/group, tos, allow-opts.
  • label names a rule for pfctl -s labels; tag/tagged carry a mark from one rule to another.
Output
pass in log quick on en0 inet proto { tcp, udp } from 10.1.1.10 - 10.1.1.12 to ($ext_if) port 2000:2004pass in proto tcp ... flags S/SA        # default: state only on the first SYNpass in inet proto icmp icmp-type 3 code 4pass ... user { < 1000, dhartmei } group staff os "OpenBSD"pass ... label "web:$dstaddr" tag X     # later: pass ... tagged Xpass ... rtable 1 probability 20%

111.9 State options

  • keep state is the default for pass; no state = stateless; modulate state randomizes the TCP ISN.
  • synproxy state: pf completes the TCP handshake itself, protecting servers from SYN floods.
  • max, max-src-nodes, max-src-states, max-src-conn, max-src-conn-rate limit states per rule/source.
  • overload <table> flush global adds an abusive source to a table and kills all its states.
Output
pass in on $ext_if proto tcp to port 22 keep state \  (max-src-conn 10, max-src-conn-rate 15/5, overload <bad_hosts> flush global)block quick from <bad_hosts>pass ... synproxy state      # pf completes the handshake (SYN flood protection)pass ... modulate state      # random TCP ISNpass ... no state            # stateless

111.10 Routing options, antispoof and anchors

  • route-to sends matching packets through a given interface and gateway; reply-to returns replies the same way.
  • dup-to sends a copy of the packet to another host (monitoring).
  • antispoof for en0 blocks packets claiming en0's network as source but arriving on another interface.
  • anchor calls a sub-ruleset; nat-anchor, rdr-anchor, binat-anchor do the same for translation rules.
Output
pass ... fastroute                    # normal lookuppass in on en0 route-to (en1 192.168.2.1) ...   # use this gatewaypass in on en1 reply-to (en1 192.168.2.1) ...   # replies leave the same waypass ... dup-to (en2 10.0.0.99)       # send a copy (monitoring)
Output
antispoof for lo0antispoof log quick for en0 inetanchor spam                        # evaluate a sub-rulesetanchor "spam/*"                    # all childrenanchor "external" on egress { block }nat-anchor com.example             # also rdr-anchor, binat-anchorload anchor spam from "/etc/pf-spam.conf"

111.11 Linux lab: pf.conf jobs with nft

pf.confLinux equivalent used in the lab
natnft masquerade
rdrnft dnat
scrub max-msstcp option maxseg size set
antispoofip saddr != $lan drop
block return-rst / block dropiptables REJECT tcp-reset / DROP
route-toip rule + table 100
pfctl -ss (states)conntrack -L
ALTQtc qdiscs (htb, hfsc): modules not loaded in the lab
Lab flow: masquerade, dnat and antispoof
  1. 1.pc 10.0.131.10 sends TCP 80 to web 192.168.131.80

  2. 2.fw masquerade: web sees 192.168.131.2

  3. 3.web connects to fw 192.168.131.2:8080

  4. 4.fw dnat forwards to pc 10.0.131.10:80: pc sees 192.168.131.80

  5. 5.pc pings with fake source 172.16.5.5

  6. 6.guard chain (antispoof) drops it at fw

Terminal
which pfctl || echo pfctl: not foundcat /etc/n111/pf.nftnft -c -f /etc/n111/pf.nft && echo syntax OKnft -f /etc/n111/pf.nft
Output
pfctl: not foundtable ip n111 {  chain pre {    type nat hook prerouting priority -100    iifname $ext_if tcp dport 8080 counter dnat to 10.0.131.10:80  }  chain post {    type nat hook postrouting priority 100    oifname $ext_if ip saddr $lan counter masquerade  }  chain guard {    type filter hook forward priority 0    iifname "veth-lan" ip saddr != $lan counter drop    tcp flags syn tcp option maxseg size set 1400  }}syntax OK
Terminal
nc -w 2 192.168.131.80 80      # on pcnc -w 2 192.168.131.2 8080     # on webconntrack -L -p tcp            # on fwnft list chain ip n111 post
Output
pc$ nc -w 2 192.168.131.80 80web sees 192.168.131.2web$ nc -w 2 192.168.131.2 8080pc sees 192.168.131.80$ conntrack -L -p tcptcp 6 118 TIME_WAIT src=192.168.131.80 dst=192.168.131.2 sport=48356 dport=8080 src=10.0.131.10 dst=192.168.131.80 sport=80 dport=48356 [ASSURED] mark=0 use=1tcp 6 116 TIME_WAIT src=10.0.131.10 dst=192.168.131.80 sport=42378 dport=80 src=192.168.131.80 dst=192.168.131.2 sport=80 dport=42378 [ASSURED] mark=0 use=1$ nft list chain ip n111 post    oifname "eth0" ip saddr 10.0.131.0/24 counter packets 3 bytes 204 masquerade
Terminal
tcpdump -lni veth-lan -c 1 "tcp[tcpflags] == tcp-syn and port 80"   # on fw (LAN side)tcpdump -lni eth0 -c 1 "tcp[tcpflags] == tcp-syn and port 80"       # on webping -c 2 -W 1 -I 172.16.5.5 192.168.131.80                          # fake sourceping -c 2 -W 1 192.168.131.80nft list chain ip n111 guard
Output
fw$ tcpdump -lni veth-lan ...01:59:39.395053 IP 10.0.131.10.58610 > 192.168.131.80.80: Flags [S], seq 64851118, win 64240, options [mss 1460,sackOK,TS val 765941874 ecr 0,nop,wscale 10], length 0web$ tcpdump -lni eth0 ...01:59:39.395116 IP 192.168.131.2.58610 > 192.168.131.80.80: Flags [S], seq 64851118, win 64240, options [mss 1400,sackOK,TS val 765941874 ecr 0,nop,wscale 10], length 0pc$ ping -c 2 -W 1 -I 172.16.5.5 192.168.131.802 packets transmitted, 0 received, 100% packet loss, time 1012mspc$ ping -c 2 -W 1 192.168.131.802 packets transmitted, 2 received, 0% packet loss, time 1001ms$ nft list chain ip n111 guard    iifname "veth-lan" ip saddr != 10.0.131.0/24 counter packets 2 bytes 168 drop

Same SYN, same sequence number: mss 1460 on the LAN side, mss 1400 at the web server. That is scrub max-mss done by the guard chain.

Terminal
iptables -A INPUT -p tcp --dport 23 -j REJECT --reject-with tcp-reset   # like block return-rstiptables -A INPUT -p tcp --dport 24 -j DROP                             # like block dropnc -zv -w 2 192.168.131.2 23   # on webnc -zv -w 2 192.168.131.2 24
Output
nc: connect to 192.168.131.2 port 23 (tcp) failed: Connection refusednc: connect to 192.168.131.2 port 24 (tcp) timed out: Operation in progress
Terminal
ip rule add from 10.0.131.10 lookup 100ip route add default via 192.168.131.80 dev eth0 table 100ip route get 1.1.1.1 from 10.0.131.10 iif veth-lanip route get 1.1.1.1 from 10.0.131.20 iif veth-lantc qdisc show dev eth0
Output
1.1.1.1 from 10.0.131.10 via 192.168.131.80 dev eth0 table 100    cache iif veth-lanRTNETLINK answers: Network unreachable$ tc qdisc show dev eth0qdisc noqueue 0: root refcnt 2

111.12 Common mistakes

  • Thinking nat is a firewall: one rdr or binat rule lets outside traffic in; always write block/pass rules.
  • Using rdr pass carelessly: it skips the filter rules completely.
  • Writing statements out of order (filter before nat) in old pf.conf syntax.
  • Forgetting quick: without it, the last matching rule wins in pf.

111.13 Interview tips

  • pf.conf order: options -> scrub -> queue -> nat/rdr -> filter.
  • block drop = silent (timeout), block return = RST for TCP / ICMP for UDP (Connection refused).
  • SSH brute force: keep state (max-src-conn-rate 15/5, overload <bad_hosts> flush global) + block quick from <bad_hosts>.
  • synproxy state protects against SYN floods; max-mss fixes MTU problems on VPN links.
  • binat = 1:1 both directions; nat = many-to-one outbound; rdr = port forward inbound.