Skip to content

Instantly share code, notes, and snippets.

@egernst
Last active March 11, 2019 23:06
Show Gist options
  • Save egernst/37f3b4bc8ea8445b72a2b8beb2d7ecda to your computer and use it in GitHub Desktop.
Save egernst/37f3b4bc8ea8445b72a2b8beb2d7ecda to your computer and use it in GitHub Desktop.
port forward and tunneling fun

Reverse Tunneling, or "how can I access that machine that is behind another network?"

Let's say we have a few test machines sitting behind a workstation router

Assuming the 'router' will forward traffic out, we can facilitate SSH'ing 'directly' to a test machine beind the router by leveraging reverse tunneling:

ssh -f -N -R 19999:localhost:22 <username>@<users host>

where: -f tells ssh to run in the background -N specifies I'm not going to run commands on the remote (useful for just port forwarding), -R :

    -R [bind_address:]port:local_socket
    -R remote_socket:host:hostport
    -R remote_socket:local_socket
    -R [bind_address:]port
            Specifies that connections to the given TCP port or Unix socket on the remote (server) host are to be forwarded to the local side.

            This works by allocating a socket to listen to either a TCP port or to a Unix socket on the remote side.  Whenever a connection is made to this port or Unix socket,
            the connection is forwarded over the secure channel, and a connection is made from the local machine to either an explicit destination specified by host port hostport,
            or local_socket, or, if no explicit destination was specified, ssh will act as a SOCKS 4/5 proxy and forward connections to the destinations requested by the remote
            SOCKS client.

            Port forwardings can also be specified in the configuration file.  Privileged ports can be forwarded only when logging in as root on the remote machine.  IPv6
            addresses can be specified by enclosing the address in square brackets.

            By default, TCP listening sockets on the server will be bound to the loopback interface only.  This may be overridden by specifying a bind_address.  An empty
            bind_address, or the address ‘*’, indicates that the remote socket should listen on all interfaces.  Specifying a remote bind_address will only succeed if the server's
            GatewayPorts option is enabled (see sshd_config(5)).

Now, from the machine <username>@<users host>, the user can access the test machine via ssh <test-machine-user>@localhost -p 19999

Port forwarding so you can access a port on a remote machine via localhost

ssh -nNT -L <local-port-to-map-to>:localhost:<remote-port-we-forward> <users@hostname>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment