SSH tunnel to Raspberry Pi

3 min read

You may want to be able to connect to your RPi which placed in home without static IP. The simplest solution is the using of the common server.

Raspberry will have stable connection to it by the internal service command. And you as a user can get there by jumping from one ssh connection to another.

The common server needs to know the both public keys of your computer and the RPi.

Preparation

Firstly you need to generate a new ssh key on the Raspberry.

ssh-keygen

You will be asked about key name and password. Left these fields with default values.

Then you need to place RPi's public key to the common server to /root/.ssh/authorized_keys file.

Try to connect to that server from RPi.

ssh root@<COMMON_SERVER_IP> -p 22

If it is the first attempt to connect to that server with current machine then you will be asked for adding this destination to known hosts list. Agree it.

Service

Now we are going to create a service which will be started automatically. It creates an SSH session between RPi and common server.

Creating

Create a service config.

nano /etc/systemd/system/tunnel.service

Place into this file the following code.

[Unit] Description=SSH Tunnel with target server After=network.target [Service] ExecStart=/usr/bin/ssh -NT -o ServerAliveInterval=60 -o ExitOnForwardFailure=yes -R 0.0.0.0:10000:localhost:22 -p 12345 root@99.55.77.222 RestartSec=5 Restart=always [Install] WantedBy=multi-user.target

And you may need a few comments about the main command.

Request to port 10000 on the common server will be redirected to 22 port on RPi.

Also if you have custom port for SSH connections on that server, you may pass it as -p 12345 option as in example or remove it if you use default.

And the last and the obvious thing — root@99.55.77.222 — username and IP address of the common server.

You can test this command before running service.

/usr/bin/ssh -NT -o ServerAliveInterval=60 -o ExitOnForwardFailure=yes -R 0.0.0.0:10000:localhost:22 -p 12345 root@99.55.77.222

And on the server's side you can check if the port 10000 was used correctly via netstat -tulpn.

Running

Update config files for services.

systemctl daemon-reload

Start tunnel service.

systemctl start tunnel

Enable run on boot.

systemctl enable tunnel

Check service state.

systemctl status tunnel

Connection

Make sure that common server has a public ssh key of the your computer first.

Now you can connect to RPi (you -> server -> RPi) via the following command from everywhere. Of course use your own params for server IP and port.

ssh -J root@99.55.77.222:12345 -p 10000 root@localhost

Links

Setup a secure (SSH) tunnel as a systemd service // gist.github.com

SSH tunnel to Pi via my own server // raspberrypi.org

Creating a Linux service with systemd // medium.com