How to redirect to reverse tunnel server with different port?
Setup:
Server A ( Hosted in private network, need VPN access )
Server B ( Public hosted )
Server C ( U can assume is my own macbook )
I use autossh
to setup my reverse tunneling at server A
with this command autossh -f -T -M 20002 -o "ServerAliveInterval 10" -o "ServerAliveCountMax 2" -N -R 19999:localhost:22 user@server_b
Then in my Server B
I able to run ssh localhost -p 199999
to connect my server A.
Server B also enabled ssh port for 22
and 2022
at /etc/ssh/sshd_config
Problem statement:
How do I use command ssh user@server_b -p 2022
at Server C to redirect access the Server A tunnel from Server B?
Big picture
macbook -- ssh ( port 2022 ) --> server B -- redirect ssh ---> Server A
**must able to do scp task
- To use a reverse tunnel automatically it is recommended to use
autossh
service. - I recommend to follow those steps:
- Change keys between the servers you want to tunnel.
- save your server A public_key on your server B
/home/user/.ssh/authorized_keys
file. - make the first connection manually with
ssh user@serverB
and see the connection is working fine. - do the same with server C - save your server B public_key on your server C
/home/user/.ssh/authorized_keys
file. - check the connection manually.
- save your server A public_key on your server B
- Now you have to redirect the ports you want with
autossh
- but first lets check that manually:- connect to your A server from your local pc with
ssh user@serverA
- on your server A shell - port forward the
ssh
connection from server A to server B withssh -R <portX>:localhost:22 user@serverB
-
on your server B shell - port forward the serverA
ssh
tunnel withssh -R <portY>:localhost:<portX> user@serverC
. - now open another terminal on your local pc (without closing the existing terminal) and try to use the redirected tunnel with
ssh user@serverC -p <portY>
this should connect you to server A through servers C and B in the specific order.
- connect to your A server from your local pc with
- Now after the tunnel seems to work fine we can automate the process by creating an
autossh
service (here is the one i am using):
[Unit]
Description=Keeps a tunnel to 'VPS' open
After=network-online.target
[Service]
User=root
ExecStart=/usr/bin/autossh -M portZ -i /root/.ssh/id_ed25519 -o "ExitOnForwardFaliure=yes" -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -N -R portX:127.0.0.1:22 [email protected]
Environment=AUTOSSH_GATETIME=0
Restart=always
RestartSec=3
StartLimitIntervalSec=0
StartLimitAction=reboot
StartLimitBurst=0
[Install]
WantedBy=multi-user.target
Now if you want to copy something into your computer with scp
from server A just run the command on your local pc terminal:
scp -P <portY> user@serverC:/path/path/filename localpcpath/path/.
Note: my answer assume that you have already created ssh keys
and that your sshd_config
file is configured well.