Skip to content

Instantly share code, notes, and snippets.

@stefanpejcic
Created March 6, 2024 23:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanpejcic/8c839c6704052ea6fbc0ff1c6aca72b9 to your computer and use it in GitHub Desktop.
Save stefanpejcic/8c839c6704052ea6fbc0ff1c6aca72b9 to your computer and use it in GitHub Desktop.
#!/bin/bash
# adds a custom blacklist to ufw
# Check if ipset is installed
if ! command -v ipset &> /dev/null
then
echo "ipset could not be found, installing..."
sudo apt-get update && sudo apt-get install -y ipset
else
echo "ipset is already installed."
fi
# Check if ipset named op_blacklist exists, if not create it
if ! sudo ipset list op_blacklist &> /dev/null
then
echo "Creating ipset list named op_blacklist..."
sudo ipset create op_blacklist hash:ip
else
echo "ipset list named op_blacklist already exists."
fi
# Check if UFW has a rule to use op_blacklist, if not add it
UFW_RULE="deny from any to any set op_blacklist"
if ! sudo ufw status verbose | grep -F -- "$UFW_RULE" &> /dev/null
then
echo "Adding UFW rule to use op_blacklist..."
sudo ufw insert 1 deny from any to any set op_blacklist
else
echo "UFW rule to use op_blacklist already exists."
fi
# Empty the ipset list
echo "Emptying the op_blacklist set..."
sudo ipset flush op_blacklist
# Prepare a temporary file for ipset restore
TMP_IPSET_FILE=$(mktemp)
# Get list of IP addresses from blacklist.pejcic.rs and save it to a temporary file
echo "Downloading list of IP addresses and preparing ipset restore file..."
echo "create op_blacklist hash:ip" > "$TMP_IPSET_FILE"
curl -s http://blacklist.pejcic.rs | while read -r line
do
echo "add op_blacklist $line" >> "$TMP_IPSET_FILE"
done
# Load ipset list from the temporary file
echo "Loading ipset list from file..."
sudo ipset restore < "$TMP_IPSET_FILE"
# Save ipset list to ensure persistence
echo "Saving ipset list for persistence..."
sudo ipset save op_blacklist > /etc/ipset_op_blacklist.conf
# Clean up temporary file
rm -f "$TMP_IPSET_FILE"
# Restart UFW to apply changes
echo "Restarting UFW..."
sudo ufw reload
echo "Setup complete."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment