I have an internal NAS which I never want to be able to make an outgoing connection on anything except SSH.

I believe the following rule on my router will block all outgoing traffic for my NAS on

iptables -A OUTPUT --source -m state --state NEW -j DROP

What I'm unclear about is how do I allow an outgoing TCP connection on port 22.


The rule you specified may or may not work to block access - note that you used "-A" which means add the rule to the end of the table. If there is an earlier rule allowing access then that will override the rule. Also, the rule you have is needlessly complex.

To answer to the question you asked is

iptables -I OUTPUT -j DROP
iptables -I OUTPUT -p tcp --dport 22 -j ACCEPT

This sets a rule at the beginning of the input table to drop all traffic. It then inserts a rule before it to allow outgoing SSH connections. Unfortunately this is unlikely to do what you want because (a) it means that any services you have running on the NAS will not work either and (b) DNS lookups won't work and (c) Blocking ICMP can break things - although it works most of the time.

Depending on exactly what you are trying to do, you could tune the rules such that it allows ICMP, incoming connections and SSH and connections as follows:

   iptables -I OUTPUT -m state --state NEW -j DROP
   iptables -I OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
   iptables -I OUTPUT -p icmp -j ACCEPT
   iptables -I OUTPUT -p tcp --dport 22 -j ACCEPT
   iptables -I OUTPUT -p tcp --dport 53 -j ACCEPT
   iptables -I OUTPUT -p udp --dport 53 -j ACCEPT

I note that these rules focus on outgoing traffic. While this can work securely, its often better to handle incoming traffic - particularly if you know the IP address ranges and/or ports which should be allowed to connect. You would do these using the INPUT chain. Maybe something like

iptables -I INPUT -j DROP
iptables -I INPUT -p tcp --sport 53 -j ACCEPT
iptables -I INPUT -p udp --sport 53 -j ACCEPT
iptables -I INPUT -p tcp --sport 22 -j ACCEPT
iptables -I INPUT -s -j ACCEPT
iptables -I INPUT -s -j ACCEPT
iptables -I INPUT -s -j ACCEPT

Which will allow people on your LAN (assuming they are in a common RFC1918 block) to communicate with your device on all protocols, and allow ICMP, DNS and SSH from anywhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.