summaryrefslogtreecommitdiff
path: root/nft/asn-filter.sh
blob: 2880d309e1595d1f74c35cebc85c18fe58f1339a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/bin/sh
#
# Copyright (C) 2025-2026 Maria Lisina
# SPDX-License-Identifier: Apache-2.0
#
# nftables ASN filter

set -e

if [ ${#} -eq 0 ]
then
    echo "No ASNs specified!"
    exit 1
fi

__blocked_asns="${@}"
shift ${#}

for __asn in ${__blocked_asns}
do
    __asn_ips="$(curl --get --silent "https://2ip.io/as/${__asn}.json" | jq -r '.prefixes[].ipv4Prefix')"
    set -- ${@} ${__asn_ips}
done

while [ ${#} -gt 0 ]
do
    _asn_ips="$(printf "%s%s" "${_asn_ips}" "${1}")"

    if [ ${#} -gt 1 ]
    then
        _asn_ips="$(printf "%s%c" "${_asn_ips}" ",")"
    fi

    shift
done

cat << EOF > /etc/nftables.d/asn_filter.nft
#!/usr/sbin/nft -f

table inet asn_filter {
    set blocked_addresses {
        typeof ip saddr
        flags interval
        auto-merge
        elements = { ${_asn_ips} }
    }

    chain input {
        type filter hook input priority 0;
        ip saddr @blocked_addresses drop
    }
}
EOF