31

How can I on my ubuntu server, in Iptables only allow one IP adress on a specific port?

Thanks

Cristian Ciupitu
  • 6,226
  • 2
  • 41
  • 55
Anonymous12345
  • 1,012
  • 1
  • 12
  • 17

3 Answers3

59

One liner:

iptables -I INPUT \! --src 1.2.3.4 -m tcp -p tcp --dport 777 -j DROP  # if it's not 1.2.3.4, drop it

A more elegant solution:

iptables -N xxx # create a new chain
iptables -A xxx --src 1.2.3.4 -j ACCEPT  # allow 1.2.3.4
iptables -A xxx --src 1.2.3.5 -j ACCEPT  # allow 1.2.3.5
iptables -A xxx --src 1.2.3.6 -j ACCEPT  # allow 1.2.3.6
iptables -A xxx -j DROP  # drop everyone else
iptables -I INPUT -m tcp -p tcp --dport 777 -j xxx  # use chain xxx for packets coming to TCP port 777
Cristian Ciupitu
  • 6,226
  • 2
  • 41
  • 55
  • Do you know if I should also add this to the OUTPUT also? – Anonymous12345 May 30 '10 at 12:05
  • @Camran: you need to be more specific. In this particular case, if you replace `INPUT` with `OUTPUT` you would block some packets sent using some addresses of the server itself (and not routed/forwarded). I doubt this makes sense, unless maybe you want to block programs that bind to some specific interfaces. – Cristian Ciupitu May 17 '11 at 20:15
  • 1
    Don't forget you can also specify your sources in a chain like: `--src 1.2.3.4/30` – deed02392 Jan 02 '13 at 20:01
  • How would I later add a new allowed IP to the chain? Would I have to remove the DROP first, then enter the new user and insert the DROP again or is there a better solution? – maddo7 Jun 03 '15 at 20:15
  • 2
    @Matthias: `iptables -I xxx --src 7.8.9.10 -j ACCEPT` – Cristian Ciupitu Jun 03 '15 at 20:17
0

Here's an example from one of my CentOS systems (addresses have been obfuscated):

-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp -s 1.2.3.4 -d 5.6.7.8 --dport 22 -j ACCEPT
obfuscurity
  • 761
  • 3
  • 7
0

I use shorewall to configure IP table. Use a rule like to accept from one host to port 123.

ACCEPT net:192.0.2.1 $FW tcp 1234

BillThor
  • 27,354
  • 3
  • 35
  • 69