How to make Windows Event Logs to record cmd.exe, powershell.exe and batch file executions with args?
Assistant
Creating detailed logs for command-line activities, such as executions of cmd.exe, powershell.exe, and batch files with their arguments, can greatly enhance your ability to monitor and audit system activities for operational and security purposes. Here’s a comprehensive guide to enabling and configuring Windows Event Logs for such events:
Step 1: Enable Detailed Process Creation Auditing
Windows provides a built-in feature under Group Policy to track detailed process creation events. Here are the steps to enable it:
Open Group Policy Editor:
Press Win + R to open the Run dialog.
Type gpedit.msc and press Enter.
Navigate to the Following Path:
Computer Configuration -> Windows Settings -> Security Settings -> Advanced Audit Policy Configuration -> System Audit Policies -> Detailed Tracking.
Enable Process Creation Auditing:
In the right pane, find and double-click on Audit Process Creation.
Check both Success and Failure options to log both successful and failed process creation attempts.
Click OK to apply the changes.
Enable Command Line Auditing:
Navigate to Computer Configuration -> Administrative Templates -> System -> Audit Process Creation.
Double-click the Include command line in process creation events policy.
Set this policy to Enabled.
Click OK to apply the changes.
Step 2: Check and Edit the Local Security Policy
In case you are doing this on a single machine (not domain joined), you will need to ensure it via Local Security Policy:
Open Local Security Policy:
Press Win + R, type secpol.msc, and press Enter.
Navigate to Advanced Audit Policy Configuration:
Go to Advanced Audit Policy Configuration -> -> .
User
Assistant
User
Write a simple batch file (.bat) to trigger detection script higher
Assistant
To create a batch file that will trigger the aforementioned Python detection script, you can follow these steps:
Ensure Python Installation:
Make sure Python is installed and added to the system PATH so that it can be invoked from the command line.
Save the Python Script:
Save the provided Python script in a file, say .
System Audit Policies
Detailed Tracking
Audit Process Creation:
Ensure Audit Process Creation is enabled for both success and failure.
Step 3: Verify Enabled Logging
Open Event Viewer:
Press Win + R, type eventvwr.msc, and press Enter.
Navigate to Security Logs:
Go to Windows Logs -> Security.
Check for Event IDs:
Look for events with Event ID 4688. These events indicate when a new process has been created, and with the policies enabled, will include the command line used to create the process.
Step 4: Customize Logging for Specific Applications (Optional)
If you want more granular control, you can use Windows Management Instrumentation (WMI) filters or AppLocker. AppLocker can enforce rules for specific executables and log accordingly.
Using WMI for cmd.exe and powershell.exe Triggers
Create a WMI Event Subscription:
You can create a permanent WMI Event Subscription to log when specific applications are executed.
Step 5: Monitor Logs
Implement a strategy to monitor these logs. Using SIEM (Security Information and Event Management) solutions can help you aggregate and analyze these logs centrally.
By following these steps, you’ll configure Windows to log not just the execution of cmd.exe, powershell.exe, and batch files, but also the arguments that are used, which can be crucial for auditing and security monitoring.
Fix a Python script to facilitate detection of potential cyber attacks using "execution" techniques. It works by scanning the Windows Event Logs for specific signs of malicious "execution" activity according to MITRE ATT&CK. The script uses the subprocess module to run PowerShell commands from Python. Events related to PowerShell usage, malicious scripts, cmd.exe interpreter abuse and similar suspicious activities are scanned and detected (using your previous answer). The script finds too many events, there should be fewer of them. Suggest an improved and more accurate version of the script. Avoid errors in Python code. Write only Python code in your answer.
detected_threats = []
for event in events_to_check:
log_name = event['log']
for event_id in event['id']:
command = "Get-WinEvent -FilterHashtable @{" \
+ f"logname='{log_name}'; id={event_id}" \
+ "} | Select-Object TimeCreated, Id, Message | ConvertTo-Json"
output = powershell_command(command)
if output:
try:
events = json.loads(output)
if type(events) is dict:
events = [events]
for event in events:
detected_threats.append({
'Time': event["TimeCreated"],
'EventID': event["Id"],
'Details': event["Message"]
})
except json.JSONDecodeError as e:
print(f"Error decoding JSON!")
return detected_threats
threats_found = scan_event_logs()
if threats_found:
print("Found markers of potential attacks: " + str(len(threats_found)))
write_to_file = open('threats.txt', 'w')
for threat in threats_found:
print(f"Time: {threat['Time']}, Event ID: {threat['EventID']}, Info: {threat['Details']}", file=write_to_file)
else:
print("No events found.")
You can use information below about execution tactic (TA0002) from MITRE ATT&CK website:
T1651 Cloud Administration Command
Adversaries may abuse cloud management services to execute commands within virtual machines. Resources such as AWS Systems Manager, Azure RunCommand, and Runbooks allow users to remotely run scripts in virtual machines by leveraging installed virtual machine agents. [1][2]
If an adversary gains administrative access to a cloud environment, they may be able to abuse cloud management services to execute commands in the environment’s virtual machines. Additionally, an adversary that compromises a service provider or delegated administrator account may similarly be able to leverage a Trusted Relationship to execute commands in connected virtual machines.[3]
Procedure Examples
ID Name Description
S0677 AADInternals
AADInternals can execute commands on Azure virtual machines using the VM agent.[4]
G0016 APT29
APT29 has used Azure Run Command and Azure Admin-on-Behalf-of (AOBO) to execute code on virtual machines.[3]
S1091 Pacu
Pacu can run commands on EC2 instances using AWS Systems Manager Run Command.[5]
Mitigations
ID Mitigation Description
M1026 Privileged Account Management
Limit the number of cloud accounts with permissions to remotely execute commands on virtual machines, and ensure that these are not used for day-to-day operations. In Azure, limit the number of accounts with the roles Azure Virtual Machine Contributer and above, and consider using temporary Just-in-Time (JIT) roles to avoid permanently assigning privileged access to virtual machines.[6]
Detection
ID Data Source Data Component Detects
DS0017 Command Command Execution
Monitor commands and scripts executed on virtual machines. In Azure, usage of Azure RunCommand can be identified via the Azure Activity Logs, and additional details on the result of executed jobs are available in the C:\Packages\Plugins\Microsoft.CPlat.Core.RunCommandWindows directory on Windows virtual machines.[6]
DS0009 Process Process Creation
Monitor virtual machines for the creation of processes associated with cloud virtual machine agents. In Windows-based Azure machines, monitor for the WindowsAzureGuestAgent.exe process.[6]
DS0012 Script Script Execution
Monitor commands and scripts executed on virtual machines. In Azure, usage of Azure RunCommand can be identified via the Azure Activity Logs, and additional details on the result of executed jobs are available in the C:\Packages\Plugins\Microsoft.CPlat.Core.RunCommandWindows directory on Windows virtual machines.[6]
T1059.001 Command and Scripting Interpreter: PowerShell
Adversaries may abuse PowerShell commands and scripts for execution. PowerShell is a powerful interactive command-line interface and scripting environment included in the Windows operating system.[1] Adversaries can use PowerShell to perform a number of actions, including discovery of information and execution of code. Examples include the Start-Process cmdlet which can be used to run an executable and the Invoke-Command cmdlet which runs a command locally or on a remote computer (though administrator permissions are required to use PowerShell to connect to remote systems).
PowerShell may also be used to download and run executables from the Internet, which can be executed from disk or in memory without touching disk.
A number of PowerShell-based offensive testing tools are available, including Empire, PowerSploit, PoshC2, and PSAttack.[2]
PowerShell commands/scripts can also be executed without directly invoking the powershell.exe binary through interfaces to PowerShell's underlying System.Management.Automation assembly DLL exposed through the .NET framework and Windows Common Language Interface (CLI).[3][4][5]
T1059.003 Command and Scripting Interpreter: Windows Command Shell
Adversaries may abuse the Windows command shell for execution. The Windows command shell (cmd) is the primary command prompt on Windows systems. The Windows command prompt can be used to control almost any aspect of a system, with various permission levels required for different subsets of commands. The command prompt can be invoked remotely via Remote Services such as SSH.[1]
Batch files (ex: .bat or .cmd) also provide the shell with a list of sequential commands to run, as well as normal scripting operations such as conditionals and loops. Common uses of batch files include long or repetitive tasks, or the need to run the same set of commands on multiple systems.
Adversaries may leverage cmd to execute various commands and payloads. Common uses include cmd to execute a single command, or abusing cmd interactively with input and output forwarded over a command and control channel.
T1059.005 Command and Scripting Interpreter: Visual Basic
Adversaries may abuse Visual Basic (VB) for execution. VB is a programming language created by Microsoft with interoperability with many Windows technologies such as Component Object Model and the Native API through the Windows API. Although tagged as legacy with no planned future evolutions, VB is integrated and supported in the .NET Framework and cross-platform .NET Core.[1][2]
Derivative languages based on VB have also been created, such as Visual Basic for Applications (VBA) and VBScript. VBA is an event-driven programming language built into Microsoft Office, as well as several third-party applications.[3][4] VBA enables documents to contain macros used to automate the execution of tasks and other functionality on the host. VBScript is a default scripting language on Windows hosts and can also be used in place of JavaScript on HTML Application (HTA) webpages served to Internet Explorer (though most modern browsers do not come with VBScript support).[5]
Adversaries may use VB payloads to execute malicious commands. Common malicious usage includes automating execution of behaviors with VBScript or embedding VBA content into Spearphishing Attachment payloads (which may also involve Mark-of-the-Web Bypass to enable execution).[6]
T1059.006 Command and Scripting Interpreter: Python
Adversaries may abuse Python commands and scripts for execution. Python is a very popular scripting/programming language, with capabilities to perform many functions. Python can be executed interactively from the command-line (via the python.exe interpreter) or via scripts (.py) that can be written and distributed to different systems. Python code can also be compiled into binary executables.[1]
Python comes with many built-in packages to interact with the underlying system, such as file operations and device I/O. Adversaries can use these libraries to download and execute commands or other scripts as well as perform various malicious behaviors.
T1059.007 Command and Scripting Interpreter: JavaScript
Adversaries may abuse various implementations of JavaScript for execution. JavaScript (JS) is a platform-independent scripting language (compiled just-in-time at runtime) commonly associated with scripts in webpages, though JS can be executed in runtime environments outside the browser.[1]
JScript is the Microsoft implementation of the same scripting standard. JScript is interpreted via the Windows Script engine and thus integrated with many components of Windows such as the Component Object Model and Internet Explorer HTML Application (HTA) pages.[2][3][4]
JavaScript for Automation (JXA) is a macOS scripting language based on JavaScript, included as part of Apple’s Open Scripting Architecture (OSA), that was introduced in OSX 10.10. Apple’s OSA provides scripting capabilities to control applications, interface with the operating system, and bridge access into the rest of Apple’s internal APIs. As of OSX 10.10, OSA only supports two languages, JXA and AppleScript. Scripts can be executed via the command line utility osascript, they can be compiled into applications or script files via osacompile, and they can be compiled and executed in memory of other programs by leveraging the OSAKit Framework.[5][6][7][8][9]
Adversaries may abuse various implementations of JavaScript to execute various behaviors. Common uses include hosting malicious scripts on websites as part of a Drive-by Compromise or downloading and executing these script files as secondary payloads. Since these payloads are text-based, it is also very common for adversaries to obfuscate their content as part of Obfuscated Files or Information.
T1053 Scheduled Task/Job
Adversaries may abuse task scheduling functionality to facilitate initial or recurring execution of malicious code. Utilities exist within all major operating systems to schedule programs or scripts to be executed at a specified date and time. A task can also be scheduled on a remote system, provided the proper authentication is met (ex: RPC and file and printer sharing in Windows environments). Scheduling a task on a remote system typically may require being a member of an admin or otherwise privileged group on the remote system.[1]
Adversaries may use task scheduling to execute programs at system startup or on a scheduled basis for persistence. These mechanisms can also be abused to run a process under the context of a specified account (such as one with elevated permissions/privileges). Similar to System Binary Proxy Execution, adversaries have also abused task scheduling to potentially mask one-time execution under a trusted system process.[2]
T1053.005 Scheduled Task/Job: Scheduled Task
Adversaries may abuse the Windows Task Scheduler to perform task scheduling for initial or recurring execution of malicious code. There are multiple ways to access the Task Scheduler in Windows. The schtasks utility can be run directly on the command line, or the Task Scheduler can be opened through the GUI within the Administrator Tools section of the Control Panel. In some cases, adversaries have used a .NET wrapper for the Windows Task Scheduler, and alternatively, adversaries have used the Windows netapi32 library to create a scheduled task.
The deprecated at utility could also be abused by adversaries (ex: At), though at.exe can not access tasks created with schtasks or the Control Panel.
An adversary may use Windows Task Scheduler to execute programs at system startup or on a scheduled basis for persistence. The Windows Task Scheduler can also be abused to conduct remote Execution as part of Lateral Movement and/or to run a process under the context of a specified account (such as SYSTEM). Similar to System Binary Proxy Execution, adversaries have also abused the Windows Task Scheduler to potentially mask one-time execution under signed/trusted system processes.[1]
Adversaries may also create "hidden" scheduled tasks (i.e. Hide Artifacts) that may not be visible to defender tools and manual queries used to enumerate tasks. Specifically, an adversary may hide a task from schtasks /query and the Task Scheduler by deleting the associated Security Descriptor (SD) registry value (where deletion of this value must be completed using SYSTEM permissions).[2][3] Adversaries may also employ alternate methods to hide tasks, such as altering the metadata (e.g., Index value) within associated registry keys.[4]
T1204 User Execution
An adversary may rely upon specific actions by a user in order to gain execution. Users may be subjected to social engineering to get them to execute malicious code by, for example, opening a malicious document file or link. These user actions will typically be observed as follow-on behavior from forms of Phishing.
While User Execution frequently occurs shortly after Initial Access it may occur at other phases of an intrusion, such as when an adversary places a file in a shared directory or on a user's desktop hoping that a user will click on it. This activity may also be seen shortly after Internal Spearphishing.
Adversaries may also deceive users into performing actions such as enabling Remote Access Software, allowing direct control of the system to the adversary; running malicious JavaScript in their browser, allowing adversaries to Steal Web Session Cookies; or downloading and executing malware for User Execution.[1][2]
For example, tech support scams can be facilitated through Phishing, vishing, or various forms of user interaction. Adversaries can use a combination of these methods, such as spoofing and promoting toll-free numbers or call centers that are used to direct victims to malicious websites, to deliver and execute payloads containing malware or Remote Access Software.[3]
T1204.001 User Execution: Malicious Link
An adversary may rely upon a user clicking a malicious link in order to gain execution. Users may be subjected to social engineering to get them to click on a link that will lead to code execution. This user action will typically be observed as follow-on behavior from Spearphishing Link. Clicking on a link may also lead to other execution techniques such as exploitation of a browser or application vulnerability via Exploitation for Client Execution. Links may also lead users to download files that require execution via Malicious File.
T1204.002 User Execution: Malicious File
An adversary may rely upon a user opening a malicious file in order to gain execution. Users may be subjected to social engineering to get them to open a file that will lead to code execution. This user action will typically be observed as follow-on behavior from Spearphishing Attachment. Adversaries may use several types of files that require a user to execute them, including .doc, .pdf, .xls, .rtf, .scr, .exe, .lnk, .pif, and .cpl.
Adversaries may employ various forms of Masquerading and Obfuscated Files or Information to increase the likelihood that a user will open and successfully execute a malicious file. These methods may include using a familiar naming convention and/or password protecting the file and supplying instructions to a user on how to open it.[1]
While Malicious File frequently occurs shortly after Initial Access it may occur at other phases of an intrusion, such as when an adversary places a file in a shared directory or on a user's desktop hoping that a user will click on it. This activity may also be seen shortly after Internal Spearphishing.
To reduce the number of events detected by your script, you can implement filters to target specific events that are more likely to be associated with malicious activity. This can be done by refining the PowerShell command to include filtering criteria such as specific keywords in the message content, specific processes, or user accounts that are more likely to indicate a threat.
Here's an updated version of your script that includes improvements to filter out less relevant events:
python
import subprocess
import json
def powershell_command(command):
process = subprocess.run(["powershell", "-Command", command], capture_output=True, text=True)
return process.stdout
def scan_event_logs():
events_to_check = [
{"log": "Microsoft-Windows-PowerShell/Operational", "id": [400, 4103, 4104]},
{"log": "Security", "id": [4688]},
{"log": "System", "id": [1, 6013]}
]
filtered_threats = []
for event in events_to_check:
log_name = event["log"]
for event_id in event["id"]:
command = (
f"Get-WinEvent -FilterHashtable @{{logname='{log_name}'; id={event_id}}} | "
f"Where-Object {{ $_.Message -match 'powershell|cmd.exe|suspicious_keyword' }} | "
f"Select-Object TimeCreated, Id, Message | ConvertTo-Json"
)
output = powershell_command(command)
if output:
try:
events = json.loads(output)
if isinstance(events, dict):
events = [events]
for event in events:
# Further filter specific keywords or signs in event message if necessary
if any(keyword in event["Message"] for keyword in ["powershell", "cmd.exe", "suspicious_keyword"]):
# Optionally, you could add more filtering logic here
filtered_threats.append({
'Time': event["TimeCreated"],
'EventID': event["Id"],
'Details': event["Message"]
})
except json.JSONDecodeError:
print("Error decoding JSON!")
return filtered_threats
threats_found = scan_event_logs()
if threats_found:
print("Found markers of potential attacks: " + str(len(threats_found)))
with open('threats.txt', 'w') as write_to_file:
for threat in threats_found:
print(f"Time: {threat['Time']}, Event ID: {threat['EventID']}, Info: {threat['Details']}", file=write_to_file)
else:
print("No events found.")
Improvements & Highlights:
Keyword Filtering:
Added a Where-Object clause in the PowerShell command to filter events by specific keywords (powershell, cmd.exe, suspicious_keyword). Adjust these keywords based on what is considered suspicious in your context.
Event Message Filtering:
Further filtering of the event messages for relevance using additional keywords. You can refine and expand the list of keywords as needed.
Exception Handling:
Enhanced error handling to gracefully handle JSON decoding errors.
This script will now only include events that contain specific keywords, greatly reducing the number of events and providing more focused results. Be sure to adjust the suspicious_keyword and the associated filtering logic according to your specific environment and threat landscape.
scan_event_logs.py
Create the Batch File:
Create a batch file, say run_detection.bat, with the following contents:
batch
@echo off
:: Ensure we are in the directory with the Python script
cd /d %~dp0
:: Run the Python script
python scan_event_logs.py
:: Check if threats were found
if exist threats.txt (
echo Potential threats detected. See threats.txt for details.
) else (
echo No events found.
)
pause
How to Create the Batch File:
Open Notepad or any text editor.
Copy and paste the above contents into the editor.
Save the file with a .bat extension, for example, run_detection.bat.
Explanation:
@echo off: This command prevents echoing of each command in the batch file to the console.
cd /d %~dp0: This command ensures the script runs in the directory where the batch file is located.
python scan_event_logs.py: This runs the Python script using Python interpreter (assuming python is in your PATH).
The conditional statements check if the threats.txt file exists and output the appropriate message.
pause: This prevents the command prompt window from closing immediately, allowing you to see the output.
Usage:
Place both the batch file (run_detection.bat) and the Python script (scan_event_logs.py) in the same directory.
Double-click run_detection.bat to execute the batch file, which in turn runs the Python script and handles the output accordingly.
This batch file leverages simple commands to ensure the Python script is executed correctly and provides basic feedback on whether potential threats were detected.