Port Forwarding with a Bastion Host (Accessing a VM on Private IP)



In cloud or private network setups, VMs are often on private subnets for security. Direct access to these VMs isn't allowed from outside. Instead, you use a Bastion Host as a jump point to access the private VM. Port forwarding is a technique that allows you to securely connect to the private VM using the bastion host as a middleman.


Flow Explanation:

  1. Bastion Host: A publicly accessible server in a secure zone that has SSH access to the private network.
  2. VM on Private IP: The machine you want to connect to, which is unreachable directly from outside the network.
  3. Port Forwarding:
    • You create a tunnel (via SSH) from your local machine to the private VM through the bastion host.
    • Your local machine forwards requests to a local port (e.g., localhost:8888) which are routed through the bastion host to the private VM's port (e.g., 192.168.1.50:22).

How to Set Up Port Forwarding

  1. Prerequisites:

    • SSH access to the bastion host.
    • SSH key or credentials for the private VM.
    • A terminal or SSH client.

Command Syntax:


ssh -L [local_port]:[target_vm_ip]:[target_port] [user]@[bastion_host]

Explanation:

  • -L: Specifies local port forwarding.
  • [local_port]: A port on your local machine (e.g., 8888).
  • [target_vm_ip]: The private IP of the VM (e.g., 192.168.1.50).
  • [target_port]: The port you want to forward to (e.g., 22 for SSH, 80 for HTTP).
  • [user]: Your SSH username for the bastion host.
  • [bastion_host]: Public IP or hostname of the bastion host.
  1. Example Command:


    ssh -L 8888:192.168.1.50:22 user@bastion.example.com
    • Connects your local machine's port 8888 to the private VM's port 22 via the bastion host.
  2. Access the Private VM:

    • Open a new terminal.
    • Use SSH to connect to the VM via the forwarded port:

      ssh -p 8888 user@localhost

Example Scenario

  • Bastion Host: Public IP: 35.198.120.10
  • Private VM: Private IP: 192.168.1.100
  • Port to Access: 22 (SSH)

Steps:

  1. Run the following command to set up the tunnel:

    ssh -L 8888:192.168.1.100:22 user@35.198.120.10
  2. In a new terminal, SSH into the private VM:

    ssh -p 8888 user@localhost

Representation:

Here’s a step-by-step flowchart for this scenario:


  1. User's Local Machine:

    • Sends request to localhost:8888.
    • Local forwarding forwards it to the bastion host.
  2. Bastion Host:

    • Receives the forwarded request.
    • Relays it to the private VM (192.168.1.100:22) inside the private network.
  3. Private VM:

    • Processes the request and sends the response back via the same path.






Please do like and subscribe to my youtube channel: https://www.youtube.com/@foalabs If you like this post please follow,share and comment