Port forwarding can be one of the more confusing aspects of pivoting between machines and networks. Both remote and local SSH forwarding can be even more confusing in the sense it matters who is initiating the connection, and who the destination server is. I’ll run through remote port forwarding here, and in a seperate page, cover local forwarding.
To begin with we will outline the concept, then we will follow this up with an example.
ssh <ssh server> -R [SSH Server IP to Bind To]:[SSH Server Port to Bind To]:[Target Destination]:[Target Port]
Once we run this command, it will open a listening port on the server machine, and any traffic sent to that port will be sent to the IP address specified as target, from the perspective of the connection initiator So, what do we mean by that? We have the following scenario with our friend Rick. He wants to be able to access his test webpage that he is developing from home, but his work won’t make it exposed to the internet.
Home (IP 22.214.171.124) – A home computer running a SSH server belonging to Rick.
Work (Web Server Port 80) – Rick’s work computer with a web server running on localhost, port 80.
ssh <ssh server> -R [SSH Server IP to Bind To]:[SSH Server Port to Bind To]:[Target Destination][Target Port]
ssh email@example.com -R 8080:127.0.0.1:80
Once this command is executed, and the password entered, do not interact with this shell. A port has been bound (8080) on Rick’s home machine, which is his SSH server. Any traffic sent to his home PC on port 8080 will be forwarded via SSH to the IP address 127.0.0.1, port 80 – relative to the machine which initiated the connection. Because Rick initiated the connection from his work computer, it will hit his web server listening on his work machine. Rick can now browse his site from home.
Once more, from an attacking perspective, this command get’s more powerful when targeting a second victim. If Rick wished to browse the Domain Controller RDP service from home, he could instead replace 127.0.0.1 with the IP of the DC, and port 80 to 3389. When he got home he could now RDP into the Domain Controller via his localhost, port 8080!
One quirk with remote port forwarding is that, by default, most SSH configuration’s will not allow you to bind to external IP addresses of a remote server. In this example, if we specified the [SSH Server IP to Bind To]:[SSH Server Port to Bind To] parameters to be 0.0.0.0:8080, it would in fact only bind to 127.0.0.1:8080 on the server. If you require the IP address to be bound to an externally accessible IP address, you need to configure GatewayPorts=yes in the sshd_config file. This would be useful if say Rick wanted to browse the work website from his laptop at home, which was seperate to his SSH server.