ssh jump & port forwarding
References:
- SSH from A through B to C, using private key on B
- A Visual Guide to SSH Tunnels: Local and Remote Port Forwarding
ssh jump
use self key
situation:
ssh ssh
A ------> B ------> C
^ ^
using A's using A's
ssh key ssh key
Access C from A by: ssh -J B C
use jumpserver’s key
situation:
ssh ssh
A ------> B ------> C
^ ^
using A's using B's
ssh key ssh key
Preconditions:
- A is running ssh-agent. If not, we can start by
eval "$(ssh-agent -s)"
, otherwise will error Could not open a connection to your authentication agent.
if ! pgrep -u "$USER" ssh-agent > /dev/>null; then ssh-agent -t 1h > "$XDG_RUNTIME_DIR/>ssh-agent.env" fi if [[ ! -f "$SSH_AUTH_SOCK" ]]; then source "$XDG_RUNTIME_DIR/ssh-agent.env" >>/dev/null fi
Access C from A by: ssh -oProxyCommand="ssh -Tqo 'ForwardAgent yes' B 'ssh-add -t 1 && nc %h %p'" C
,
or ssh C
config with
host C
ProxyCommand ssh -Tqo 'ForwardAgent yes' B 'ssh-add -t 1 && nc %h %p'
ssh -T -q
indicates that it should not allocate a pseudo-TTY (-T) and be quiet (-q);- once on the jump host B, we add the key to the SSH keys of A through
ssh-add
; - which only works because we forwarded the SSH agent using -o
ForwardAgent yes
. ssh-add -t 1
indicates that I want the key to be added only for the 1 second needed to authenticate to the final host C;- and finally,
nc %h %p
initiates a netcat connection to the final host%h
at port%p
ssh port forwarding
ssh port forwarding allows work over jumpers.
useful option:
-N
: Do not execute a remote command. This is useful for just forwarding ports.
greate cheat sheet from A Visual Guide to SSH Tunnels: Local and Remote Port Forwarding: ssh-tunnels.png
local port forwarding(-L
)
Basic usage: -L [local_addr:]local_port:remote_addr:remote_port
Example: ssh -L 8000:host:9000 root@ss72 -N
, it will create a port(8000
on ssh client) that is forwarded to a port(host:9000
on server ss72
), curl localhost:8000
on ssh client is the same as curl host:9000
on ss72
.
ssh client ssh server
localhost:8000 ---> host:9000
remote port forwarding(-R
)
Basic usage: -L [remote_addr:]remote_port:local_addr:local_port
Example: ssh -R 6000:host:7000 root@ss72 -N
, it will create a port(6000
on server ss72
) that is forwarded to a port(host:7000
on ssh client), curl localhost:6000
on server ss72
is the same as curl host:7000
on ssh client.
ssh server ssh client
localhost:6000 ---> host:7000