Implementing IP Sets for Dynamic Blacklisting

Implementing IP Sets for Dynamic Blacklisting

IP sets provide a powerful way to manage large lists of IP addresses efficiently. Instead of creating individual rules for each blocked IP, you can reference an IP set that can be updated dynamically without modifying firewall rules.

Create and populate IP sets:

# Install ipset if not already available
sudo apt-get install ipset

# Create an IP set for blacklisted addresses
sudo ipset create blacklist hash:ip timeout 3600

# Create an IP set for whitelisted addresses
sudo ipset create whitelist hash:ip

# Add IPs to sets
sudo ipset add blacklist 192.168.1.100
sudo ipset add blacklist 10.0.0.50 timeout 7200
sudo ipset add whitelist 203.0.113.0/24

Reference IP sets in iptables rules:

# Always allow whitelisted IPs
sudo iptables -A INPUT -m set --match-set whitelist src -j ACCEPT

# Block blacklisted IPs early in the chain
sudo iptables -A INPUT -m set --match-set blacklist src -j DROP

# Add failed login attempts to temporary blacklist
sudo iptables -A INPUT -p tcp --dport 22 -m recent --name SSH --update --seconds 300 --hitcount 5 -j SET --add-set blacklist src --exist