How to reliably keep an SSH tunnel open?

244

109

I use an SSH tunnel from work to go around various idotic firewalls (it's ok with my boss :)). The problem is, after a while the ssh connection usually hangs, and the tunnel is broken.

If I could at least monitor the tunnel automatically, I could restart the tunnel when it hangs, but I haven't even figured a way of doing that.

Bonus points for the one who can tell me how to prevent my ssh connection from hanging, of course!

Peltier

Posted 2009-09-08T13:04:22.457

Reputation: 4 834

It is your tunnel dead because inactivity? I had this problem when tunneling ports from my phone so i finally ended spawning dummy commands on the connection to make it "alive" using the watch command like: watch -n1 60 echo "wiiiii". Tunnel will not die unless network is broken or you don't use it. – m3nda – 2017-02-10T02:07:27.580

1

Related: https://unix.stackexchange.com/q/200239/

– sampablokuper – 2017-12-29T16:28:20.213

Answers

296

Sounds like you need autossh. This will monitor an ssh tunnel and restart it as needed. We've used it for a couple of years and it seems to work well.

autossh -M 20000 -f -N your_public_server -R 1234:localhost:22 -C

More details on the -M parameter here

KeithB

Posted 2009-09-08T13:04:22.457

Reputation: 8 506

5autossh -f -nNT -i ~/keypair.pem -R 2000:localhost:22 username@myoutsidebox.com
You might notice that I set this up using -nNT which doesn't create a remote terminal so that I can put autossh into the background, and the -i option for SSH to use a .pem file. If you're going to be keeping a connection open all the time, I definitely recommend going through the extra setup.
– juckele – 2015-08-31T20:01:02.610

2

For what it's worth, it looks like it's typically better to omit the -M parameter: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=351162

– rinogo – 2015-09-15T22:40:46.877

If its not working and you are using keys, check this answer - http://serverfault.com/a/545093/288788

– muttonUp – 2016-11-09T11:30:06.533

How can I make autossh retry even if the first connection ever fails? – PedroD – 2017-03-10T16:09:14.030

2I did this to make it retry upon network change, it works well for me: autossh -M 0 -o "ServerAliveInterval 10" -o "ServerAliveCountMax 2" -L 9999:localhost:19999 server@example.com – Luke Stanley – 2017-06-29T13:23:07.530

1How does that work if I have a passphrase ? would it store that passphrase in a keychain ( for example on a mac ) ? – Yannick Y – 2017-11-06T16:08:50.073

Just used this. But after 10 minutes, the ssh connection is dead, even though I had added a 20 secs AUTOSSH_POLL interval. – cmal – 2018-04-28T13:29:18.480

mosh is also a great tool, but you need to install on server. – Jack Wasey – 2018-10-19T15:07:22.707

2For those who just copy and then wonder why their connection might be slow: -C forces compression of the connection, it's useful on modem lines and slow internet connections but if a fast connection is in place it will actually slow things down. Nowadays it should most likely be not used, unless your connection speed is terribly slow. – confetti – 2018-10-23T08:53:30.147

2+1 for autossh, it does what it says on the tin. I believe part of its functionality also is to send keep-alive style packets to prevent any kind of timeout. – akent – 2009-09-08T13:55:28.143

31Could you put the example tunnel using autossh in the answer? – Ehtesh Choudhury – 2012-12-20T21:45:50.747

40

All stateful firewalls forget about a connection after not seeing a packet for that connection for some time (to prevent the state tables from becoming full of connections where both ends died without closing the connection). Most TCP implementations will send a keepalive packet after a long time without hearing from the other side (2 hours is a common value). If, however, there is a stateful firewall which forgets about the connection before the keepalive packets can be sent, a long-lived but idle connection will die.

If that is the case, the solution is to prevent the connection from becoming idle. OpenSSH has an option called ServerAliveInterval which can be used to prevent the connection from being idle for too long (as a bonus, it will detect when the peer died sooner even if the connection is idle).

CesarB

Posted 2009-09-08T13:04:22.457

Reputation: 4 480

Thanks, this helped. But note (from a lower-ranked answer here, http://superuser.com/a/146641/115515) that if you specify ServerAliveInterval and not ServerAliveCountMax, you may find ssh intentionally disconnecting sooner than you wanted.

– metamatt – 2012-01-26T21:54:43.730

The interval specified is in seconds, so you can provide some fine tuning. If your stateful firewall has a 5 minute idle timeout, then 60 or 120 seconds is enough to keep the connection open. It's one of the ways I keep my ssh sessions through my home router open. – Darren Hall – 2009-12-02T21:16:02.200

4@metamatt, that lower-ranked answer you reference is lower-ranked for good reason: IT IS WRONG. – Lambart – 2014-02-20T00:14:38.527

24

On your own mac or linux machine configure your ssh keep the server ssh alive every 3 minutes. Open a terminal and go your your invisible .ssh in your home:

cd ~/.ssh/ 

then create a 1 line config file with:

echo "ServerAliveInterval 180" >> config

you should also add:

ServerAliveCountMax xxxx (high number)

the default is 3 so ServerAliveInterval 180 will stop sending after 9 minutes (3 of the 3-minute interval specified by ServerAliveInterval).

David Shaw

Posted 2009-09-08T13:04:22.457

Reputation: 265

Not working on macOS 10.15.3 – 4F2E4A2E – 2020-02-13T09:58:34.517

2Note that your command is not recommended if you already have a config file. Using >> for redirection would be a lot better! – Peltier – 2011-03-18T09:34:46.270

why does ServerAliveInterval 180 give us 6 minutes? intuition makes me try this : 180/60 == 3. So, does ServerAliveInterval work in multiples of 30 secs? – nemesisfixx – 2011-11-30T14:37:23.767

@mcnemesis: ServerAliveInterval 180 means 3 minutes. ServerAliveCountMax default of 3 means 3 of those intervals, so 9 minutes. – metamatt – 2012-01-26T21:50:03.393

2I'm voting this answer up because thanks for mentioning ServerAliveCountMax, and what happens if you specify ServerAliveInterval without ServerAliveCountMax. But like the preceding comments, I notice the calculation on "will stop sending after" is wrong, and I think this answer would serve better if it just gave the information on these options, not telling us how to apply them with cd and echo commands. – metamatt – 2012-01-26T21:51:26.620

21Downvoting because it makes no sense to set ServerAliveCountMax to a "high number". ServerAliveCountMax specifies how many times it will try to send the "keepalive" message before giving up. The default is 3, so with ServerAliveInterval 180, it will stop sending ONLY if the server has NOT RESPONDED after 9 minutes, in which case your connection is probably well and truly dead. – Lambart – 2014-02-20T00:13:12.613

23

I've used the following Bash script to keep spawning new ssh tunnels when the previous one dies. Using a script is handy when you don't want or can't install additional packages or use compiler.

while true
do
  ssh <ssh_options> [user@]hostname
  sleep 15
done

Note that this requires a keyfile to establish the connection automatically but that is the case with autossh, too.

Jawa

Posted 2009-09-08T13:04:22.457

Reputation: 3 349

1It helps if you can't install things in the server. autossh doesn't come preinstalled and bureucracy it's sometimes very obtuse. – quarkex – 2017-03-13T15:13:57.757

1Yes, preferable not to have to install things. I've been doing it this way for a year as my only way to keep a remote machine accessible (even set crontab to run it upon reboot). It's never failed, and more importantly, I know why it will never fail. – sudo – 2018-04-02T06:42:08.930

2You should add any reasons that you'd use this script over autossh, or is it just that it's easier this way? – kyrias – 2012-10-20T17:25:56.610

4This wouldn't help if ssh itself freezes, would it? – nafg – 2013-11-25T23:59:59.710

21

Systemd is ideally suited for this.

Create a service file /etc/systemd/system/sshtunnel.service containing:

[Unit]
Description=SSH Tunnel
After=network.target

[Service]
Restart=always
RestartSec=20
User=sshtunnel
ExecStart=/bin/ssh -NT -o ServerAliveInterval=60 -L 5900:localhost:5900 user@otherserver

[Install]
WantedBy=multi-user.target

(Modify the ssh command to suit)

  • this will run as user sshtunnel so make sure that user exists first
  • issue systemctl enable sshtunnel to set it to start at boot time
  • issue systemctl start sshtunnel to start immediately

Update Jan 2018: some distros (e.g. Fedora 27) may use SELinux policy to prevent the use of SSH from systemd init, in which case a custom policy will need to be created to provide the necessary exemptions.

IanB

Posted 2009-09-08T13:04:22.457

Reputation: 375

2

This looks very similar to my gist: https://gist.github.com/guettli/31242c61f00e365bbf5ed08d09cdc006#file-ssh-tunnel-service Feedback is welcome!

– guettli – 2017-12-22T11:47:02.607

Excellent for a systemd system. If one uses Restart=on-failure then manually killing the SSH client will not result in a restart-by-systemd as the SSH client with exit with success. – David Tonhofer – 2018-03-22T19:36:40.770

If you want to start ssh from a (bash) script given as argument to ExecStart for example to build the ssh argument list, do basic checks etc then call it from the script like so exec /bin/ssh -N .... Here is my command: exec /bin/ssh -N -oExitOnForwardFailure=Yes -oTCPKeepAlive=no -oServerAliveInterval=5 -oServerAliveCountMax=6 -i "${LOCAL_PRIVATE_KEY}" -L "${TUNNEL_INLET}:${TUNNEL_OUTLET}" "${REMOTE_USER}@${REMOTE_MACHINE}" where TUNNEL_INLET="127.0.0.1:3307" and TUNNEL_OUTLET="127.0.0.1:3306" – David Tonhofer – 2018-03-22T19:42:23.390

11

It sure looks to me that you're all misinterpreting ServerAliveCountMax. As I understand the docs, it is the number of server alive messages which can go unanswered without the connection being terminated. So in cases like we're discussing here, setting it to a high value will just ensure that a hung connection will not be detected and terminated!

Simply setting ServerAliveInterval should be sufficient to solve the problem with a firewall forgetting about the connection, and leaving ServerAliveCountMax low will allow the originating end to notice the failure and terminate if the connection fails anyway.

What you want is, 1) for the connection to stay open permanently under normal circumstances, 2) for connection failure to be detected and the originating side to exit on failure, and 3) for the ssh command to be re-issued every time it exits (how you do that is very platform dependent, the "while true" script suggested by Jawa is one way, on OS X I actually set up a launchd item).

user2793784

Posted 2009-09-08T13:04:22.457

Reputation: 111

9

Always use ServerAliveInterval SSH option in case the tunnel issues are generated by expired NAT sessions.

Always use a respawning method in case the connectivity goes down entirely, you have at least three options here:

  • autossh program
  • bash script (while true do ssh ...; sleep 5; done) do not remove the sleep command, ssh may fail quickly and you'll respawn too many processes
  • /etc/inittab, to have access to a box shipped and installed in another country, behind NAT, without port forwarding to the box, you can configure it to create an ssh tunnel back to you:

    tun1:2345:respawn:/usr/bin/ssh -i /path/to/rsaKey -f -N -o "ServerAliveInterval 180" -R 55002:localhost:22 user@publicip 'sleep 365d'
    
  • upstart script on Ubuntu, where /etc/inittab is not available:

    start on net-device-up IFACE=eth0
    stop on runlevel [01S6]
    respawn
    respawn limit 180 900
    exec ssh -i /path/to/rsaKey -N -o "ServerAliveInterval 180" -R 55002:localhost:22 user@publicip
    post-stop script
        sleep 5
    end script
    

or always use both methods.

claudiuf

Posted 2009-09-08T13:04:22.457

Reputation: 321

1+1 for inline option in case you don't want it for all of your SSH connections – user1146334 – 2014-07-07T14:29:12.170

You write "in case connectivity goes down entirely". Now I don't understand, what problems does autossh fix itself, and what does it not? I thought, of course, it would take care of any broken connection, like unplugging the cable for a few hours, but perhaps not? – Mads Skjern – 2016-05-12T19:02:07.977

6

I solved this problem with this:

Edit

~/.ssh/config

And add

ServerAliveInterval 15
ServerAliveCountMax 4

According to man page for ssh_config:

ServerAliveCountMax
         Sets the number of server alive messages (see below) which may be
         sent without ssh(1) receiving any messages back from the server.
         If this threshold is reached while server alive messages are
         being sent, ssh will disconnect from the server, terminating the
         session.  It is important to note that the use of server alive
         messages is very different from TCPKeepAlive (below).  The server
         alive messages are sent through the encrypted channel and there‐
         fore will not be spoofable.  The TCP keepalive option enabled by
         TCPKeepAlive is spoofable.  The server alive mechanism is valu‐
         able when the client or server depend on knowing when a connec‐
         tion has become inactive.

         The default value is 3.  If, for example, ServerAliveInterval
         (see below) is set to 15 and ServerAliveCountMax is left at the
         default, if the server becomes unresponsive, ssh will disconnect
         after approximately 45 seconds.  This option applies to protocol
         version 2 only.

 ServerAliveInterval
         Sets a timeout interval in seconds after which if no data has
         been received from the server, ssh(1) will send a message through
         the encrypted channel to request a response from the server.  The
         default is 0, indicating that these messages will not be sent to
         the server.  This option applies to protocol version 2 only.

nachopro

Posted 2009-09-08T13:04:22.457

Reputation: 161

@Lambart but if the connection is really flaky and drops connections often, it at least detects a dead connection and gives the opportunity to retry earlier. – binki – 2014-12-13T02:00:36.823

Not working on macOS 10.15.3 – 4F2E4A2E – 2020-02-13T09:59:02.167

Every 15 seconds seems pretty often to ping the server. – Lambart – 2014-02-20T00:08:06.577

4

ExitOnForwardFailure yes is a good adjunct to the other suggestions. If it connects but can't establish the port forwarding it's just as useless to you as if it hadn't connected at all.

jcomeau_ictx

Posted 2009-09-08T13:04:22.457

Reputation: 687

This is a very good idea.

Even autossh is useless if the previous connection is perceived as timed out earlier in the remote side than in the local host, since in this case the local host will try to connect again, but the forwarding cannot be established because the port is still open. – Raúl Salinas-Monteagudo – 2017-05-24T07:42:45.300

1

I've had a need to maintain an SSH-tunnel long-term. My solution was running from a Linux server, and it's just a small C program that respawns ssh using key-based authentication.

I'm not sure about the hanging, but I've had tunnels die due to timeouts.

I would love to provide the code for the respawner, but I can't seem to find it right now.

baumgart

Posted 2009-09-08T13:04:22.457

Reputation: 1 176

1

while there are tools like autossh that helps to restart ssh session... what i find to be really useful is to run the 'screen' command. It allows you to RESUME your ssh sessions even after you disconnect. Especially useful if your connection is not as reliable as it should be.

...don't forget to mark this is the 'correct' answer if it helps you k! ;-)

koss

Posted 2009-09-08T13:04:22.457

Reputation: 219

7... but the question was about how to keep SSH tunnels open, not just a terminal session. Screen IS great though! – akent – 2009-09-08T14:15:15.680

I already use screen, but it doesn't solve my problem :-/ Thanks for your answer, though. – Peltier – 2009-09-08T14:15:47.783

1

A bit of a hack, but I like to use screen to keep this. I currently have a remote forward that has been running for weeks.

Example, starting locally:

screen
ssh -R ......

When the remote forward is applied, and you have a shell on the remote computer:

screen
Ctrl + a + d

You now have an uninterrupted remote forward. The trick is to run screen on both ends

landypro

Posted 2009-09-08T13:04:22.457

Reputation: 21

1

Recently had this issue myself, because these solutions require you to re-enter the password every time if you use a password login I used sshpass in a loop along with a text prompt to avoid having the password in the batch file.

Thought I'd share my solution on this thead in case anyone else has the same issue:

#!/bin/bash
read -s -p "Password: " pass
while true
do
    sshpass -p "$pass" ssh user@address -p port
    sleep 1
done

Brainfloat

Posted 2009-09-08T13:04:22.457

Reputation: 111

0

As autossh does not meet our needs (it exists with error if it can't connect to the server at the very first attempt), we've written a pure bash application: https://github.com/aktos-io/link-with-server

It creates a reverse tunnel for the NODE's sshd port (22) on the server by default. If you need to perform any other actions (like forwarding additional ports, sending mails on connection, etc...) you can place your scripts on-connect and on-disconnect folders.

ceremcem

Posted 2009-09-08T13:04:22.457

Reputation: 363

0

You could very simply use tmux command on your remote server. It allows you to open a "session" on the remote machine where your will run your remote code.

Then you can exit (or lose the connection in your case) the remote machine without worrying given that your code is safely running in your tmux session.

Finally, when you reconnect on the remote server, you only need to tmux attach to come back to the session you had previously open and that's it.

Mat A

Posted 2009-09-08T13:04:22.457

Reputation: 1

0

I have had similar problems with my previous ISP. For me it was the same with any tcp connection, visiting websites or sending mail.

The solution was to configure a VPN connection over UDP(I was using OpenVPN). This connection was more tolerant to whatever caused the disconnections. Then you can run any service through this connection.

There can still be issues with the connection but since the tunnel will be more tolerant any ssh session will feel a short holdup rather than being disconnected.

To do this you will need a VPN service online which you can setup on your own server.

hultqvist

Posted 2009-09-08T13:04:22.457

Reputation: 287