SSH port forwarding via tunneling

July 26, 2020 - Reading time: 2 minutes

Use this to create an encrypted connection between a local/remote box.

*** Local forwarding

Forwards a port from the client machine to the server machine. The ssh client listens for connections on a configured port, tunnels the connection to the server, and the server then connects to the destination address/port.

For example, I want that every client connecting to my IP address 192.168.1.157 on port 8080 to be tunneled to my server on pzolo.info and then have the connection sent to icanhazip.com on port 80:

root@twickenham:~# ssh -L 192.168.1.157:8080:icanhazip.com:80 root@pzolo.info
root@pzolo.info's password:

Now we can see that the ssh client is listening on port 8080 and also has an established connectin, the tunnel, to the server:

root@twickenham:/home/ptosiani# lsof -P | grep 3703 | grep TCP
ssh       3703                      root    3u     IPv4              40524       0t0        TCP 192.168.1.157:60542->pzolo.info:22 (ESTABLISHED)
ssh       3703                      root    4u     IPv4              35436       0t0        TCP 192.168.1.157:8080 (LISTEN)

This is what we see in a packet capture when a client on the network connects to 192.168.1.157:8080:

17:49:47.131557 IP 192.168.1.168.52691 > 192.168.1.157.8080: Flags [S], seq 697753369, win 64240, options [mss 1460,nop,wscale 8,nop,nop,sackOK], length 0
[...]
GET / HTTP/1.1
Host: 192.168.1.157:8080
Connection: keep-alive
[...]
17:49:47.133320 IP 192.168.1.157.60542 > 151.236.216.195.22: Flags [P.], seq 2537745498:2537745598, ack 3952728736, win 501, options [nop,nop,TS val 3200931444 ecr 4168325949], length 100
#
# Then on the server 
#
16:49:47.160112 IP pzolo.info.59848 > dedi4.de.icanhazip.com.http: Flags [P.], seq 1:508, ack 1, win 502, length 507: HTTP: GET / HTTP/1.1
E..#:.@.@.......t.7j...Pm5h..[5;P.......GET / HTTP/1.1
Host: 192.168.1.157:8080
Connection: keep-alive
Cache-Control: max-age=0
#
# Response on the client shows the IP addrss of the server 
#
HTTP/1.1 200 OK
Server: nginx
Date: Sun, 26 Jul 2020 16:49:47 GMT
Content-Type: image/vnd.microsoft.icon
Content-Length: 16
Connection: close
X-SECURITY: This site DOES NOT distribute malware. Get the facts. https://goo.gl/1FhVpg
X-RTFM: Learn about this site at http://bit.ly/icanhazip-faq and do not abuse the service.
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET

151.236.216.195