Skip to content

Instantly share code, notes, and snippets.

@ibqn
Created July 14, 2019 19:33
Show Gist options
  • Save ibqn/a4a1894afbe6332aa1ab3e17d77d771c to your computer and use it in GitHub Desktop.
Save ibqn/a4a1894afbe6332aa1ab3e17d77d771c to your computer and use it in GitHub Desktop.
Fear China. Unexpected ddos on your sshd deamon blocking china with ipset and iptables

Install ipset

sudo apt install ipset

Create folder

sudo mkdir -p /etc/block-china/

Create a bash script

sudoedit /etc/block-china/populate.bash

with the following content

# Create the ipset list
ipset -N china hash:net

# remove any old list that might exist from previous runs of this script
rm cn.zone

# Pull the latest IP set for China
wget -P . http://www.ipdeny.com/ipblocks/data/countries/cn.zone

# Add each IP address from the downloaded list into the ipset 'china'
for i in $(cat /etc/cn.zone ); do ipset -A china $i; done

# Restore iptables
/sbin/iptables-restore < /etc/block-china/iptables-firewall.rules

Save the file. To be clear, the full iptables-firewall.rules looks like this:

*filter

#  Allow all loopback (lo0) traffic and drop all traffic to 127/8 that doesn't use lo0
-A INPUT -i lo -j ACCEPT
-A INPUT -d 127.0.0.0/8 -j REJECT

#  Accept all established inbound connections
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Block anything from China
# These rules are pulled from ipset's china list
# The source file is at /etc/cn.zone (which in turn is generated by a shell script at /etc/block-china.sh )
-A INPUT -p tcp -m set --match-set china src -j DROP

#  Allow all outbound traffic - you can modify this to only allow certain traffic
-A OUTPUT -j ACCEPT

#  Allow HTTP and HTTPS connections from anywhere (the normal ports for websites and SSL).
-A INPUT -p tcp --dport 80 -j ACCEPT
-A INPUT -p tcp --dport 443 -j ACCEPT

#  Allow SSH connections
#
#  The -dport number should be the same port number you set in sshd_config
#
-A INPUT -p tcp -m state --state NEW --dport 22 -j ACCEPT

#  Allow ping
-A INPUT -p icmp -j ACCEPT

#  Log iptables denied calls
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7

#  Drop all other inbound - default deny unless explicitly allowed policy
-A INPUT -j DROP
-A FORWARD -j DROP

COMMIT

Right now, nothing has changed with the server because no new rules have been applied; to do so, run the block-china.sh script:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment