Linux – allow only single IP and block all IP IPTABLES

iptableslinux

How do I allow only certain ip addresses and block all other ip address connection in iptables?

For allowing I entered the following command

iptables -A INPUT -s 192.168.1.1 -j ACCEPT

What should I do for Blocking?

Best Answer

The thing to remember is that firewall rules are checked in the order they are listed. The kernel will stop processing the chain when a rule is triggered that will either allow or dis-allow a packet or connection.

Assuming that your current firewall only has that single rule (check for instance with iptables-save or iptables -L -v -n --line-numbers):

You need append a second rule that instructs your firewall what to do with traffic that isn't matched by the first rule.

Rules without a more specific matching rule will match anything and the very short:

iptables -A -j REJECT 

should suffice.

Check with iptables-save and you should see a minimal firewall similar to this:

[root@host ~]# iptables-save
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -i lo -j ACCEPT
-A INPUT -s 192.168.1.1 -j ACCEPT
-A INPUT -j REJECT 
COMMIT

The kernel will stop processing the chain when a rule is triggered that will either allow or dis-allow a packet or connection.

Addendum: when no rules are triggered the policy that is set on a chain gets applied. So rather than adding a rule that blocks everything at the end of your current config you can also set/change the policy on the input chain to achieve the same:

iptables -P INPUT DROP

and

[root@host ~]# iptables-save
*filter
:INPUT DROP[0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -i lo -j ACCEPT
-A INPUT -s 192.168.1.1 -j ACCEPT
COMMIT