6

I have a server which runs a few services. However, for security reasons, I configured the server so that nothing, except for SSH, is accessible from outside.

What I'd like to do instead, though, is to have the server allow access to all its services to anybody who has managed to successfully login via SSH (and once that person disconnects, close all the ports again, except for the SSH port which should remain open).

Is there a way to do this?

I'm using Arch Linux on the server and ufw to manage the firewall.

houbysoft
  • 4,444

2 Answers2

1

You can put commands in ~/.bashrc, anything in there is executed each time a user logs in.

For your commands to only run when logging in via ssh (and not when logging in physically), you can test for the presence of the SSH_CONNECTION environment variable.

0

I wrote a solution for this. It is not perfect, and improvements are welcome. Especially, I think that ~/.bash_logout doesn't get called if the connection dies, but I want the firewall to close itself in those cases too.

In any case, first of all, configure the sudoers file so that your user can run the ufw binary without entering a password.

Then, in ~/.bashrc:

ip=`echo $SSH_CONNECTION | cut -d " " -f 1`
echo "=> Opening the firewall for $ip..."
sudo ufw allow from $ip
echo "=> Done."

In ~/.bash_logout:

ip=`echo $SSH_CONNECTION | cut -d " " -f 1`
echo "=> Closing the firewall for $ip..."
sudo ufw delete allow from $ip
echo "=> Bye."

Again, though, this will only reclose the ports if you terminate your session properly. If somebody knows how to make it close whenever the connection quits / dies / whatever, please edit this answer with your solution.

houbysoft
  • 4,444