Linux Digest

Kali Linux · Metasploit · OSCP · Pentest tutorials

SSH Tunneling Metasploit: A Practical Guide for Pivoting

SSH tunneling in Metasploit is the practice of using a compromised host to route network traffic through an encrypted SSH connection, effectively turning that host into a gateway to an internal network. You can achieve this by using the auxiliary/server/socks_proxy module to create a SOCKS server on your attack machine or by using the portfwd command within a Meterpreter session to map remote ports to your local environment. These techniques allow you to bypass firewall restrictions and reach targets that are otherwise inaccessible from your primary attack position.

In my years of performing penetration tests, I've found that network segmentation is often the biggest hurdle after gaining an initial foothold. You might land on a web server in a DMZ, only to find that the juicy database servers and domain controllers are hidden three layers deep in the network. This is where mastering SSH tunneling metasploit workflows becomes a career-defining skill. It isn't just about running a command; it is about understanding how to manipulate traffic flows to make the internal network feel like it is directly connected to your Kali Linux machine.

Key Takeaway: SSH tunneling is your primary method for lateral movement when direct routing is blocked. By using Metasploit’s built-in routing and proxy modules, you can use a single SSH session to scan, exploit, and manage an entire internal subnet.

Mastering SSH Tunneling Metasploit Fundamentals

Before jumping into the Metasploit console, you need to understand what the protocol is doing under the hood. SSH (Secure Shell) isn't just for remote command execution; it is a powerful transport layer. When we talk about ssh tunneling metasploit, we are usually looking at three distinct types of port forwarding. Each serves a specific purpose depending on where you are in the network and what you want to reach.

Local Port Forwarding vs. Dynamic Forwarding

Local port forwarding (the -L flag in standard SSH) takes a port on your local machine and tunnels it to a specific port on a remote machine. For example, if you want to access a web server on 192.168.1.50 that only the compromised host can see, you would map your local port 8080 to the remote port 80. This is great for single targets but lacks flexibility for broad network discovery.

Dynamic port forwarding (the -D flag) is much more useful for pentesters. It turns your SSH client into a SOCKS proxy. Instead of mapping one port to one target, you can point your tools (like Nmap or a browser) at the SOCKS proxy, and the SSH tunnel will handle the routing to any IP or port the compromised host can reach. Within the Metasploit ecosystem, we replicate this behavior using the SOCKS proxy modules to facilitate pivoting.

Why Use Metasploit for SSH Tunneling?

You might wonder why you should bother with Metasploit when you could just use the native OpenSSH client. The answer lies in integration. Metasploit allows you to manage multiple sessions, automate the routing of all internal modules through a specific tunnel, and use post-exploitation tools without leaving the framework. If you've used the Msfvenom payload generator tutorial to create a Linux-based stager, having an SSH session ready to tunnel your next stage is a huge advantage.

Setting Up a SOCKS Proxy in Metasploit

The most common way to implement ssh tunneling metasploit is by setting up a SOCKS proxy. This allows external tools like Proxychains to "talk" through your Metasploit session. I've used this countless times to run vulnerability scanners against internal targets that the client thought were safe behind their firewall.

Configuring the SOCKS Server Module

Metasploit includes a specific auxiliary module for this purpose. Usually, I prefer using SOCKS5 because it supports UDP and authentication, though SOCKS4a is often sufficient for simple TCP scanning. To start the proxy, follow these steps in your msfconsole:

use auxiliary/server/socks_proxy
set SRVHOST 127.0.0.1
set SRVPORT 1080
set VERSION 4a
run

By setting SRVHOST to 127.0.0.1, you ensure the proxy is only accessible from your local machine. This is a critical security step; you don't want to accidentally open a proxy on your attack box that the rest of the internet can use. Once the module is running, Metasploit is listening on port 1080, ready to route traffic through any active sessions you have configured in your routing table.

Routing Traffic Through Active Sessions

The proxy server by itself doesn't know where to send the traffic. You must tell Metasploit which session to use for which network range. If you have an active SSH session (Session 1) on a host that has access to the 10.10.10.0/24 network, you would run:

route add 10.10.10.0 255.255.255.0 1

This command tells Metasploit: "Any traffic destined for 10.10.10.x should be sent through Session 1." You can verify this by running route print. This combination of a SOCKS proxy and the route command is the bread and butter of SSH tunneling metasploit operations.

Pivoting Through a Compromised SSH Host

Sometimes you don't start with an SSH session; you start with a Meterpreter shell. However, the host might have SSH services running, or you might want to establish an SSH tunnel to bypass certain traffic inspections that flag Meterpreter's custom protocol. In these cases, you can use the host's native SSH capabilities to your advantage.

Using Autoroute and Routing Tables

If you're in the middle of an OSCP exam or a high-pressure engagement, you don't want to manually calculate subnets. The post/multi/manage/autoroute module is a lifesaver. It automatically detects internal interfaces and adds the necessary routes to Metasploit’s internal routing table. Once these routes are in place, any Metasploit module you run will automatically use the tunnel.

For example, if you want to check for SMB vulnerabilities on a newly discovered internal host, you can use the information from our SMB brute force Metasploit guide. Because your route is set, the brute force traffic will flow through the SSH tunnel or Meterpreter session seamlessly.

The Meterpreter Portfwd Command

While SOCKS proxies are great for general scanning, portfwd is better for targeting specific services. If you discover a Windows machine inside the network with RDP (port 3389) enabled, you can use portfwd to map that remote port to your local machine. This is a classic ssh tunneling metasploit move.

meterpreter > portfwd add -l 3389 -p 3389 -r 10.10.10.50

Now, you can simply open your RDP client on Kali and point it to 127.0.0.1. The traffic is tunneled through your session and exits from the pivot host directly to the target. This technique is often more stable than SOCKS for heavy protocols like RDP or complex web applications.

Comparing SSH Tunneling with Metasploit Port Forwarding

Choosing the right tool for the job is what separates juniors from seniors. While both achieve the same goal, the performance and stealth characteristics vary. I've put together a quick comparison based on my experience in the field.

Method Complexity Speed Best Use Case
Metasploit SOCKS Proxy Medium Moderate Scanning subnets with Nmap/Proxychains.
Meterpreter Portfwd Low Fast Accessing specific services (RDP, DB, Web).
SSH Dynamic (-D) High Very Fast Bypassing deep packet inspection (DPI).
Metasploit Autoroute Very Low Moderate Automated pivoting for MSF modules.

Advanced Post-Exploitation Using SSH Tunnels

Once you have your tunnel established, the real work begins. You are no longer just an outsider; you have a virtual presence inside the network. This is the stage where you use your SSH tunneling metasploit setup to gather credentials and escalate privileges. I often find that once I'm inside, the internal security is much weaker than the perimeter.

If you've managed to pivot to a Windows machine, your next step should be credential harvesting. You can refer to our guide on dumping passwords with Mimikatz to find cleartext passwords or hashes in memory. With a tunnel in place, you can run these tools remotely or upload them through your session. These credentials can then be used to SSH into other Linux boxes or authenticate via SMB to more Windows targets.

Optimizing Proxychains for SSH Tunneling

To use external tools like Nmap, sqlmap, or enum4linux through your Metasploit tunnel, you need Proxychains. This utility intercepts network calls and forces them through your SOCKS proxy. On Kali Linux, edit the /etc/proxychains4.conf file and ensure the last line matches your Metasploit SOCKS settings:

socks4  127.0.0.1 1080

One tip from the field: always use the -sT (TCP Connect scan) flag in Nmap when scanning through a SOCKS proxy. SOCKS proxies cannot handle the raw packets required for a default SYN scan (-sS). If you forget this, Nmap will give you "host down" errors or extremely inaccurate results, which can be incredibly frustrating during a timed exam.

Maintaining Persistence and Stability

SSH tunnels are notorious for dropping if there is a network hiccup. If your tunnel dies, your entire attack infrastructure against the internal network collapses. I recommend using the ServerAliveInterval and ServerAliveCountMax options if you are using a native SSH client, or Metasploit's persistence modules to ensure your session stays alive. You can learn more about these in our Metasploit post-exploitation techniques article.

Detection and Defense Against SSH Tunneling

As a red teamer, you must know how defenders catch you. While SSH tunneling metasploit traffic is encrypted, it isn't invisible. Defenders look for "long-lived" SSH connections, especially those originating from unusual sources like a web server or a printer. They also look for high volumes of data being transferred over port 22, which suggests data exfiltration or heavy tunneling.

According to research from security firms, many organizations now use Deep Packet Inspection (DPI) to identify SSH-in-SSH or other protocols hidden inside the tunnel. To stay stealthy, I often recommend changing the default SSH port to 443 (HTTPS) to blend in with standard web traffic. You can find more information on these techniques in the MITRE ATT&CK: Non-Standard Port documentation.

Expert Warning: Never tunnel highly sensitive data over an SSH connection you established via a compromised host unless you trust the integrity of that host. The root user on the pivot machine can theoretically sniff the traffic before it enters the tunnel.

Troubleshooting Common SSH Tunneling Issues

If your SSH tunneling metasploit setup isn't working, it’s usually due to one of three things: routing, firewall rules, or proxy configuration. I've spent hours debugging these, and it usually comes down to a simple oversight.

When in doubt, use the netstat -antp command on both your attack machine and the pivot host to see if the expected ports are listening and established. Seeing a ESTABLISHED state on port 22 or your custom listener port is the first sign of success.

Frequently Asked Questions

What is the difference between SSH tunneling and a VPN?

SSH tunneling operates at the application or transport layer (Layer 4/7) and is generally used for specific ports or via SOCKS. A VPN creates a virtual network interface at the data link or network layer (Layer 2/3), providing a more "complete" network experience but often requiring higher privileges and more complex setup than a simple SSH pivot.

Can I use Metasploit SSH tunneling on Windows hosts?

Yes, modern versions of Windows 10 and Windows Server 2019/2022 include a native OpenSSH server. If you have administrative credentials, you can enable the SSH service and use it for tunneling exactly like a Linux host. Alternatively, you can use Metasploit's portfwd command within a Meterpreter session on any Windows version.

Is SSH tunneling slower than direct exploitation?

Generally, yes. Because the traffic must be encrypted, encapsulated, and decrypted at each hop, there is a performance overhead. This is especially noticeable when running high-bandwidth tools like large Nmap scans or transferring files. I recommend keeping your scans targeted to minimize the impact of this latency.

How do I stop my SSH tunnel from timing out?

In Metasploit, you can use the SessionKeepAlive setting. In a standard SSH client, add -o ServerAliveInterval=60 to your command. This sends a "null" packet every 60 seconds to keep the connection active and prevent firewalls from closing the "idle" session.

For more technical guides on mastering your pentesting environment, check out our Kali Linux Nessus setup guide or learn how to visualize your attacks with our Armitage tutorial. You can also find more resources on the OpenSSH official website or the Metasploit Framework GitHub repository.