SSH

From WTFwiki
Jump to navigation Jump to search

SSH port forwarding is a magical technique that allows you to tunnel a port over ssh to a remote machine. It is useful in traversing firewalls and suchlike.

SSH Port Forwarding

Tunneling ports to the local machine

To tunnel a remote port to a port on the local machine use ssh -L.

 ssh -L [bind_address:]port:host:hostport remote_host

bind_address is optional and can be used to bind to a specific IP on the local machine (defaults to loopback).

For example, if I wanted to do X11 forwarding over a firewall:

 ssh -L 6000:myworkstation.work:6000 firewall.work

This would create a ssh connection to the firewall firewall.work, open a tunnel through to myworkstation.work on port 6000 and open a port on the local machine (the one you ran the ssh command from) on port 6000(which might be a bad idea for X11).

Tunneling ports to a remote machine

SSH -R allows you to create a tunnel to a remote machine, and expose a service there.

 ssh -R [bind_address:]port:host:hostport remote_host

Again, bind_address is the address to bind to and again it defaults to the loopback.

For example, if you wanted to expose your work machine to home (and you had a box that had internet facing ssh access).

 ssh -R 6000:myworkstation.work:6000 gateway.home

Then, port 6000 on your gateway at home is tunneled to port 6000 on your machine at work.

An example for letting people ssh to your machine via an external server (for if you're NATed on a network you don't control)

 sudo  ssh -R :2222:127.0.0.1:22 myserver -v -N

If you want people to be able to connect to your server from their machine, you need to enable the 'GatewayPorts' sshd option.

Additional Notes

The machine you're forwarding to doesn't have to be the local machine. Any machine you can ssh to from the machine you're running the ssh command on can be the destination or target of the forwarding.

Backups over SSH

There's a couple ways to do this, each one has pros and cons...

Backups from local machine to backup machine

This will work with anything that outputs to stdout and you can compress it on the local machine before sending it over the network.

 dd if=/dev/sda | bzip2 -9 -c | ssh user@backupserver "cat > ~/backup.bz2"

Backups from backup machine from backed up machine

This can be run from the backup machine to remotely connect to another machine and back it up

 ( ssh user@remote sudo dd if=/dev/hda ) >localfile.img