Ssh - Tunnel - From server to local (Right Port Forwarding)

1 - About

When the port is not open on a server, you can still reach it via SSH and a right tunnel (or Right port forwarding).

When the tunnel is active, a request to a local port will be forwarded via the SSH tunnel to the port of the remote server.

Illustration Image Credit: How does reverse SSH tunneling work? from Erik

3 - Steps

With the below example, we will query a HTTP server running on the client from the remote Server through SSH tunneling.

3.1 - Create the tunnel

You can create it with any SSL client such as:

3.1.1 - Ssh

From the client host:


ssh -N -T -l loginName -R8881:localhost:8888 sshServerHost

where

  • localhost is the host seen from the ssh client
  • The remote port is 8881 (The port of the Remote ssh Server)
  • The local host port is 8888
  • The loginName is loginName
  • N means no remote command
  • T disables pseudo-tty allocation (No terminal)

3.1.2 - Jsch

Java with Jsch


JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
int localPort = 8888;
String localHost = "localhost";
int remotePort = 8881;
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
session.setPortForwardingR(localPort, localHost, remotePort);

3.2 - Make a request

Usage Example - Make a request from the server rerouted to your computer: On the remote SSH server request, a call to the port 8881 will be redirected to the port 8880 of localhost.


wget localhost:8881/hello.html


--2017-02-07 12:29:22--  http://localhost:8881/hello.html
Resolving localhost... 127.0.0.1
Connecting to localhost|127.0.0.1|:8881... connected.
HTTP request sent, awaiting response... 200 OK
Length: 5 [text/html]
Saving to: `hello.html'

100%[============================================>] 5           --.-K/s   in 0s

2017-02-07 12:29:23 (62.8 KB/s) - `hello.html' saved [5/5]


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap