We’ve expanded our partnership with Mandiant, now part of Google Cloud, to help our users operationalize and prioritize threat intelligence. READ THE PRESS RELEASE >

Hunting Impacket: Part 2

Impacket Overview

Welcome back. This is part two of our blog series covering the Impacket example tools. Impacket is a collection of Python classes focused on providing tools to understand and manipulate low-level network protocols. This capability enables you to craft or decode packets of a wide variety of protocols such as IP, TCP, UDP, ICMP, and even higher-level protocols like SMB, MSRPC, NetBIOS, and others.

One of the key strengths of Impacket is its ability to facilitate the development of scripts and tools for network exploration, penetration testing, and exploit development. It is widely used by security researchers and penetration testers to create or extend their own tools when working on assessments or research projects. Impacket includes modules to perform operations like network authentication cracking, relay attacks, and execution of code on target machines through protocols like SMB.

Moreover, Impacket provides several command-line tools as practical examples of what can be achieved using its classes. These example tools include scripts for executing commands on remote systems, transferring files, port scanning, and gathering system information, etc. Tools such as smbexec, wmiexec, and psexec are particularly notable for their widespread use to perform remote command execution on Windows systems, demonstrating the power and flexibility of Impacket in real-world scenarios. Register for a FREE community account to access the tons of content included in this blog post, as well as thousands of other community detections.

In the previous post we covered psexec, smbexec, and atexec scripts. This time we are going to look at wmiexec, dcomexec, and wmipersist. This will round out what we consider to be the remote code execution tools.

Wmiexec.py

Here is the basic usage of wmiexec to execute a command on a remote host using valid credentials.
Wmiexec.py
Like the other remote code execution Impacket tools, it supports multiple authentication methods. It can also be run in semi-interactive mode to run cmd or powershell commands. All of wmiexec’s commands will be prefaced by specific parameters depending on which shell type is used. Using the powershell shell-type will append the following:
				
					powershell.exe -NoP -NoL -sta -NonI -W Hidden -Exec Bypass -Enc
				
			
The process graph for this shows our command being executed via WMI as expected by the script name.
There are a few new unique things to look at when trying to detect this activity. You will see an interesting DCOM request that can be detected with network intrusion detection tools like Zeek.
				
					sourcetype: bro:dce_rpc:json
operation: RemoteCreateInstance
endpoint: IRemoteSCMActivator
named_pipe: 135
id_resp_p: 135
				
			
You’ll also see WmiPrvSE.exe spawning a command and piping the output to the ADMIN$ on localhost (127.0.0.1). This is slightly different than the output redirection method in the other tools but is used in a few others. This output redirection to the admin share this way is a pretty solid indicator of Impacket. Note that this time instead of a .tmp file it writes to a file beginning with “__” and ending with a timestamp. Hunting for suspicious subprocesses of WmiPrvSE can also bubble up this activity.
				
					EventCode: 1
ParentProcessName: WmiPrvSE.exe
CommandLine: cmd.exe /Q /c powershell.exe -NoP -NoL -sta -NonI -W Hidden -Exec Bypass -Enc JABQAHIAbwBnAHIAZQBzAHMAUAByAGUAZgBlAHIAZQBuAGMAZQA9ACIAUwBpAGwAZQBuAHQAbAB5AEMAbwBuAHQAaQBuAHUAZQAiADsAdwBoAG8AYQBtAGkA 1> \\127.0.0.1\ADMIN$\__1709834834.6321354 2>&1
ParentUser: NT AUTHORITY\NETWORK SERVICE

EventCode: 1
ParentProcessName: WmiPrvSE.exe
CommandLine: cmd.exe /Q /c whoami 1\> \\127.0.0.1\ADMIN$\__1707943085.0702221 2>&1
ParentUser: NT AUTHORITY\NETWORK SERVICE
				
			
Like other techniques, you will see a request for this output file. There will also be file events for the temporary file (C:\Windows\_1709834834.6321354) by the NT AUTHORITY\SYSTEM user.
				
					EventCode: 5145
AccessList: %%4416
ObjectType: File
ShareName: 
ShareLocalPath: \\?\C:\Windows
RelativeTargetName: __1709834834.6321354
				
			

For more logs and details, we have captured this activity in our platform: Impacket Wmiexec (Powershell) & Impacket Wmiexec
For Detections check out this Collection: Hunting Impacket WMIEXEC

MITRE

T1047: Windows Management Instrumentation
Adversaries may abuse Windows Management Instrumentation (WMI) to execute malicious commands and payloads.

T1048: Exfiltration Over Alternative Protocol
Adversaries may steal data by exfiltrating it over a different protocol than that of the existing command and control channel.

T1059.006: Command and Scripting Interpreter: Python
Adversaries may abuse Python commands and scripts for execution.

T1078.002: Valid Accounts
Adversaries may obtain and abuse credentials of existing accounts as a means of gaining Initial Access, Persistence, Privilege Escalation, or Defense Evasion.

Dcomexec.py

This one is fairly similar to the wmiexec technique. This utility facilitates command execution without requiring SMB server-side components, making it an effective alternative for environments where SMB is restricted or monitored. Here is the basic usage to run a command on a target host.

Dcomexec.py
Depending on the object that is passed in the dcomObject parameter it will use a few different CLSIDs as seen here:
				
					if self.__dcomObject == 'ShellWindows': 
                # ShellWindows CLSID (Windows 7, Windows 10, Windows Server 2012R2) 
                iInterface = w.CoCreateInstanceEx(string_to_bin('9BA05972-F6A8-11CF-A442-00A0C90A8F39'), IID_IDispatch) 
                iMMC = IDispatch(iInterface) 
                resp = iMMC.GetIDsOfNames(('Item',)) 
                resp = iMMC.Invoke(resp[0], 0x409, DISPATCH_METHOD, dispParams, 0, [], []) 
                iItem = IDispatch(self.getInterface(iMMC, resp['pVarResult']['_varUnion']['pdispVal']['abData'])) 
                resp = iItem.GetIDsOfNames(('Document',)) 
                resp = iItem.Invoke(resp[0], 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], []) 
                pQuit = None 
            elif self.__dcomObject == 'ShellBrowserWindow': 
                # ShellBrowserWindow CLSID (Windows 10, Windows Server 2012R2) 
                iInterface = dcom.CoCreateInstanceEx(string_to_bin('C08AFD90-F2A1-11D1-8455-00A0C91F3880'), IID_IDispatch) 
                iMMC = IDispatch(iInterface) 
                resp = iMMC.GetIDsOfNames(('Document',)) 
                resp = iMMC.Invoke(resp[0], 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], []) 
                pQuit = iMMC.GetIDsOfNames(('Quit',))[0] 
            elif self.__dcomObject == 'MMC20': 
                iInterface = dcom.CoCreateInstanceEx(string_to_bin('49B2791A-B1AE-4C90-9B8E-E860BA07F889'), IID_IDispatch) 
                iMMC = IDispatch(iInterface) 
                resp = iMMC.GetIDsOfNames(('Document',)) 
                resp = iMMC.Invoke(resp[0], 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], []) 
                pQuit = iMMC.GetIDsOfNames(('Quit',))[0] 
            else: 
                logging.fatal('Invalid object %s' % self.__dcomObject) 
                return
				
			
This will change which process spawns the commands. Compare the process graphs for the default (ShellWindows) vs MMC20.
ShellWindows
MMC20
As expected, based on the script name, you will see a bunch of DCOM traffic with this technique. This includes the previous one for the RemoteCreateInstance we detected as well.
				
					sourcetype: bro:dce_rpc:json
operation: unknown-6
endpoint: IDispatch
id.resp_p: 53203

sourcetype: bro:dce_rpc:json
operation: unknown-5
endpoint: IDispatch
id.resp_p: 53203

sourcetype: bro:dce_rpc:json
operation: RemoteCreateInstance
endpoint: IRemoteSCMActivator
id.resp_p: 135

sourcetype: bro:dce_rpc:json
operation: DRSUnbind
endpoint: drsuapi
id.resp_p: 49667

sourcetype: bro:dce_rpc:json
operation: DRSCrackNames
endpoint: drsuapi
id.resp_p: 49667

sourcetype: bro:dce_rpc:json
operation: DRSBind
endpoint: drsuapi
id.resp_p: 49667

sourcetype: bro:dce_rpc:json
operation: ept_map
endpoint: epmapper
id.resp_p: 135
				
			
Similar again to wmiexec you will see the command output redirection to a temporary file on the ADMIN$ share. This doesn’t change no matter which object type is used.
				
					EventCode: 1
ParentProcessName: explorer.exe
CommandLine: "C:\Windows\System32\cmd.exe" /Q /c whoami 1\> \\127.0.0.1\ADMIN$\TEMP\__17077 2\>&1
ParentUser: SNAPATTACK\user
				
			

And then finally the requests to that same temporary file.

				
					EventCode: 5145
AccessList: %%1537, %%4423
ObjectType: File
ShareName: \\*\ADMIN$
ShareLocalPath: \??\C:\Windows
RelativeTargetName: TEMP\__17077

EventCode: 5145
AccessList: %%4416
ObjectType: File
ShareName: \\*\ADMIN$
ShareLocalPath: \??\C:\Windows
RelativeTargetName: TEMP\__17077

EventCode: 5145
AccessList: %%1538, %%1541, %%4417, %%4418, %%4420, %%4423, %%4424
ObjectType: File
ShareName: \\*\ADMIN$
ShareLocalPath: \??\C:\Windows
RelativeTargetName: TEMP\__17077

EventCode: 5145
AccessList: %%4417
ObjectType: File
ShareName: \\*\ADMIN$
ShareLocalPath: \??\C:\Windows
RelativeTargetName: TEMP\__17077

				
			

For more logs and details, we have captured this activity in our platform: Impacket DCOMExec (MMC20) & Impacket DCOMExec
For Detections check out this Collection: Hunting Impacket DCOMEXEC

MITRE

T1021.002: Remote Services: SMB/Windows Admin Shares
Adversaries may use valid accounts to interact with a remote network share using Server Message Block (SMB).

T1021.003: Remote Services: Distributed Component Object Model
Adversaries may use valid accounts to interact with remote machines by taking advantage of Distributed Component Object Model (DCOM).

T1059.006: Command and Scripting Interpreter: Python
Adversaries may abuse Python commands and scripts for execution.

T1059: Command and Scripting Interpreter
Adversaries may abuse command and script interpreters to execute commands, scripts, or binaries.

T1078: Valid Accounts
Adversaries may obtain and abuse credentials of existing accounts as a means of gaining Initial Access, Persistence, Privilege Escalation, or Defense Evasion.

Wmipersist.py

Here, we’ll walk through basic usage of wmipersist.py to create a persistent execution of a vbs script. There are a few different methods that can be used to trigger the execution, most commonly a timer or when a seperate process is launched.

Timer Based
Wmipersist.py Timer based
Process Trigger
Wmipersist.py Process Trigger
The process graph for this activity is a bit unique compared to the other techniques.
Similar to the wmiexec script you will see a few DCOM requests.
				
					sourcetype: bro:dce_rpc:json
operation: RemoteCreateInstance
endpoint: IRemoteSCMActivator
named_pipe: 135
id.resp_p: 135

sourcetype: bro:dce_rpc:json
operation: NTLMLogin
endpoint: IWbemLevel1Login
named_pipe: 64017
id.resp_p: 64017

sourcetype: bro:dce_rpc:json
operation: RemRelease
endpoint: IRemUnknown
named_pipe: 64017
id.resp_p: 64017

sourcetype: bro:dce_rpc:json
operation: DeleteClass
endpoint: IWbemServices
named_pipe: 64017
id.resp_p: 64017

sourcetype: bro:dce_rpc:json
operation: unknown-6
endpoint: IWbemCallResult interface
named_pipe: 64017
id.resp_p: 64017
				
			
However, the important thing to look at is the WMI Event Consumers and Filters. This is the core of how this technique achieves persistence and execution. These can be captured with Symon events 19, 20, and 21. These give a ton of good details about the actions that are being taken.
				
					EventCode: 20
EventType: WmiConsumerEvent
Operation: Created
User: BUILTIN\Administrators
Name: "SNAP"
Type: Script
Destination: "CreateObject(wscript.shell).Run(calc.exe)"
				
			
We can see that a WmiConsumerEvent was created with a Script, and we can see what that script was doing. In this case it’s simply executing calc.exe but this could be any action the attacker wants. We can also look at the Filter Event that is created associated with this consumer.
				
					EventCode: 19
EventType: WmiFilterEvent
Operation: Created
User: BUILTIN\Administrators
EventNamespace: "root\subscription"
Name: “EF_SNAP"
Query: "select * from __TimerEvent where TimerID = \TI_SNAP\ "

				
			
WMI filters are queries that are used to sift through the vast amount of data in the WMI repository to target specific information or events. Filters specify criteria that must be met for an event to be considered of interest. A WMI filter is defined using the WMI Query Language (WQL), which is similar to SQL but designed specifically for interacting with the WMI datastore. When an event occurs, WMI evaluates the event against the criteria specified in the filter. If the event matches the criteria, it is passed on to any associated consumers; otherwise, it is ignored. WMI consumers are the entities that receive events filtered by WMI filters. Consumers react to these events by executing predefined actions, such as running scripts, logging information, or altering system configurations. Finally, there is the WmiBindingEvent that ties the filter and consumer together.
				
					EventCode: 21
EventType: WmiBindingEvent
Operation: Created
User: BUILTIN\Administrators
Consumer: "ActiveScriptEventConsumer.Name=\SNAP\"
Filter: "__EventFilter.Name=\EF_SNAP\"
				
			
Another location to look at WMI events are with Windows WMI Event Logs (5859, 5860, 5861). Here you can see the filter and consumer in one place.
				
					EventCode: 5861
Consumer: ActiveScriptEventConsumer="SNAP"
ESS: EF_SNAP
PossibleCause: Binding EventFilter:
                instance of __EventFilter
                {
                CreatorSID = {1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0};
                EventNamespace = "root\subscription";
                Name = "EF_SNAP";
                Query = "select * from __TimerEvent where TimerID = \"TI_SNAP\"";
                QueryLanguage = "WQL";
                };
                Perm. Consumer:
                instance of ActiveScriptEventConsumer
                {
                CreatorSID = {1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0};
                KillTimeout = 0;
                MaximumQueueSize = 0;
                Name = "SNAP";
                ScriptingEngine = "VBScript";
                ScriptText = "CreateObject(\"wscript.shell\").Run(\"calc.exe\")";
                };

				
			
Looking back at the process graph there is a unique Windows built-in process we see launching the calc.exe process. This is scrcons.exe, which is an executable associated with the WMI Scripting Host. The WMI Scripting Host enables scripts (often written in VBScript or PowerShell) to interact with WMI to manage Windows systems, query system information, configure settings, and much more. This is specifically responsible for executing scripts that are part of WMI Event Subscriptions. This is further being executed by the scvhost process under the DcomLaunch service group.
				
					EventCode: 1
Description: WMI Standard Event Consumer - scripting
CommandLine: C:\Windows\system32\wbem\scrcons.exe -Embedding
User: NT AUTHORITY\SYSTEM
ParentCommandLine: C:\Windows\system32\svchost.exe -k DcomLaunch -p

EventCode: 1
Description: Windows Calculator
CommandLine: "C:\Windows\System32\calc.exe"
User: NT AUTHORITY\SYSTEM
ParentCommandLine: C:\Windows\system32\wbem\scrcons.exe -Embedding
				
			

For more logs and details, we have captured this activity in our platform: Impacket WMIPersist
For Detections check out this Collection: Hunting Impacket WMIPERSIST

MITRE

T1021: Remote Services
Adversaries may use valid accounts to log into a service that accepts remote connections, such as telnet, SSH, and VNC.

T1047: Windows Management Instrumentation
Adversaries may abuse Windows Management Instrumentation (WMI) to execute malicious commands and payloads.

T1059.005: Command and Scripting Interpreter: Visual Basic
Adversaries may abuse Visual Basic (VB) for execution.

T1059.006: Command and Scripting Interpreter: Python
Adversaries may abuse Python commands and scripts for execution.

T1078: Valid Accounts
Adversaries may obtain and abuse credentials of existing accounts as a means of gaining Initial Access, Persistence, Privilege Escalation, or Defense Evasion.

T1546.003: Event Triggered Execution: Windows Management Instrumentation Event Subscription
Adversaries may establish persistence and elevate privileges by executing malicious content triggered by a Windows Management Instrumentation (WMI) event subscription.

Conclusion

In summary, Impacket is a widely utilized tool used by a range of malicious actors. It offers various capabilities for executing remote commands on a target system including SMB, DCOM, and WMI. Many of these require legitimate credentials or hashes to work so it isn’t usually an initial infection but rather a method of lateral movement or enumeration. We covered many detection opportunities for these attacks, and you can dig deeper into them at SnapAttack.

SnapAttack is the threat hunting, detection engineering, and detection validation platform for proactive threat-informed defense. Register for a FREE community account to access the tons of content included in this blog post, as well as thousands of other community detections. Subscribers also get advanced features like a no-code detection builder, one-click deployments to leading SIEMs and EDRs like Chronicle, Sentinel, Splunk, CrowdStrike and SentinelOne, advanced threat profiles to prioritize relevant threats, and customized reports that track MITRE ATT&CK coverage and more!

This concludes part two of our blog series on Impacket. Keep an eye out for future content for even more insights.

About SnapAttack: SnapAttack is an innovator in proactive, threat-informed security solutions. The SnapAttack platform helps organizations answer their most pressing question: “Are we protected against the threats that matter?”

By rolling threat intelligence, adversary emulation, detection engineering, threat hunting, and purple teaming into a single, easy-to-use product with a no-code interface, SnapAttack enables companies to get more from their tools and more from their teams so they can finally stay ahead of the threat.