Blog | G5 Cyber Security

Firewall: Block Countries

TL;DR

This guide shows you how to block outbound connections from your server or network to specific countries using a firewall (specifically, iptables on Linux). This is useful for preventing unwanted access or limiting data transfer.

Prerequisites

Step 1: Get a Country IP Address List

You’ll need a list of IP address ranges for the countries you want to block. Several sources provide these lists, often in text format.

Download the list relevant to your needs.

Step 2: Create an IP Address List File

Once you have downloaded the list, you may need to format it into a simple text file with one IP address (or CIDR block) per line. For example:

192.0.2.0/24
198.51.100.0/24
...

Save this file, for instance, as blocked_countries.txt.

Step 3: Block the Countries using iptables

Use iptables to block outbound traffic to the IP addresses in your list. The following commands assume you want to block all TCP and UDP traffic on the outgoing interface (e.g., eth0).

  1. Create a new chain: This keeps your rules organised.
  2. iptables -N BLOCK_COUNTRIES
  3. Add a rule to jump to the new chain for outbound traffic: Replace eth0 with your actual outgoing interface.
  4. iptables -A OUTPUT -o eth0 -j BLOCK_COUNTRIES
  5. Read the IP address list and add rules: This loops through each entry in the file and adds a block rule. Replace blocked_countries.txt with your filename.
  6. while read ip; do iptables -A BLOCK_COUNTRIES -d $ip -j DROP; done < blocked_countries.txt
  7. Add a default policy to accept other traffic: This ensures that anything not explicitly blocked is allowed.
  8. iptables -A BLOCK_COUNTRIES -j ACCEPT

Step 4: Save the iptables Rules

The rules you’ve added are currently in memory and will be lost on reboot. You need to save them.

sudo apt-get install iptables-persistent
sudo netfilter-persistent save
  • CentOS/RHEL/Fedora:
  • sudo yum install iptables-services
    sudo service iptables save

    Step 5: Verify the Rules

    Check that your rules have been added correctly.

    iptables -L BLOCK_COUNTRIES -v -n

    This will list all the rules in the BLOCK_COUNTRIES chain. You should see entries corresponding to the IP addresses you loaded from the file.

    Step 6: Testing

    Test your blocking by attempting to connect to a service within one of the blocked countries (e.g., using ping or traceroute). The connection should fail.

    Important Considerations

    Exit mobile version