Skip to main content

whitelist IP Addresses centos 6.10 [Resolved]

How to allow specific IP Addresses to a dport in iptables ? for example : i have 2 clients, first client's IP Address is 182.3.3.1 and the second ones is 202.4.5.6, and i have a port let's say 2222. what i want is, only these IP addresses can access to port 2222.

i wrote this rules :

iptables -A INPUT -p tcp ! -s 182.3.3.1  --dport 2222 -j REJECT
iptables -A INPUT -p tcp ! -s 202.4.5.6  --dport 2222 -j REJECT

What happens is only 1 address can access, and the other one is blocked. Whats wrong ?


Question Credit: pakar-indo
Question Reference
Asked April 14, 2019
Posted Under: Unix Linux
8 views
1 Answers

The way iptables process rules is: grab a packet and try to match it against the ruleset, from top do bottom. If a rule match, execute it and stop further processing (except for specific cases like when the target is another chain, LOG, RETURN, etc).

Every chain also have a DEFAULT Policy (its ACCEPT by default), that is what happens with a packet that does not match any rule.

Now, if you have two rules like this:

iptables -A INPUT -p tcp ! -s 182.3.3.1 --dport 2222 -j REJECT
iptables -A INPUT -p tcp ! -s 202.4.5.6 --dport 2222 -j REJECT  

If you access from the IP 182.3.3.1, the first rule matches and is applied (by doing nothing, and the rule is treated by the chain DEFAULT Policy, that I believe is ACCEPT). In the second case, If the IP is 202.4.5.6, the first rule matches also and is applied (by REJECTing the access).

What you problably want is something like this (don't just type these rules on your system or you will lock yourself out!):

iptables -P DROP INPUT # Changes the INPUT Chain default policy to DROP
iptables -A INPUT -p tcp -s 182.3.3.1 --dport 2222 -j ACCEPT # Allows the access of IP 182.3.3.1  
iptables -A INPUT -p tcp -s 202.4.5.6 --dport 2222 -j ACCEPT # Allows the access of IP 202.4.5.6 

Understand that, by using these rules, you'll need to update your ruleset to allow access for other services (like allowing yourself accessing SSH and other services on the server, thus the advice against locking yourself out of the server).


credit: JucaPirama
Answered April 14, 2019
Your Answer