Convalesco

Current revision: 0.8

Last update: 2024-01-12 12:51:21 +0000 UTC

If a man will begin with certainties, he shall end in doubts; but if he will be content to begin with doubts, he shall end in certainties.

F. Bacon , The Advancement Of Learning - 1605 A.D.


Debian: allow access from specific countries

Date: 11/01/2015, 02:26

Category: technology

Revision: 1



This simple firewall configuration is specific to the Debian GNU/Linux distribution which is my default choice for Linux server deployments.

First install the ipset tool using apt-get:


$ sudo apt-get install ipset

Then create the file /etc/iptables.rules using your favorite editor. Here is the most simple ruleset:


*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -i lo -j ACCEPT
-A INPUT -d 127.0.0.0/8 ! -i lo -j REJECT --reject-with icmp-port-unreachable
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -m set --match-set gr.zone src -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -m set --match-set gr.zone src -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7
-A INPUT -j REJECT --reject-with icmp-port-unreachable
-A FORWARD -j REJECT --reject-with icmp-port-unreachable
-A OUTPUT -j ACCEPT
COMMIT

This ruleset allows connections from gr.zone to ports 80 and 443 (HTTP and HTTPS). The gr.zone is a collection of IP addresses originating from Greece but allows connections to port 22 from anywhere.

NOTE: That’s not my exact setup. I never run secure shell servers on default ports and I never use password authentication. The era of password-based SSH authentication has long gone!

Finally create the following file, /etc/network/if-pre-up.d/iptables and copy paste the following:


#!/bin/sh

# Greek IP Zone
ipset -F gr.zone
ipset -N gr.zone nethash
for IP in $(wget -O - http://www.ipdeny.com/ipblocks/data/countries/gr.zone)
do ipset -A gr.zone $IP
  echo $IP
done

# Load firewall rules
/sbin/iptables-restore < /etc/iptables.rules

Now turn this file into an executable:

$ sudo chmod +x /etc/network/if-pre-up.d/iptables

Now just restart the server. Debian will execute this file on every server restart, so you won’t have to worry about manually loading the firewall every time.

That’s it! You can substitude Greece (gr) with any other country zone code (e.g. de, uk, us, jp, cn, ca, etc)

Further reading:

ps. OpenBSD’s firewall, pf, can achieve the same result reading the list of IP addresses from a file. I found pf’s approach in the past a lot easier and way more readable that this.