Using ASNs and nftables to block connections

January 01, 2022 #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

#!/bin/sh

set -euf

# facebook ASNs
ASNs="AS32934 AS11917"

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

asn_ips=

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

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 = {
            $asn_ips
        }
        auto-merge
    }
    chain output {
        meta nfproto ipv4 ip daddr @asn_blocked_addresses log prefix "BLOCKED BY NFT_ASN_BLOCK: " drop;
    }
}
EOF

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.