Linux Debian common way to block IP

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

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

Iptables insert match-set blacklist and drop

iptables -I INPUT -m set --match-set blacklist src -j DROP
ip6tables -I INPUT -m set --match-set blacklist6 src -j DROP

List current blacklist

ipset list

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