IP sets in OpenWrt 22.03


OpenWrt has recently released version 22.03, and one of the biggest changes is the switch to nftables.

I’ve noticed though that nftables doesn’t use ipsets as I was used to, but it has a new concept of sets inside the nftables ruleset.

I wanted to create a firewall rule to filter a list of IPs from an URL, however the integration was not as straightforward as with iptables, so I’ve ended creating this solution.

The rules that I want to create is to block the list of DNS servers from this list to avoid the clients from my IoT network to use them as DoH resolvers.

So first, I create my custom rules in nftables where I define some empty nftables sets and the filter rules that use them:

/etc/nftables.d/01-dns-resolvers.nft

set resolvers4 {
    type ipv4_addr
    comment "Set resolvers - IPv4"
}

set resolvers6 {
    type ipv6_addr
    comment "Set resolvers - IPv6"
}

chain user_pre_forward {
    type filter hook forward priority -1; policy accept;
    iifname $iot_devices jump user_pre_forward_iot comment "User-defined rules for pre-forward IoT"
}

chain user_pre_forward_iot {
    ip daddr @resolvers4 tcp dport 443 log prefix "reject DoH: " jump handle_reject
    ip daddr @resolvers4 udp dport 443 log prefix "reject DoH: " jump handle_reject
    ip6 daddr @resolvers6 tcp dport 443 log prefix "reject DoH: " jump handle_reject
    ip6 daddr @resolvers6 udp dport 443 log prefix "reject DoH: " jump handle_reject
}

This is enough for the rules to be loaded at boot time and with each firewall reload. Now we need to populate the sets from an external URL. For that, I’ve created a cron job that runs this script periodically:

# crontab -e
*/10 * * * * /bin/nice -n 19 /usr/bin/nftables-set-fetch.sh resolvers https://public-dns.info/nameservers-all.txt

And you can get the script from the following repository:

https://codeberg.org/jorti/nftables-set-fetch

The script only fetches the URL or update the sets after the data is considered stale (3 days by default), so it can be run in cron with high frequency.

See also