77

I have struggled throughout the years to get a solid understanding on iptables. Any time I try and read through the man pages my eyes start to glaze over.

I have a service that I only want to allow the localhost to have access to.

What terms (or configuration, if someone is feeling generous) should I Google for to allow only localhost host to have access to a given port?

3 Answers3

86

If by service you mean a specific port, then the following two lines should work. Change the "25" to whatever port you're trying to restrict.

iptables -A INPUT -p tcp -s localhost --dport 25 -j ACCEPT
iptables -A INPUT -p tcp --dport 25 -j DROP
Hyppy
  • 15,814
36

I'd recommend:

iptables -A INPUT -i lo -p tcp --dport $APP_PORT -j ACCEPT
iptables -A INPUT -p tcp --dport $APP_PORT -j DROP

Because, self-addressed packets do not necessarily have 127.0.0.1 as its source, but they all 'enter' from the lo interface.

Now, if you really want to understand iptables the first thing you should do is to download and print good diagrams explaining the relations of the netfilter tables. Here are two great ones:

Finally, read a lot of iptables HOWTO's. The practical examples would help you get up-to-speed real quick :)

pepoluan
  • 5,248
0

I had a similar problem. I configured iptables to deny incoming requests from all ports except the ones I specifically want to allow. I didn't bother to allow 27107 because I mistakenly reasoned that iptables affects only traffic from other hosts, and I don't need to expose this instance of mongodb to the outside world.

I was wrong about iptables. When I added this rule, it worked again:

-A INPUT -p tcp -m tcp -s localhost --dport 27017 -j ACCEPT

This tells netfilter to accept incoming traffic to port 27017 as long as it's from the local host.

If I want to access this instance of mongo from a different host (such as my laptop), I can still do so with an IP tunnel.