Debian common way to block IP

Here I will list out common way that I use IPtables and IPset to block IP

Updated June 22, 2019

Use Iptables

Block traffic by port

iptables -A INPUT -j DROP -p tcp --destination-port 110 -i eth0

Drop all traffic

iptables -I INPUT -s -j DROP

Block or Allow some traffic or port range

## IPv4

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -i lo -m comment --comment "Allow loopback connections" -j ACCEPT
iptables -A INPUT -p icmp -m comment --comment "Allow Ping to work as expected" -j ACCEPT
iptables -A INPUT -p tcp -m multiport --destination-ports 22,25,53,80,443,465,3389,1701:1703 -j ACCEPT
iptables -A INPUT -p udp -m multiport --destination-ports 53 -j ACCEPT
iptables -P INPUT DROP
iptables -P FORWARD DROP

## IPv6
ip6tables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
ip6tables -A INPUT -p tcp --syn --dport 80 -s fe80::/64 -m connlimit --connlimit-above 16 --connlimit-mask 64 -j REJECT
ip6tables -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
ip6tables -P INPUT DROP
ip6tables -P FORWARD DROP

Use ipset


apt install ipset

Setup Ipv4, IPv6

ipset create blacklist hash:ip hashsize 4096
ipset create blacklist6 hash:net hashsize 4096 family inet6
## Add some ip
ipset add blacklist

// To add an IP address, simply do:
sudo ipset add blacklist <IP-ADDRESS_OR_CIDR-IF-NETHASH>

//To remove an IP address, do:
sudo ipset del blacklist <IP-ADDRESS_OR_CIDR-IF-NETHASH>

//To remove ALL IP addresses in a list, use the flush command
sudo ipset flush blacklist

// To save the current list to a file:
sudo ipset save blacklist -f ipset-blacklist.backup

//To restore said file:
sudo ipset restore -! < ipset-blacklist.backup

// Delete a list
ipset destroy blacklist

// List current blacklist
ipset list

Iptables insert match-set blacklist and drop

iptables -I INPUT -m set --match-set blacklist src -j DROP
iptables -I FORWARD -m set --match-set blacklist src -j DROP

ip6tables -I INPUT -m set --match-set blacklist6 src -j DROP
ip6tables -I FORWARD -m set --match-set blacklist6 src -j DROP

Make ipset persistent

nano /etc/systemd/system/ipset-persistent.service

Description=ipset persistancy service

ExecStart=/sbin/ipset restore -f -! /etc/ipsets.conf

# save on service stop, system shutdown etc.
ExecStop=/sbin/ipset save blacklist -f /etc/ipsets.conf


// Save and enable this service

sudo systemctl daemon-reload
sudo systemctl start ipset-persistent
sudo systemctl enable ipset-persistent

Save your iptables rules and view

sudo iptables-restore < /tmp/v4
sudo ip6tables-restore < /tmp/v6

View current Iptables Rules

iptables -L -nv

Make your iptables rules always apply after reboot

# Add file
nano /etc/network/if-pre-up.d/
# cmd inside
iptables-restore < /etc/iptables/rules.v4
ip6tables-restore < /etc/iptables/rules.v6
exit 0

# make it excutable
chmod +x

Credit: Photo by Escape Artiste on Unsplash