#!/bin/bash PROGNAME=${0##*/} main() { { info "generating prologue ..." # Start from nothing echo "flush ruleset" # Create prerequisite containers echo "table ip filter {" echo " chain INPUT {" echo " type filter hook input priority 0; policy accept;" # block China & Russia info "generating rules to block China and Russia ..." I=0 for COUNTRY in cn ru; do wget -qO - http://www.ipdeny.com/ipblocks/data/countries/$COUNTRY.zone | while read CIDR; do ((I++)) # On the command line the spaces and other characters need to be removed (even backslash-escaping, # as suggested somewhere on the web, didn't work). However, if I put spaces in /etc/nftables.conf # and run 'systemctl restart nftables' then the spaces are present in the output of 'nft list ruleset'. gen_block $CIDR "block $COUNTRY CIDR#$I" done done # Block other stuff info "generating rules to block other stuff ..." CIDR_COMMENT_TUPLES=( 168.119.0.0/16 "Hetzner Online GmbH (hack requestor on judithhabgood.freemyip.com)" 178.63.0.0/16 "Hetzner Online GmbH (hack requestor on judithhabgood.freemyip.com)" 46.4.0.0/16 "Hetzner Online GmbH (hack requestor on judithhabgood.freemyip.com)" 88.198.0.0/16 "Hetzner Online GmbH (hack requestor on judithhabgood.freemyip.com)" 148.251.0.0/16 "Hetzner Online GmbH (hack requestor on judithhabgood.freemyip.com)" 78.46.0.0/15 "Hetzner Online GmbH (hack requestor on judithhabgood.freemyip.com)" 144.76.0.0/16 "Hetzner Online GmbH (hack requestor on judithhabgood.freemyip.com)" ) for ((I=0; I<${#CIDR_COMMENT_TUPLES[*]}; I+=2)); do CIDR=${CIDR_COMMENT_TUPLES[$I]} COMMENT=${CIDR_COMMENT_TUPLES[$((I+1))]} gen_block $CIDR "$COMMENT" done info "generating epilogue ..." echo " }" echo "}" } > /tmp/$PROGNAME.$$.nft info "loading generated output ..." nft -f /tmp/$PROGNAME.$$.nft rm -f /tmp/$PROGNAME.$$.nft info "saving current config ..." { echo "#!/usr/sbin/nft -f" echo "# This file was generated by $PROGNAME on $(date)." echo echo "flush ruleset" echo nft list ruleset } > /etc/nftables.conf chmod 755 /etc/nftables.conf info "reloading that to make sure it works ..." /etc/nftables.conf } gen_block() { local CIDR COMMENT CIDR=$1 COMMENT=$2 echo " meta iifname br0 ip saddr $CIDR tcp dport { http, https } counter log prefix \"DROPPED: \" drop comment \"$COMMENT\"" } info() { echo "$PROGNAME: INFO: $1" >&2 } main "$@"