How do I allow only certain IPs with iptables?

Linode Staff

Dear team,

I need your help in restricting access to the server from the external world apart from a certain IP range. I was asked to use iptables to restrict access but what if something goes wrong while doing the same, what can i do and fix it?

1 Reply

Hi there if your would like to block all traffic except for a certain range of IPs using iptables you can run the following commands.

 # 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 -s 192.168.1.0/24 -j ACCEPT
 # iptables -A INPUT -s 198.51.100.0 -j ACCEPT
 # iptables -P INPUT DROP
 # iptables -P FORWARD DROP

When running the commands above do not do this using SSH you will be locked out! You want to use Lish.

The follwoing lines in the commands specify what IPs will be allowed to connect. You will want to edit these based on the IPs you want to allow. Dont forget about internal and extrenal IPs. You can use CIDR ranges with your iptables. Just as shown below for the local IPs.

 # iptables -A INPUT -s 192.168.1.0/24 -j ACCEPT
 # iptables -A INPUT -s 198.51.100.0 -j ACCEPT

After you have setup your firewall rules you want to make sure you set them to persistent. If you don't they will not survive a reboot. You would have to do this again.

There's also a great guide from Nix Craft explaining all the options for iptables.

We also have a great guide for Unclomplicated Firewall (UFW) which is much easier to use than iptables. But not as robust.

Reply

Please enter an answer
Tips:

You can mention users to notify them: @username

You can use Markdown to format your question. For more examples see the Markdown Cheatsheet.

> I’m a blockquote.

I’m a blockquote.

[I'm a link] (https://www.google.com)

I'm a link

**I am bold** I am bold

*I am italicized* I am italicized

Community Code of Conduct