Script: getting into an iptables-protected server

Translation of the original in Catalan. Read it in: CatalàCastellano

A very human and therefore common phenomenon, when we are configuring a firewall with iptables against a remote server we don't have access to, let's say it's in the USA, is to lock ourselves out when running the script that loads the filtering rules. Then we can reboot the machine through the control panel offered by the ISP, or any other procedure. The problem is that if this script runs as soon as the machine boots, in rc.local or any other startup process, it will be impossible for us to authenticate over SSH after the server boots.

But... as all of us who have watched a linux server boot know, between the moment the SSH server is called and the moment the script with the firewall rules is launched, 1s (~approx) can pass depending on how fast the server is. If we were quick enough authenticating to the machine we could launch a process that would be launched after the iptables script and this script could give us access to the machine again, for example, by flushing the firewall rules and changing the default policy.

Well then, after trying to do it by hand I came to the conclusion that despite having taken a typing course when I was little, I was still too slow and the link was cut before I could regain control of the machine. So I decided to check whether the machine had a language called expect which is based on TCL/TK. This language, as I've already mentioned a few times on the blog, lets us automate interactive processes. So I made this little script:

#!/usr/bin/expect -f

spawn /usr/bin/ssh root@ip_del_servidor 
expect "ssword: $" { send "password_de_root\n" } 
expect "#" { 
  send "echo \"sleep 30;iptables -F;iptables -P INPUT ACCEPT;iptables -P FORWARD ACCEPT;iptables -P OUTPUT ACCEPT\" > rest.sh \nchmod 700 rest.sh\nnohup ./rest.sh\nsleep 5\n./rest.sh" } 
interact

Notice that it's very simple, what it does is connect over SSH to the remote server, send the root password; then it creates a very simple script that is saved to rest.sh, gives it execution permissions and runs it with a nohup so that if our console loses the connection with the server the script doesn't stop running. The content of this little script that gets created is as simple as waiting 30s so that it makes sure the machine has finished the boot process and then flushing the firewall rules and setting the policies to ACCEPT. So we can already get in without problems.

Well then, with this, a ping that watches when the network card has come up and then running this script I've put here, on Tuesday I managed to bring back to life a remote server I had no physical access to, only forcing reboots through the control panel they provided me with. How easy it would have been to have a remote administration console and be done in a second. But I suppose necessity breeds ingenuity, right?