Traces of Windows remote command execution

Rédigé par Nicolas Biscos - 13/09/2022 - dans CSIRT , Pentest - Téléchargement
A real ninja leaves no traces. However, in the Windows context, a lot of information are disseminated when performing actions and can be leveraged by DFIR analysts.

Focusing on remote command execution techniques used by attackers and red-teamers, this article aims to get a collection of artifacts that can collected by analysts.

Introduction

A typical compromise starts with an attacker obtaining access to a workstation, through phishing for instance. The attacker then tries to spread on other workstations or servers, and execute commands.

There are several ways an attacker can execute commands on a Windows system.

This article aims to:

  • Build a comprehensive list of techniques that are used by pentesters and attackers;
  • Indicate the way these techniques are implemented in different tools;
  • List artifacts that can be collected by DFIR analysts.

Please note that artifacts mentioned in this article are collected from a system with default configuration. It is possible to get more logs by modifying the configuration. In particular, the addition of Sysmon-like event logging allows keeping tracks of file creation and process spawning. On the other hand, setting up an exploitable configuration is a tedious process1.

Moreover, as most lateral movement techniques require administrator privileges, it is legitimate to wonder about the integrity of the artifact left (e.g. unaltered).

PsExec

Historically, there were no “legitimate” ways to natively execute remote commands. SysInternals developed the PsExec utility in order to circumvent this lack of built-in tools.

PsExec was intended for administrators, but was quickly adopted by pentesters and real-life attackers.

How does it work

Original SysInternals PsExec and its derivatives (Impacket, RemCom) work the following way:

  • It requires administrator rights;
  • It uploads an executable file in a share (generally the ADMIN$ shared folder) on the target remote computer. This binary uses a named pipe to wrap stdin, stdout and stderr file descriptors;
  • It creates a service that run as NT AUTHORITY\SYSTEM and runs the previously uploaded executable file;
  • It starts the service and, depending on the implementation, wraps commands entered by the attacker in the previously created named pipe.

Example of execution

There are slight differences between the two implementations hereafter. These differences are explained in the next paragraph.

  • SysInternals PsExec:

    PS X:\> .\PsExec64.exe \\192.168.56.8 whoami
    [...]
    win-k588959mc80\administrator

    With -s (run as SYSTEM) flag:

    PS X:\> .\PsExec64.exe \\192.168.56.8 -s whoami
    [...]
    nt authority\system
  • Impacket psexec.py:

    $ psexec.py Administrator:P@ssw0rd@192.168.56.8 -debug
    Impacket v0.9.22 - Copyright 2020 SecureAuth Corporation
    
    [+] Impacket Library Installation Path: /usr/local/lib/python3.9/dist-packages/impacket
    [+] StringBinding ncacn_np:192.168.56.8[\pipe\svcctl]
    [*] Requesting shares on 192.168.56.8.....
    [*] Found writable share ADMIN$
    [*] Uploading file SBLxhrLb.exe
    [*] Opening SVCManager on 192.168.56.8.....
    [*] Creating service IcsJ on 192.168.56.8.....
    [*] Starting service IcsJ.....
    [!] Press help for extra shell commands
    Microsoft Windows [Version 10.0.14393]
    (c) 2016 Microsoft Corporation. All rights reserved.
    
    C:\Windows\system32>whoami
    nt authority\system
    
    C:\Windows\system32>dir
     Volume in drive C has no label.
     Volume Serial Number is D836-FB0E
    [...]
    C:\Windows\system32[*] Process cmd.exe finished with ErrorCode: 0, ReturnCode: 0
    [*] Opening SVCManager on 192.168.56.8.....
    [*] Stopping service IcsJ.....
    [*] Removing service IcsJ.....
    [*] Removing file SBLxhrLb.exe.....

Artifacts

Several tools implementing PsExec techniques exist and some specific artifacts can be retrieved, even with a default event log policy.

Several artifacts are linked to the operation mode of the attack:

  • The following events are generated at user logon:

    Provider EventID Description Comments
    Security 4624 Logon LogonType == 3 (Network)
    Security 4672 Special Logon User must have SC_MANAGER_CREATE_SERVICE or SC_MANAGER_ALL_ACCESS on SCM (Service Control Manager), which is the case by default for Administrators and SYSTEM accounts2
  • When the service is created, the following event is generated :

    Provider EventID Description Comments
    Service Control Manager 7045 A service was installed in the system. Contains the Service Name, the executable name and account running the service
  • The latest event is generally followed by the following event once the service has started:

    Provider EventID Description Comments
    Service Control Manager 7036 The %1 service entered the %2 state. With %2 values running in this case.
  • Once the attack is completed (shell terminated), the same event with %2 valuing “stopped” is issued. Several other states can be recorded, and are listed in https://docs.microsoft.com/en-us/windows/win32/api/winsvc/ns-winsvc-service_status.

  • Please note that there is no event when the PsExec tool removes the service. However, depending on the closure of the tool, the service and/or the executable may be incorrectly removed. As such, it is interesting to get the list of running processes and their arguments.

  • The USN (Update Sequence Number)3 journal contains entries for the executable that is dropped on the disk. Note that the MFT may not contain tracks of this file because the entry is reallocated

    x:\> DFIR-Orc.exe USNInfo /out=x:\usn.cvs /logfile=x:\usn.log c:\
    
    [...],2022-07-04 13:07:21.907,"SBLxhrLb.exe","\Windows\SBLxhrLb.exe","A............",FILE_CREATE,[...]
    [...],2022-07-04 13:07:21.907,"SBLxhrLb.exe","\Windows\SBLxhrLb.exe","A............",DATA_EXTEND|FILE_CREATE,[...]
    [...]2022-07-04 13:07:21.907,"SBLxhrLb.exe","\Windows\SBLxhrLb.exe","A............",CLOSE|DATA_EXTEND|FILE_CREATE,[...]
    [...]2022-07-04 13:10:14.015,"SBLxhrLb.exe","\Windows\SBLxhrLb.exe","A............",CLOSE|FILE_DELETE,[...]
  • The SysInternals PsExec starts a service that is named PsExeSvc by default4 whereas Impacket’s psexec.py tool spawns a process with a randomly generated 4-characters name. For instance, this is the event ID 7045 content for the execution of the psexec.py command:

    ServiceName IcsJ
      ImagePath %systemroot%\SBLxhrLb.exe
      ServiceType user mode service
      StartType demand start
      AccountName LocalSystem
  • Every SysInternals tools require the user to accept the End-User License Agreement (EULA), and stores the acceptance in value EulaAccepted within the registry key HKCU\Software\Sysinternals\TOOLNAME where TOOLNAME is the name of the executed tool. As a consequence, it may be interesting to seek for this entry on the Windows computer originating the compromise.

  • The binary dropped on the file system depends on the tool used, but it can be changed to anything by the attacker. SysInternals’ PsExec uses its own PSEXESVC.exe binary, whereas Impacket PsExec uses a default-compiled version of RemCom.

  • Tracks of the binary dropped on the file system can also be searched in prefetch if enabled.

  • Whenever Sysmon or affiliated is used, it may be interesting to monitor services spawning subcommands.

  • Every service creates an entry under the registry key HKLM\SYSTEM\CurrentControlSet\Services, which is removed when the service is deleted. However, the HKLM\SYSTEM\CurrentControlSet\Services key timestamp is modified when this entry is removed. If the attack is detected soon enough, the last modification time may be a good indicator. It is also possible to carve the registry offline to recover, under some circumstances, the original key:

    Recover Service Registry
    Registry Explorer allows retrieving deleted Registry keys and values

     

Monitoring enhancement

Monitoring may be enhanced with the following elements:

  • The event ID 4697 (A service was installed in the system) can be generated by Security provider if the following parameter is enabled:

    Computer Configuration
     └ Windows Settings
       └ Security Settings
         └ Advanced Policy Configuration
           └ System
             └ Audit Security System Extenstion
    

    In addition to the elements contained in the event ID 7045, this event contains the account name of the account that created the event and its logon ID.

  • The event ID 5145 (A network share object was checked to see whether client can be granted desired access.) can be generated by activating the Audit Detailed File Share for both successes and failures:

    Computer Configuration
     └ Windows Settings
       └ Security Settings
         └ Advanced Policy Configuration
           └ Object Access
             └ Audit Detailed File Share

    The event ID 5145 is generated every time a file or folder is accessed, and includes detailed information about the permissions or other criteria used to grant or deny access. On a workstation or server (except for file servers and domain controllers), monitoring ADMIN$ and C$ access may help to track down this kind of remote access.

    It is also a good idea to monitor sensitive named pipe access: indeed this event also logs the access to IPC$ and access to svcctl (to start service) and dedicated named pipe for communication:

    • RemCom_communication and RemCom_communication_stdin|stdout|stderr suffixed with a random value for RemCom binary tool embedded with Impacket psexec.py;

    • PSEXESVC suffixed with the name of the target and stdin/stdout/stderr (for instance PSEXESVC-DESKTOP-JN9FUC3-4664-stdout) for SysInternals PsExec tool.

  • Monitoring spawned process named psexec or similar through Sysmon or equivalent may permit to spot such an attack. In particular, services spawning cmd.exe or powershell.exe may be considered suspicious.

Derivates

SMBExec works like PsExec, but instead of dropping a binary executable on the target’s disk, it creates a service per command. This is somehow more noisy than a regular PsExec as it creates a bunch of Service Control Manager events, that contains the command line executed:

Command line
Event ID 7045 shows the full command line executed by the service in the SMBExec case

In the Impacket smbexec.py implementation at least, the command line to be executed is stored in a batch file, execute.bat, that can be found in the USN logs.

The output of the command is stored in a temporary file in the current user temporary directory and copied back to a share exposed by the attacker machine. So there are also tracks of the output file in the USN or MFT.

Windows Management Instrumentation

Windows Management Instrumentation (WMI) is the Microsoft implementation of Web-Based Enterprise Management (WBEM) and Common Information Model (CIM) standards.

It was first released with Windows 2000 and Windows Server 2003.

It provides a set of interfaces that allows an administrator to monitor and control most Windows resources locally or remotely.

How does it work

Although WMI does not provide a remote shell, it is possible to leverage some interfaces to get a pseudo-shell on a remote system.

In particular, WMI contains a Win32_Process class, which represents a process. It is possible to spawn a new process by invoking the Create method of this class.

It requires to be Administrator (or at least having the Execute Method and Remote Enable permissions for the root\cimv2 namespace) in order to remotely spawn commands through this way.

wmiexec.py, provided as an example code for Impacket, implements a pseudo interactive shell by:

  • Instantiating a new process through WMI Win32_Process class. The process simply spawns a shell (cmd.exe by default) that executes a command and redirects stdout and stderr to a file on the file system;
  • Connects through SMB to collect this output file, display it in the attacker console and remove the file.

Example of execution

  • Native wmic Windows command, with SMB connection to retrieve command output:

    C:\> wmic /node:192.168.56.8 process call create 'cmd /c whoami.exe > %TEMP%/out.txt'
    Executing (Win32_Process)->Create()
    Method execution successful.
    Out Parameters:
    instance of __PARAMETERS
    {
            ProcessId = 1688;
            ReturnValue = 0;
    };
    
    C:\> copy \\192.168.56.8\C$\Users\Administrator\AppData\Local\Temp\out.txt .
    C:\> del \\192.168.56.8\C$\Users\Administrator\AppData\Local\Temp\out.txt
    C:\> type .\out.txt
    win-k588959mc80\administrator
  • Impacket wmiexec.py:

    $ wmiexec.py -debug Administrator:P@ssw0rd@192.168.56.8 whoami
    [+] Impacket Library Installation Path: /usr/local/lib/python3.9/dist-packages/impacket
    [*] SMBv3.0 dialect used
    [+] Target system is 192.168.56.8 and isFDQN is False
    [+] StringBinding: \\\\WIN-K588959MC80[\\PIPE\\atsvc]
    [+] StringBinding: WIN-K588959MC80[49666]
    [+] StringBinding: 192.168.56.8[49666]
    [+] StringBinding chosen: ncacn_ip_tcp:192.168.56.8[49666]
    win-k588959mc80\administrator

Artifacts

When leveraging this command execution technique, the following artifacts can be retrieved, even with a default event log policy:

  • The following events are generated at user logon:

    Provider EventID Description Comments
    Security 4624 Logon LogonType == 3 (Network)
    Security 4672 Special Logon User must have admin privileges

Several of these events are generated (DCOM, iWbemLevel1Login and SMB access at least)

  • The following event is also generated :

    Provider EventID Description Comments
    WMI-Activity/Operational 5857 CIMWin32 provider started […] This is event is generated for every WMI activity, so should be correlated with other artifacts

The HostProcess indicates wmiprvse.exe in the current case.

  • Execution leveraging WMI the Impacket way can also be tracked in prefetch (if enabled) by looking for the following processes in a short time frame:

    • CONNHOST.EXE
    • WMIPRVSE.EXE
    • CMD.EXE or POWERSHELL.EXE depending on the shell used
  • Due to the behavior of wmiexec.py, a file is created on the file system (output redirection of command). However, it is immediately deleted once read through the SMBConnection. Due to its small size and immediate deletion, it may not appear in the MFT, but it is logged in the USN logs:

    X:\> .\DFIR-Orc.exe USNInfo /out=x:\usn.csv /logile=x:\usn.log c:\
    [...]
    [...],"\Windows\__1656925531.1376853","A............",FILE_CREATE,[...]
    [...],"\Windows\__1656925531.1376853","A............",CLOSE|FILE_CREATE,[...]
    [...],"\Windows\__1656925531.1376853","A............",CLOSE|FILE_DELETE,[...]
    [...],"\Windows\__1656925531.1376853","A............",FILE_CREATE,[...]
    [...],"\Windows\__1656925531.1376853","A............",DATA_EXTEND|FILE_CREATE,[...]
    [...],"\Windows\__1656925531.1376853","A............",CLOSE|DATA_EXTEND|FILE_CREATE,[...]
    [...],"\Windows\__1656925531.1376853","A............",CLOSE|FILE_DELETE,[...]
    [...],"\Windows\__1656925531.1376853","A............",FILE_CREATE,[...]
    [...],"\Windows\__1656925531.1376853","A............",DATA_EXTEND|FILE_CREATE,[...]
    [...],"\Windows\__1656925531.1376853","A............",CLOSE|DATA_EXTEND|FILE_CREATE,[...]
    [...],"\Windows\__1656925531.1376853","A............",CLOSE|FILE_DELETE,[...]
  • This commit of Impacket introduces the possibility to use PowerShell in wmiexec.py instead of cmd.exe as pseudo interactive shell.

    Using this option creates new events in EventLogs: 600, 400 and 403 in the PowerShell provider. These events correspond to the life cycle of PowerShell:

    Provider EventID Description
    PowerShell 600 Provider “%1” is Started.
    PowerShell 400 Engine state is changed from None to Available.
    PowerShell 403 Engine state is changed from Available to None.

    These events contain the command line in the HostApplication parameter, which gives precious piece of information:

    Engine state is changed from Available to Stopped.
    
    Details:
      NewEngineState=Stopped
      PreviousEngineState=Available
    
      SequenceNumber=15
    
      HostName=ConsoleHost
      HostVersion=5.1.14393.0
      HostId=ed4deb57-4fab-476a-9900-565775109139
      HostApplication=powershell.exe -NoP -NoL -sta -NonI -W Hidden -Exec Bypass -Enc JABQAHIAbwBnAHIAZQBzAHMAUAByAGUAZgBlAHIAZQBuAGMAZQA9ACIAUwBpAGwAZQBuAHQAbAB5AEMAbwBuAHQAaQBuAHUAZQAiADsAdwBoAG8AYQBtAGkA
      EngineVersion=5.1.14393.0
      RunspaceId=28668222-c772-49f8-9318-83869a1fdd6f
      PipelineId=
      CommandName=
      CommandType=
      ScriptName=
      CommandPath=
      CommandLine=

    The base64-decoded string correspond to the following command: $ProgressPreference="SilentlyContinue";whoami

    However, no tracks are left in the PowerShell history file (%APPDATA%\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt) as the tool is terminal-less; this is not a big deal as the command line is logged by the Windows-PowerShell provider.

Monitoring Enhancement

As mentioned in Monitoring Enhancement in PsExec section, the activation of the “Detailed File Share” audit may be used to detect illegitimate connections to C$ and ADMIN$ (used to retrieve the file containing the output of the executed command).

On top of that, monitoring processes spawned by wmiprvse.exe is a good indicator of compromise. This can be implemented by a Sysmon rule for instance (see https://github.com/SwiftOnSecurity/sysmon-config/blob/master/sysmonconfig-export.xml#L88)

DCOM Execution

According to this Microsoft page:

[…] Distributed Component Object Model (DCOM) is a remote protocol that exposes application objects via Remote Procedure Calls (RPCs) and consists of a set of extensions layered on the Microsoft Remote Procedure Call Extensions.

There are a lot of applications that are exposed and provide remote command execution techniques. We can cite MMC20, ShellBrowserWindow, ShellWindows, Excel, and much more.

The processing is well-described in these articles :

The most famous is the MMC (Microsoft Management Console) exec technique, which is implemented in some tools such as CrackMapExec or Impacket dcomexec.py and secretsdump.py.

Example

  • Native Windows call:

    PS C:\> $com = [activator]::CreateInstance([type]::GetTypeFromProgId("MMC20.Application", "192.168.56.8"))
    PS C:\> $com.Document.ActiveView.ExecuteShellCommand("C:\Windows\System32\cmd.exe", $null, "/q ping 192.168.56.1", "7")
Svchost.exe spawning suspicious commands
Process Explorer is showing that svhost.exe is spawning mmc.exe which spawns in turn a cmd.exe process
  • Impacket dcomexec.py:

    $ dcomexec.py -object MMC20 -debug Administrator:P@ssw0rd@192.168.56.8 whoami
    Impacket v0.9.25.dev1+20220503.174139.678981d2 - Copyright 2021 SecureAuth Corporation
    
    [+] Impacket Library Installation Path: /home/nicolas/tools/impacket.new.net/venv_impacket.new.net/lib/python3.9/site-packages/impacket-0.9.25.dev1+20220503.174139.678981d2-py3.9.egg/impacket
    [*] SMBv3.0 dialect used
    [+] Target system is 192.168.56.8 and isFQDN is False
    [+] StringBinding: WIN-K588959MC80[49704]
    [+] StringBinding: 192.168.56.8[49704]
    [+] StringBinding chosen: ncacn_ip_tcp:192.168.56.8[49704]
    win-k588959mc80\administrator

Artifacts

No event ID, except the logon and logoff ones, are logged by default for successful attacks. It is however possible to retrieve some elements:

  • The Impacket dcomexec.py acts as wmiexec.py and uses a temporary file to store the command outputs. As such, the filename 5 is recoverable in the USN logs.
  • Some entries in prefetch may be identified, such as the following for the MMC technique:

    • CONNHOST.EXE
    • MMC.EXE
    • CMD.EXE
  • As for wmiexec.py, this commit of Impacket introduces the possibility to use PowerShell in dcomexec.py instead of cmd.exe as pseudo interactive shell.

    As stated earlier, this option adds new events in EventLogs: 600, 400 and 403 in the PowerShell provider, which contain the PowerShell command line used in the HostApplication parameter.

Monitoring enhancement

A Sysmon-like system can help monitoring DCOM spawning some illegitimate processes. For instance, when using MMC technique, it can be seen that the svchost.exe process is spawning an MMC console, which in turn spawn cmd.exe or powershell.exe.

The svchost container of interest is the one that handle DCOM and is started with the C:\Windows\system32\svchost.exe -k DcomLaunch command line.

WinRM

According to this Microsoft documentation:

Windows Remote Management (WinRM) is one component of the Windows Hardware Management features that manage server hardware locally and remotely.

This provides several components, including Windows Remote Shell (WinRS) which enables remote command execution.

WinRS permits to natively execute remote commands through cmd.exe on the remote host and to retrieve the output. This shell is not interactive. However, it is also possible to get an interactive PowerShell command prompt through this component if PowerShell Remoting (PSRemoting) is enabled (Enable-PSRemoting). Members of built-in groups Administrators, and Remote Management Users since Windows 2012, can use PSRemoting to execute remote commands.

WinRM is activated by default on Microsoft Windows Server editions since 2008 R2 version. It was introduced in Windows 7, but it is not enabled by default on workstations.

It should be noted that both WinRS and PSRemoting can be disabled by typing the command below. Disabling PSRemoting solely through Disable-PSRemoting cmdlet does not disable WinRS.

winrm config winrm/config/winrs '@{AllowRemoteShellAccess="false"}'

Examples

  • Native winrs command:

    PS C:\Users\Administrator\Documents> winrs -r:192.168.56.8 whoami.exe
    win-k588959mc80\administrator
  • Native PowerShell cmdlet:

    PS C:\> $creds = Get-Credential -UserName user
    PS C:\> $s = New-PSSession -ComputerName 192.168.56.8 -Credential $creds
    PS C:\ Enter-PSSession -Session $s
    [192.168.56.8]: PS C:\Users\user\Documents> whoami
    win-k588959mc80\user
    [192.168.56.8]: PS C:\Users\user\Documents> whoami /groups
    
    GROUP INFORMATION
    -----------------
    
    Group Name                             Type             SID          Attributes
    ====================================== ================ ============ ==================================================
    [...]
    BUILTIN\Remote Management Users        Alias            S-1-5-32-580 Mandatory group, Enabled by default, Enabled group
    [...]
    [192.168.56.8]: PS C:\Users\user\Documents> exit
    PS C:\> Remove-PSSession -Session $s
  • evil-winrm 6

    $ ./evil-winrm.rb -i 192.168.56.8 -u user -p P@ssw0rd
    Info: Establishing connection to remote endpoint
    
    *Evil-WinRM* PS C:\Users\Administrator\Documents> whoami
    win-k588959mc80\user

Artifacts

  • With a default logging policy, when PSRemoting is used, solely the start and stop of activity is logged through the following events:

    Provider EventID Description Comments
    PowerShell 400 Engine state is changed from None to Available. HostName is set to ServerRemoteHost
    WinRM/Operational 91 Creating WSMan shell on server with ResourceUri: %1 UTF16LE data correspond to http://schemas.microsoft.com/powershell/Microsoft.PowerShell
  • As WinRM is based on WMI, it is also possible to observe the event 5857 in the Microsoft-Windows-WMI-Activity/Operational provider:

    Provider EventID Description
    WMI/Operational 5857 mgmtprovider provider started with result code 0x0
    WMI/Operational 5857 CIMWin32 provider started with result code 0x0
    WMI/Operational 5857 NetAdapterCim provider started with result code 0x0
    WMI/Operational 5857 nettcpip provider started with result code 0x0
    WMI/Operational 5857 deploymentprovider provider started with result code 0x0
  • It should be noted that commands are not logged by default in any EventID, nor in the PowerShell history file (%APPDATA%\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt) as it is not executed in a console.

  • The presence of WSMPROVHOST.EXE process in prefetch is a good indicator of use of PSRemoting. Indeed, this process acts as a proxy for PowerShell through WinRM.

Monitoring enhancement

  • For PSRemoting, it is possible to activate logging for PowerShell either in:

    Computer Configuration
    └ Administrative Templates
      └ Windows Components
        └ Windows PowerShell
          └ Turn on Module Logging
          └ Turn on Script Block Logging
          └ Turn on PowerShell Transcription
    • Module Logging: generates events ID for modules defined in the policy (see below). If this policy is enabled, pipeline execution events for members of the specified modules are recorded in the Windows PowerShell.
    Provider EventID Description Comments
    PowerShell 800 Pipeline Execution Details Contains the name of the user executing the command in UserId parameter and the command in CommandInvocation parameter
    Microsoft-Windows-PowerShell/Operational 4103 Executing Pipeline Contains the name of the user executing the command in Connected User parameter, the command in Command parameter and the hint ServerRemoteHost in HostName indicating it is PSRemoting
    • Script Block Logging: generates the same events ID than with Module Logging, but for all PowerShell script inputs, as if module name was set to ’*’:
    Log all modules
    Turning on Module Logging in group policy editor
    • PowerShell Transcription: generates file that contains Windows PowerShell commands input and output. By default, the file is located at $env:USERPROFILE\Documents\<DATE>\Powershell_transcript.$env:COMPUTERNAME.<RANDOM>.<DATE>.txt

Task scheduler & AT command exec

Microsoft Windows provides mechanisms to execute scheduled tasks. It is possible to remotely create scheduled tasks through named pipe atsvc or through the TCP named pipe ITaskSchedulerService.

This can be leveraged by an attacker to execute remote commands.

How does it work

The Impacket atexec.py tool creates a new immediate scheduled task with the highest possible privileges (SYSTEM) that executes one command. By default, the command is wrapped in cmd.exe to be able to redirect output of the command to a temporary file. This file is retrieved through an SMB connection, read and destroyed. At the opposite of the other Impacket tools, this tool allows to execute a single command.

The name of the task is built of 8 random characters.

For every scheduled task created, an XML file with the name of the task is created under C:\Windows\System32\Tasks\ and contains the description of the task. The file is automatically removed at the schedule task instantiation.

As many Impacket tool, the standard output of commands are located in a file in C:\Windows\Temp\ directory. The file is named after the task name and with a .tmp extension.

Example of execution

  • Impacket atexec.py :

    $ atexec.py -debug administrator:P@ssw0rd@192.168.56.8 whoami.exe
    Impacket v0.9.22 - Copyright 2020 SecureAuth Corporation
    
    [!] This will work ONLY on Windows >= Vista
    [+] Impacket Library Installation Path: /usr/local/lib/python3.9/dist-packages/impacket
    [*] Creating task \zzbCcjBj
    [*] Running task \zzbCcjBj
    [+] Calling SchRpcGetLastRunInfo for \zzbCcjBj
    [*] Deleting task \zzbCcjBj
    [*] Attempting to read ADMIN$\Temp\zzbCcjBj.tmp
    [*] Attempting to read ADMIN$\Temp\zzbCcjBj.tmp
    nt authority\system
    
    [+] Deleting file ADMIN$\Temp\zzbCcjBj.tmp
  • Native Windows commands:

    PS C:\Users\Administrator> schtasks.exe /s "192.168.56.8" /ru "SYSTEM" /Create /SC ONCE /ST 00:00 /TN "mytask" /TR "c:\windows\system32\cmd.exe /c whoami.exe > c:\windows\temp\test123"
    WARNING: Task may not run because /ST is earlier than current time.
    SUCCESS: The scheduled task "mytask" has successfully been created.
    PS C:\Users\Administrator> schtasks.exe /RUN  /s "192.168.56.8" /TN "mytask"
    SUCCESS: Attempted to run the scheduled task "mytask".
    PS C:\Users\Administrator> type \\192.168.56.8\ADMIN$\temp\test123
    nt authority\system
    PS C:\Users\Administrator> del \\192.168.56.8\ADMIN$\temp\test123
    PS C:\Users\Administrator> schtasks.exe /delete  /s "192.168.56.8" /TN "mytask"  /f
    SUCCESS: The scheduled task "mytask" was successfully deleted.

There are plenty of ways to create scheduled tasks with Microsoft Windows interfaces (PowerShell, WMI, etc.) which are left has an exercise for the reader :)

Artifacts

  • By default, the creation, start and stop of scheduled tasks do not register any event. However, it is possible to identify tracks of creation of new scheduled tasks. Indeed, when a new task is created, an XML file describing the task is dropped in the \Windows\System32\Task directory and is named after the name of the task. This file is immediately destroyed after the task is created, but tracks can be found in USN logs:

    $ grep mJLzCKaK usn.csv
    
    [...],2022-07-20 12:31:47.864,"mJLzCKaK","\Windows\System32\Tasks\mJLzCKaK","A............",FILE_CREATE,[...]
    [...],2022-07-20 12:31:47.864,"mJLzCKaK","\Windows\System32\Tasks\mJLzCKaK","A............",DATA_EXTEND|FILE_CREATE,[...]
    [...],2022-07-20 12:31:47.880,"mJLzCKaK","\Windows\System32\Tasks\mJLzCKaK","A............",CLOSE|DATA_EXTEND|FILE_CREATE,[...]
    [...],2022-07-20 12:31:47.880,"mJLzCKaK","\Windows\System32\Tasks\mJLzCKaK","A............",SECURITY_CHANGE,[...]
    [...],2022-07-20 12:31:47.880,"mJLzCKaK","\Windows\System32\Tasks\mJLzCKaK","A............",CLOSE|SECURITY_CHANGE,[...]
    [...],2022-07-20 12:31:47.897,"mJLzCKaK","\Windows\System32\Tasks\mJLzCKaK","A............",CLOSE|FILE_DELETE,[...]
  • Impacket atexec.py creates a temporary file containing the output of the command executed in \Window\Temp and which is named after the task name and use a .tmp extension. This file can also be found in USN logs:

    $ grep mJLzCKaK.tmp usn.csv
    [...],2022-07-20 12:31:47.897,"mJLzCKaK.tmp","\Windows\Temp\mJLzCKaK.tmp","A............",FILE_CREATE,[...]
    [...],2022-07-20 12:31:47.912,"mJLzCKaK.tmp","\Windows\Temp\mJLzCKaK.tmp","A............",DATA_EXTEND|FILE_CREATE,[...]
    [...],2022-07-20 12:31:47.912,"mJLzCKaK.tmp","\Windows\Temp\mJLzCKaK.tmp","A............",CLOSE|DATA_EXTEND|FILE_CREATE,[...]
    [...],2022-07-20 12:31:50.912,"mJLzCKaK.tmp","\Windows\Temp\mJLzCKaK.tmp","A............",CLOSE|FILE_DELETE,[...]

Monitoring enhancement

Monitoring can be improved by activating the Audit Other Object Access Events in

Computer Configuration
└ Windows Settings
  └ Security Settings
    └ Advanced Audit Policy Configuration
      └ System Audit Policy
        └ Object Access

This will make the Security provider generates these relevant events:

Provider EventID Description Comments
Security 4698 A scheduled task was created contain the XML describing the task, which can be used to identify malicious payload in the TaskInformation field
Security 4699 A scheduled task was deleted  

Please note that no Prefetch seems to be generated for the binary spawned by a scheduled task.

Conclusion

As we saw, every command execution techniques leaves some traces, but some of them are really tenuous. However, event logs can be enriched with some useful information with an enhanced policy and with some fine-grained process logging, such as provided by Sysmon.

We did not cover the RDP case, which is one of the techniques often used by the attackers to access the file system and to execute commands on the underlying operating system. This subject may be covered in a future article.

Please note that SSH for Windows provides a new area for command execution. This was introduced recently and is deactivated by default.


  1. Some configurations are freely available on the Internet and can be used as based to adjust to one’s need. For instance, https://github.com/SwiftOnSecurity/sysmon-config can be used.↩︎

  2. The SDDL of the SCM can be obtained from command line sc.exe sdshow manager and set with sc.exe sdset manager SDDL_STRING. This SDDL specifies extended rights that are explained in https://docs.microsoft.com/fr-fr/windows/win32/services/service-security-and-access-rights. This SDDL is stored in the registry value Security of the registry key HKLM\System\CurrentControlSet\Control\ServiceGroupOrder\Security\Security↩︎

  3. USN Journal maintains a record of changes made to a NTFS volume↩︎

  4. it can be changed using the -r flag.↩︎

  5. C:\Windows\__TIMESTAMP↩︎

  6. https://github.com/Hackplayers/evil-winrm↩︎