ref: 5e945955e2c3c1c0843786a31e890f5bfbe82ffb blog.craftyguy.net/content/2022-01-01-nft-asn-block.md -rw-r--r-- 2.3 KiB
5e945955Clayton Craft content/2022-01-07-ipxe-aarch64: new post 6 months ago

+++ title = "Using ASNs and nftables to block connections" date = 2022-01-01 [taxonomies] tags = ["linux", "privacy"] +++

Blocking Facebook, and similarly-toxic sites/services, is a common theme amongst those who value privacy. Facebook goes to great lengths to track everyone, regardless of whether or not they have an account or use anything they "generously" offer to the public. Previously I had a long, long list of domains that Facebook owned, and set up unbound (the DNS resolver I run) to deny lookups to those domains. This was a classic game of cat & mouse, as Facebook would frequently acquire new domains and it was basically impossible to keep up.

Enter autonomous system numbers (ASN), which are unique identifiers that the IANA assigns to owners of public IP blocks. Using as ASN, it's possible to look up every IP "owned" by the thing the ASN was given to. Once you have every IP, it's trivial to generate a firewall rule (using nftables, at least) to block connections to them. You can evidently even get ASNs for entire ISPs (and therefore, effectively, [some] entire countries!)

I have done this in the script below, ASNs can be set to include others as well, but I have left the two ASNs for Facebook as a convenience to the reader :D


set -euf

# facebook ASNs
ASNs="AS32934 AS11917"

get_asn_ips() {
        whois -h whois.radb.net -- -i origin "$asn" |  awk '/route:/ {printf("\t\t%s,", $2)}'


for a in $ASNs; do
        asn_ips=$(printf "%s%s" $asn_ips $(get_asn_ips $a))

cat  <<EOF > /etc/nftables.d/50-nft_asn_block.nft
#!/usr/sbin/nft -f
table inet filter {
    set asn_blocked_addresses {
        type ipv4_addr
        flags interval
        elements = {
    chain output {
        meta nfproto ipv4 ip daddr @asn_blocked_addresses log prefix "BLOCKED BY NFT_ASN_BLOCK: " drop;

I have this set to run as a cron job every week, which might be too often (don't forget to reload nftables), but it works fine ¯\_ (ツ)_/¯

There are various ways to find an ASN, some searches allow you to specify the company/organization name, but the most common seem to do lookups based on a given IP address. I won't link to any here, because it's easy to find them using your favorite search engine.