Hunting Impacket: Part 1

Impacket Overview

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.

Featured Protocols

  • Ethernet
  • IP (IPv4 and IPv6), TCP, UDP, ICMP, IGMP, ARP.
  • NMB and SMB1, SMB2 and SMB3
  • MSRPC version 5 over TCP, SMB/TCP, SMB/NetBIOS and HTTP.
  • Plain, NTLM and Kerberos authentications (via various mechanisms)
  • The following MSRPC interfaces: EPM, DTYPES, LSAD, LSAT, NRPC, RRP,
    SAMR, SRVS, WKST, SCMR, BKRP, DHCPM, EVEN6, MGMT, SASEC, TSCH, DCOM,
    WMI, OXABREF, NSPI, OXNSPI.
  • Portions of TDS (MSSQL) and LDAP protocol implementations.

Example Scripts

Impacket contains a collection of “examples” that offer prebuilt scripts utilizing the library. They cover a wide range of functionalities, including network protocol interactions, authentication mechanisms, and more. Each script demonstrates Impacket’s capabilities for specific network protocols or security tasks, such as SMB enumeration, Kerberos authentication, network service manipulation, and remote command execution. Many of these are widely used by malicious actors due to their ease of use and availability.
Impacket Example Scripts
In fact, many malicious actors have been documented using the Impacket tools over the years. Here are just a few articles discussing the use of these tools by legitimate threat actors.
The example scripts can be broken down into a few categories.

Remote Command Execution

The first chunk we want to dive into is using Impacket to execute commands on a remote system. The example scripts that fall under this category are:

psexec.py:

Implements PSEXEC like functionality using RemComSvc. PsExec works by copying a system executable to the remote machine and then instructing the Windows Service Control Manager to run that service. This process allows command execution on the remote machine by creating a named pipe that the service uses to communicate back to the PsExec client, facilitating input and output redirection.

smbexec.py:

A similar approach to PSEXEC without using RemComSvc. This implementation instantiates local smbserver to receive the output of the commands. This is useful in the situation where the target machine does NOT have a writeable share available.

atexec.py:

This example implements methods to run remote code via creating, enumerating, running, and deleting jobs using the task scheduler service.

wmiexec.py:
Uses a similar approach to smbexec but executing commands through WMI. Main advantage here is it runs under the Admin account, not SYSTEM, plus, it doesn’t generate noisy messages in the event log that smbexec.py does when creating a service. Drawback is it needs DCOM.

dcomexec.py:
Similar to wmiexec.py using other DCOM endpoints.

wmipersist.py:

Leverages the Windows Management Instrumentation (WMI) to establish persistence on a compromised Windows machine. It does this by creating a WMI event subscription, which executes a given payload (such as a command or script) when specified system events occur, enabling attackers to maintain access to the system across reboots without needing traditional auto-start methods.

Psexec.py

Psexec has been around for a long time and Impacket’s implementation isn’t that different. Here is the basic usage of the psexec.py script to execute whoami on a remote computer using existing credentials. It does support other authentication methods such as pass-the-hash or kerberos.
Psexec.py
Under the process graph we see the following activity:
Psexec.py
The first thing to note about psexec is that it isn’t very stealthy. Between accessing the ADMIN$ share, creating the service, and accessing specific named pipes for communication there are a lot of detection opportunities.

The first event to look at is Windows Event 5145. This is when a network share object was checked to see whether client can be granted desired access. This event indicates an attempt to access a shared resource, like a file or a named pipe on the network. In psexec’s case this will be the writeable share it finds. Here we can see it attempting to write the service executable to the C:\Windows path using the ADMIN$ share. The Access List here (%%4417) is for WriteData (or AddFile). For a file object, it requests the right to write data to the file. For a directory object, the right to create a file in the directory.

				
					EventCode: 5145
AccessList: %%4417
ObjectType: File
ProcessId: 4
RelativeTargetName: DVPYGeEx.exe
ShareLocalPath: \\?\C:\Windows
ShareName: \\*\ADMIN$
				
			

After the service executable is staged, it will attempt to create the service it uses. WIndows Event 4697 documents when a service is installed on the system. Of interest here is the Client and Parent ProcessId’s being 0. We can also see it points to the service executable written earlier with a manual start (3) and a Service Type of 10, which is a Win32 program that can be started by the Service Controller and that obeys the service control protocol.

				
					EventCode: 4697
ClientProcessId: 0
ParentProcessId: 0
ServiceName: wJdn
ServiceFileName: %systemroot%\DVPYGeEx.exe
ServiceStartType: 3
ServiceAccount: LocalSystem
ServiceType: 10
				
			

You can also see the service installation via Event 7045, which denotes when a remote service is installed on the system.

				
					EventCode: 7045
EventSourceName: "Service Control Manager"
ServiceType: user mode service
StartType: demand start
ImagePath: %systemroot%\DVPYGeEx.exe
				
			
Additionally, you can find logs of the service creation in the registry. There will be a new chunk of registry keys created under HKLM\System\CurrentControlSet\Services, but the primary one to look at is the ImagePath key. This will point to the staged service executable again.
				
					EventCode: 13
EventType: SetValue
ProcessName: services.exe
TargetObject: HKLM\System\CurrentControlSet\Services\wJdn\ImagePath
Details: %%systemroot%%\DVPYGeEx.exe
				
			
Once the service has been executed it will use Windows Server Message Block (SMB) protocol and named pipes for inter-process communication, allowing for command execution with system-level privileges on the remote host. By default, these named pipes will use a naming scheme of RemCom_*, but the script supports renaming these if the attacker desires.
				
					EventCode: 18
EventType: ConnectPipe
ProcessId: 4
PipeName: \RemCom_communicaton
User: NT AUTHORITY\SYSTEM

EventCode: 18
EventType: ConnectPipe
ProcessId: 4
PipeName: \RemCom_stdinCrFu8456
User: NT AUTHORITY\SYSTEM

EventCode: 18
EventType: ConnectPipe
ProcessId: 4
PipeName: \RemCom_stdoutCrFu8456
User: NT AUTHORITY\SYSTEM

EventCode: 18
EventType: ConnectPipe
ProcessId: 4
PipeName: \RemCom_stderrCrFu8456
User: NT AUTHORITY\SYSTEM
				
			
The commands executed by using psexec can be seen in process creation events (Sysmon EventId 1). They will run under the service executable with System level permissions.
				
					EventCode: 1
CommandLine: whoami
ParentImage: C:\Windows\DVPYGeEx.exe
User: NT AUTHORITY\SYSTEM
				
			

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

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).

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.

T1543.003: Create or Modify System Process: Windows Service
Adversaries may create or modify Windows services to repeatedly execute malicious payloads as part of persistence.

T1543: Create or Modify System Process
Adversaries may create or modify system-level processes to repeatedly execute malicious payloads as part of persistence.

T1569.002: System Services: Service Execution
Adversaries may abuse the Windows service control manager to execute malicious commands or payloads.

T1570: Lateral Tool Transfer
Adversaries may transfer tools or other files between systems in a compromised environment.

Smbexec.py

A similar technique to psexec but utilizing a local smbserver to get the output. Here is the basic usage of smbexec to gain a semi-interactive shell on the target system.
SMBEXEC
Again, we can see quite a bit of activity on the process graph.
SMBEXEC
With smbexec you will see a few similarities. Primarily there will be a remote service creation event (7045) and usage of a share. However, there are a few differences. First looking at the service creation. Instead of a staged service executable it uses command prompt with output redirection to a file.
				
					EventCode: 7045
EventSourceName: "Service Control Manager"
ServiceType: user mode service
StartType: demand start
ImagePath: %COMSPEC% /Q /c echo whoami ^> \\%COMPUTERNAME%\C$\__output 2^>^&1 > %SYSTEMROOT%\HziVFHQH.bat & %COMSPEC% /Q /c %SYSTEMROOT%\HziVFHQH.bat & del %SYSTEMROOT%\HziVFHQH.bat
				
			
Again, the registry events are a source of detection for this activity since creating the service will create all the necessary registry keys like the psexec technique. Focusing on the ImagePath key we can see the command that is going to be executed.
				
					EventCode: 13
EventType: SetValue
ProcessName: services.exe
TargetObject: HKLM\System\CurrentControlSet\Services\JwkuauZg\ImagePath
Details: %%COMSPEC%% /Q /c echo whoami ^> \\%%COMPUTERNAME%%\C$\__output 2^>^&1 > %%SYSTEMROOT%%\HziVFHQH.bat & %%COMSPEC%% /Q /c %%SYSTEMROOT%%\HziVFHQH.bat & del %%SYSTEMROOT%%\HziVFHQH.bat
				
			
Here we see the execution of the command redirection to a bat file on the C$ share. Note you will see services.exe spawning the cmd.exe process with System level permissions.
				
					EventCode: 1
ParentProcessName: services.exe
CommandLine: C:\Windows\system32\cmd.exe /Q /c echo whoami ^> \\SLABS-DC\C$\__output 2^>^&1 > C:\Windows\HziVFHQH.bat & C:\Windows\system32\cmd.exe /Q /c C:\Windows\HziVFHQH.bat & del C:\Windows\HziVFHQH.bat
User: NT AUTHORITY\SYSTEM
				
			
This technique will lead to a cmd.exe process spawning under that parent cmd.exe process as seen on the process graph. So, you won’t see the executed command as a direct child of services.exe but you can follow the path all the way up.

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

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).

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.

T1543.003: Create or Modify System Process: Windows Service
Adversaries may create or modify Windows services to repeatedly execute malicious payloads as part of persistence.

T1543: Create or Modify System Process
Adversaries may create or modify system-level processes to repeatedly execute malicious payloads as part of persistence.

T1569.002: System Services: Service Execution
Adversaries may abuse the Windows service control manager to execute malicious commands or payloads.

Atexec.py

Here is a basic example of using atexec.py to execute whoami on a remote system using valid credentials.
ATEXEC
The process graph for this one is much simpler than smbexec. This time the cmd process is spawned under svchost.exe instead of services.exe.
ATEXEC

Since this tool utilizes the task scheduler for its technique the first place to look for detection opportunities is going to be the task being created with Windows Event 4698. Here you will see the command arguments written to a temp file. Note that it is being set to run at the system level context with RunLevel HighestAvailable.

				
					EventCode: 4698
Arguments: /C whoami \> %windir%\Temp\vfIUxfly.tmp 2>&1
Command: cmd.exe
Context: LocalSystem
LogonType: InteractiveToken
RunLevel: HighestAvailable
Principal: LocalSystem
AllowStartOnDemand: TRUE
Enabled: TRUE
Hidden: TRUE
Priority: 7
TaskName: \vfIUxfly
				
			
This technique has a prebuilt xml that it uses to compose the task so identifying tasks with this format could help with hunting this activity.
				
					<?xml version="1.0" encoding="UTF-16"?> 
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"> 
  <Triggers> 
    <CalendarTrigger> 
      <StartBoundary>2015-07-15T20:35:13.2757294</StartBoundary> 
      <Enabled>true</Enabled> 
      <ScheduleByDay> 
        <DaysInterval>1</DaysInterval> 
      </ScheduleByDay> 
    </CalendarTrigger> 
  </Triggers> 
  <Principals> 
    <Principal id="LocalSystem"> 
      <UserId>S-1-5-18</UserId> 
      <RunLevel>HighestAvailable</RunLevel> 
    </Principal> 
  </Principals> 
  <Settings> 
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy> 
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries> 
    <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries> 
    <AllowHardTerminate>true</AllowHardTerminate> 
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> 
    <IdleSettings> 
      <StopOnIdleEnd>true</StopOnIdleEnd> 
      <RestartOnIdle>false</RestartOnIdle> 
    </IdleSettings> 
    <AllowStartOnDemand>true</AllowStartOnDemand> 
    <Enabled>true</Enabled> 
    <Hidden>true</Hidden> 
    <RunOnlyIfIdle>false</RunOnlyIfIdle> 
    <WakeToRun>false</WakeToRun> 
    <ExecutionTimeLimit>P3D</ExecutionTimeLimit> 
    <Priority>7</Priority> 
  </Settings> 
  <Actions Context="LocalSystem"> 
    <Exec> 
      <Command>%s</Command> 
      <Arguments>%s</Arguments> 
    </Exec> 
  </Actions> 
</Task>
				
			
We can then see the activity in a process creation event after the task has been executed. The process will have an interesting parent command line as well since it will be kicked off by svchost process starting the task scheduler under the netsvcs group.
				
					EventCode: 1
CommandLine: cmd.exe /C whoami > C:\Windows\Temp\vfIUxfly.tmp 2>&1
ParentCommandLine: C:\Windows\system32\svchost.exe -k netsvcs -p -s Schedule
User: NT AUTHORITY\SYSTEM
				
			
Since the command does use output redirection to a temporary file we can look at file creation events for these events. It will be a .tmp file with eight characters created under C:\Windows\Temp as the NT AUTHORITY\SYSTEM user.
				
					EventCode: 11
User: NT AUTHORITY\SYSTEM
Image: C:\Windows\system32\cmd.exe
TargetFilename: C:\Windows\Temp\vfIUxfly.tmp
				
			
In addition, there will be a network request to try and access this temporary object via the ADMIN$ share. Looking for these requests to .tmp files is a good indicator of this activity.
				
					EventCode: 5145
AccessList: %%4416
ObjectType: File
ProcessId: 4
RelativeTargetName: Temp\vfIUxfly.tmp
ShareLocalPath: \\?\C:\Windows
ShareName: \\\*\ADMIN\$
				
			
Finally, you will see the deletion of the scheduled task as a cleanup step. It is uncommon for tasks to be deleted randomly so hunting for this activity could clue into suspicious task activity.
				
					EventCode: 4699
TaskName: \vfIUxfly
Name: A scheduled task was deleted
				
			

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

MITRE

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

T1053.002: Scheduled Task/Job: At
Adversaries may abuse the at utility to perform task scheduling for initial or recurring execution of malicious code.

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.

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 one 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.