|
| 1 | +import sys |
| 2 | +import time |
| 3 | +from ipaddress import ip_network |
| 4 | +from pathlib import Path |
| 5 | +from subprocess import CalledProcessError, run |
| 6 | +from typing import Final |
| 7 | + |
| 8 | +import httpx |
| 9 | +import typer |
| 10 | + |
| 11 | +RTTABLE_CACHE: Final = Path("/var/lib/nft-asblock/table.txt") |
| 12 | +NFT_TABLE: Final = "abuse" |
| 13 | +NFT_IPV4_SET: Final = "blocked4" |
| 14 | +NFT_IPV6_SET: Final = "blocked6" |
| 15 | + |
| 16 | + |
| 17 | +def get_rttable() -> str: |
| 18 | + def fetch() -> str: |
| 19 | + url = "https://bgp.tools/table.txt" |
| 20 | + headers = { "User-Agent": "nixos.org infra - [email protected]"} |
| 21 | + response = httpx.get(url, headers=headers) |
| 22 | + assert response.status_code == 200 |
| 23 | + return response.text |
| 24 | + |
| 25 | + try: |
| 26 | + mtime = RTTABLE_CACHE.stat().st_mtime |
| 27 | + except FileNotFoundError: |
| 28 | + mtime = None |
| 29 | + |
| 30 | + # don't pull more often than every two hours |
| 31 | + if not mtime or time.time() - mtime > 2 * 3600: |
| 32 | + print("Pulling routing table from bgp.tools", file=sys.stderr) |
| 33 | + data = fetch() |
| 34 | + with RTTABLE_CACHE.open("w") as fd: |
| 35 | + fd.write(data) |
| 36 | + else: |
| 37 | + print("Loading routing table from cache", file=sys.stderr) |
| 38 | + with RTTABLE_CACHE.open() as fd: |
| 39 | + data = fd.read() |
| 40 | + |
| 41 | + return data |
| 42 | + |
| 43 | + |
| 44 | +def nft_block(prefixes: set[str]) -> None: |
| 45 | + networks = map(ip_network, prefixes) |
| 46 | + |
| 47 | + for network in networks: |
| 48 | + print(f"\nBlocking {network}...", file=sys.stderr, end="") |
| 49 | + try: |
| 50 | + run( |
| 51 | + [ |
| 52 | + "nft", |
| 53 | + "add", |
| 54 | + "element", |
| 55 | + "inet", |
| 56 | + NFT_TABLE, |
| 57 | + NFT_IPV4_SET if network.version == 4 else NFT_IPV6_SET, |
| 58 | + "{", |
| 59 | + str(network), |
| 60 | + "}", |
| 61 | + ], |
| 62 | + check=True, |
| 63 | + ) |
| 64 | + except CalledProcessError: |
| 65 | + continue |
| 66 | + |
| 67 | + |
| 68 | +def main(autnums: list[str]) -> None: |
| 69 | + rttable = get_rttable() |
| 70 | + |
| 71 | + prefixes = set() |
| 72 | + for line in rttable.splitlines(): |
| 73 | + try: |
| 74 | + prefix, autnum = line.split() |
| 75 | + except ValueError: |
| 76 | + continue |
| 77 | + if autnum in autnums: |
| 78 | + prefixes.add(prefix) |
| 79 | + nft_block(prefixes) |
0 commit comments