scripts/bin/blockinst.sh

94 lines
2.6 KiB
Bash
Executable file

#!/usr/bin/env bash
###
### Takes a list of instances (one per line), resolves their IPs,
### and creates a blocklist your server understands. Caddy does
### per-server blocks while nginx does server-wide blocks.
###
### Caddy example:
### ipfilter / {
### rule block
### prefix_dir blocks # folder relative to working dir
### blockpage www/blocked.html # optional block page
### }
###
### Nginx example: (not necessary if running debian or a debian derivative)
### http {
### ...
### include blockips.conf;
### ...
### }
###
### todo:
### ignore cloudflare IPs
### add apache
### add license text
###
# blocklist location
filename="$HOME/.config/blocked.txt"
# Which web server are you using? [nginx|caddy]
srv="caddy"
# Config locations. Ignore any you don't need
confCaddy="$HOME/.config/caddy/blocks"
confNginx="/etc/nginx/conf.d/blocks.conf"
# The DNS server to use for the domain lookups
# A local dnsmasq server is fine
dnsServer="192.168.2.2"
### ----------------------------------------------------
### Don't edit anything below unless you know what you're doing
### -----------------------------------------------------
# Cloudflare ip matches
cfThree="173.245.48|103.21.244|103.22.200|103.31.4|141.101.64|108.162.192|190.93.240|188.114.96|197.234.240|198.41.128"
cfTwo="162.158|104.16|172.64"
# clear blocks if using nginx
if [ "$srv" == "nginx" ]; then
sudo rm $confNginx
sudo touch $confNginx
elif [ "$srv" == "caddy" ]; then
rm $confCaddy/*
fi
# read blocklist
while read domain; do
# dns lookup
rawip=$(dig +short $domain @$dnsServer | grep '^[.0-9]*$')
# skip if the ip resolves to a cloudflare node
if [[ "$(echo $ip | cut -d'.' -f1-3)" == "^($cfThree)$" ]] || [[ "$(echo $ip | cut -d'.' -f1-2)" == "^($cfTwo)$" ]] || [[ "$(echo $ip | cut -d'.' -f1).0.$(echo $ip | cut -d'.' -f3)" == "131.0.72" ]]; then
echo "$domain: not willing to block a cloudflare node"
else
# just say the domain isn't found if lookup fails
if [ -z "$rawip" ]; then
echo "$domain: not found"
else
# read each ip in dig's output
for ip in $rawip; do
echo "$domain: $ip"
# create block files for caddy
if [ "$srv" == "caddy" ]; then
echo "$domain" > $confCaddy/$ip
# create block file for nginx
elif [ "$srv" == "nginx" ]; then
echo "deny $ip;" | sudo tee -a $confNginx > /dev/null
# configured web server not supported
else
echo "Server unsupported or mis-spelt! Check the config and try again."
echo "[ caddy | nginx ]"
fi
done
fi
fi
done < $filename