Firewall – ufw seems to block all incoming connections when defaulting to block outgoing

firewallubuntu-12.04ufw

I am currently trying to configure ufw on Ubuntu 12.04 but to my understanding it behaves oddly. i tried allowing just some services on a remote machine, denying everything else. I thought – anyway, i might have gotten it wrong – that denying all by default and then allowing some services would serve my purpose, hence i emitted the following commands

ufw allow ssh
ufw default deny incoming
ufw default deny outgoing

To my understanding the last command would only block every connection i am trying to establish from the remote computer to some other computer, but it caused all connections i am trying to establish to the remote computer ending up being rejected. I am pretty sure that this command and not the deny incoming caused this behavior. To me this is quite counter-intuitive. I would suggest that, if I explicitly allowed ssh, i would be able to establish an connection to the remote machine, independent of the default settings. Even more it seems quite strange that blocking the outgoing connections breaks my ssh.

I would be very grateful if anyone could explain this to me.

Best Answer

Let's assume you have a SSH on your serverA on port 22. serverB tries to connect to it. It sends a packet from a random port within a net.ipv4.ip_local_port_range (3252 for example) to serverA 22 port. serverB:3252 -> ufw incoming allow 22 -> serverA:22

So on serverA connection gets allowed because incoming connections on 22 port are allowed, but but when your ssh server responses it sends a response packet from 22 port to serverB 3252 port and outgoing connections due to ufw default deny outgoing are blocked.

serverB:3252 <- ufw outgoing default deny <- serverA:22

So you have to add an allow rule in outgoing chain either for packets with source port 22 or with destination port within a local_port_range - usually 32768-61000 but may vary so better use source port base filtering.