How can I block port 6379 for outside traffic on ubuntu?

I want to block access to port 6379 on my server, but I still want to connect to it internally. The redis-server application runs on that port and I want to connect to it only locally (127.0.0.1). How can I do this?


Solution 1:

To do this, you need to make sure that your IPTables rules are configured properly. Ubuntu generally leaves their servers wide open by default, which is why I still don't recommend their use as servers unless you are quite well aware of how to do this properly already.

I imagine that your iptables -L -nv looks something like this, yes?

# iptables -L -nv
Chain INPUT (policy ACCEPT 4M packets, 9M bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 8M packets, 4M bytes)
 pkts bytes target     prot opt in     out     source               destination

It's empty and it's wide open. The Ubuntu IPTables HowTo will probably help quite a bit with this. (https://help.ubuntu.com/community/IptablesHowTo)

I recommend something like this, which allow SSH on any interface and tcp 6379 any interface but the one you don't want:

*filter
:INPUT DROP [92:16679]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [203:36556]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i lo -p tcp -m tcp --dport 6379 -j ACCEPT
-A INPUT -i lo -p udp -m udp --dport 6379 -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -i lo -j ACCEPT
COMMIT

You would then save this file in /etc/iptables.rules.

Obviously, any other ports that you specifically want open should be added.

Note: I've added the specific 6379 lines for clarity. The bottom ACCEPT right before the COMMIT would actually allow this because all loopback connections must be allowed on a Linux system for proper operation.

You will also want to put the rules in your /etc/network/interfaces file as well, to ensure that they are added when the interface comes up and not later in the boot process. Adding something like this is recommended:

auto eth0
iface eth0 inet dhcp
  pre-up iptables-restore < /etc/iptables.rules

Edit: To load this configuration initially, you need to run the iptables-restore command referenced above:

iptables-restore < /etc/iptables.rules

Solution 2:

Well, I would suggest to use the "uncomplicated firewall" (ufw), which is also recommended by canonical. Reading and writing iptables is too complicated for just occasional port locking tasks.

See here: https://wiki.ubuntu.com/UncomplicatedFirewall