Skip to content

Instantly share code, notes, and snippets.

@arter97
Last active September 7, 2024 07:01
Show Gist options
  • Save arter97/2b71e193700ab002c75d1e5a0e7da6dc to your computer and use it in GitHub Desktop.
Save arter97/2b71e193700ab002c75d1e5a0e7da6dc to your computer and use it in GitHub Desktop.
ipset firewall for crontab
#!/bin/bash
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
exec > /dev/kmsg 2>&1
TMP=/tmp/ipsum.txt
until wget --spider https://raw.githubusercontent.com/stamparm/ipsum/master/ipsum.txt > /dev/null 2>&1; do
echo "Waiting for GitHub to be accessible"
sleep 1
done
while true; do
until curl --compressed https://raw.githubusercontent.com/stamparm/ipsum/master/ipsum.txt > $TMP 2>/dev/null; do
echo "Retrying ipsum download"
done
if [ $(stat -c%s $TMP) -le 65536 ]; then
echo "WARNING: Downloaded ipsum firewall database looks wrong, retrying"
else
break
fi
sleep 1
done
echo "Updating firewall data"
LINES=$(cat $TMP | grep -v '#' | wc -l)
echo "Creating ipset set with $LINES matches"
if ipset list | grep -q "Name: ipsum"; then
iptables -D INPUT -m set --match-set ipsum src -j DROP
ipset flush ipsum
ipset destroy ipsum
fi
ipset create ipsum hash:ip maxelem $(cat $TMP | grep -v '#' | grep -vE $(cat /etc/resolv.conf | grep '^nameserver' | awk '{print $2}' | sed -z '$ s/\n$//' | tr '\n' '|') | wc -l)
cat $TMP | grep -v '#' | grep -vE $(cat /etc/resolv.conf | grep '^nameserver' | awk '{print $2}' | sed -z '$ s/\n$//' | tr '\n' '|') | cut -f 1 | sed -e 's/^/add ipsum /g' | ipset restore -!
rm $TMP
iptables -I INPUT -m set --match-set ipsum src -j DROP
ipset list | grep -A6 "Name: ipsum"
echo "Updated firewall data"
ipsum firewall for crontab based on https://github.com/stamparm/ipsum
1. Install required packages
`apt install iptables ipset curl wget`
2. Download the firewall.sh below to /root (so that it won't be accessible to regular users)
3. Don't forget to make it executable
`sudo chmod 755 /root/firewall`
4. Add it to crontab
`sudo crontab -e`
```
@reboot /root/firewall
0 5 * * * /root/firewall
```
This will run the script on each reboot and 05:00 AM everyday.
5. Execute `sudo /root/firewall` manually, no reboots necessary
6. All logs will be available at `dmesg`
```
[ 7167.250087] Updating firewall data
[ 7172.506405] Updated firewall data
[ 7172.506418] Added firewall rules for 11852 IPs
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment