Please continue your answer:

Write simple Python script that can look through Windows system logs and detect signs of cyberattacks using the MITRE execution technique.

Avoid mistakes in Python code and use the information from the text below:

Execution The adversary is trying to run malicious code.

Execution consists of techniques that result in adversary-controlled code running on a local or remote system. Techniques that run malicious code are often paired with techniques from all other tactics to achieve broader goals, like exploring a network or stealing data. For example, an adversary might use a remote access tool to run a PowerShell script that does Remote System Discovery.

ID: TA0002 Created: 17 October 2018 Last Modified: 19 July 2019 Version Permalink Techniques Techniques: 14 ID Name Description 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. T1059 Command and Scripting Interpreter Adversaries may abuse command and script interpreters to execute commands, scripts, or binaries. These interfaces and languages provide ways of interacting with computer systems and are a common feature across many different platforms. Most systems come with some built-in command-line interface and scripting capabilities, for example, macOS and Linux distributions include some flavor of Unix Shell while Windows installations include the Windows Command Shell and PowerShell. .001 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. 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). .002 AppleScript Adversaries may abuse AppleScript for execution. AppleScript is a macOS scripting language designed to control applications and parts of the OS via inter-application messages called AppleEvents. These AppleEvent messages can be sent independently or easily scripted with AppleScript. These events can locate open windows, send keystrokes, and interact with almost any open application locally or remotely. .003 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. .004 Unix Shell Adversaries may abuse Unix shell commands and scripts for execution. Unix shells are the primary command prompt on Linux and macOS systems, though many variations of the Unix shell exist (e.g. sh, bash, zsh, etc.) depending on the specific OS or distribution. Unix shells can control every aspect of a system, with certain commands requiring elevated privileges. .005 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. .006 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. .007 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. .008 Network Device CLI Adversaries may abuse scripting or built-in command line interpreters (CLI) on network devices to execute malicious command and payloads. The CLI is the primary means through which users and administrators interact with the device in order to view system information, modify device operations, or perform diagnostic and administrative functions. CLIs typically contain various permission levels required for different commands. .009 Cloud API Adversaries may abuse cloud APIs to execute malicious commands. APIs available in cloud environments provide various functionalities and are a feature-rich method for programmatic access to nearly all aspects of a tenant. These APIs may be utilized through various methods such as command line interpreters (CLIs), in-browser Cloud Shells, PowerShell modules like Azure for PowerShell, or software developer kits (SDKs) available for languages such as Python. .010 AutoHotKey & AutoIT Adversaries may execute commands and perform malicious tasks using AutoIT and AutoHotKey automation scripts. AutoIT and AutoHotkey (AHK) are scripting languages that enable users to automate Windows tasks. These automation scripts can be used to perform a wide variety of actions, such as clicking on buttons, entering text, and opening and closing programs. T1609 Container Administration Command Adversaries may abuse a container administration service to execute commands within a container. A container administration service such as the Docker daemon, the Kubernetes API server, or the kubelet may allow remote management of containers within an environment. T1610 Deploy Container Adversaries may deploy a container into an environment to facilitate execution or evade defenses. In some cases, adversaries may deploy a new container to execute processes associated with a particular image or deployment, such as processes that execute or download malware. In others, an adversary may deploy a new container configured without network rules, user limitations, etc. to bypass existing defenses within the environment. In Kubernetes environments, an adversary may attempt to deploy a privileged or vulnerable container into a specific node in order to Escape to Host and access other containers running on the node. T1203 Exploitation for Client Execution Adversaries may exploit software vulnerabilities in client applications to execute code. Vulnerabilities can exist in software due to unsecure coding practices that can lead to unanticipated behavior. Adversaries can take advantage of certain vulnerabilities through targeted exploitation for the purpose of arbitrary code execution. Oftentimes the most valuable exploits to an offensive toolkit are those that can be used to obtain code execution on a remote system because they can be used to gain access to that system. Users will expect to see files related to the applications they commonly used to do work, so they are a useful target for exploit research and development because of their high utility. T1559 Inter-Process Communication Adversaries may abuse inter-process communication (IPC) mechanisms for local code or command execution. IPC is typically used by processes to share data, communicate with each other, or synchronize execution. IPC is also commonly used to avoid situations such as deadlocks, which occurs when processes are stuck in a cyclic waiting pattern. .001 Component Object Model Adversaries may use the Windows Component Object Model (COM) for local code execution. COM is an inter-process communication (IPC) component of the native Windows application programming interface (API) that enables interaction between software objects, or executable code that implements one or more interfaces. Through COM, a client object can call methods of server objects, which are typically binary Dynamic Link Libraries (DLL) or executables (EXE). Remote COM execution is facilitated by Remote Services such as Distributed Component Object Model (DCOM). .002 Dynamic Data Exchange Adversaries may use Windows Dynamic Data Exchange (DDE) to execute arbitrary commands. DDE is a client-server protocol for one-time and/or continuous inter-process communication (IPC) between applications. Once a link is established, applications can autonomously exchange transactions consisting of strings, warm data links (notifications when a data item changes), hot data links (duplications of changes to a data item), and requests for command execution. .003 XPC Services Adversaries can provide malicious content to an XPC service daemon for local code execution. macOS uses XPC services for basic inter-process communication between various processes, such as between the XPC Service daemon and third-party application privileged helper tools. Applications can send messages to the XPC Service daemon, which runs as root, using the low-level XPC Service C API or the high level NSXPCConnection API in order to handle tasks that require elevated privileges (such as network connections). Applications are responsible for providing the protocol definition which serves as a blueprint of the XPC services. Developers typically use XPC Services to provide applications stability and privilege separation between the application client and the daemon. T1106 Native API Adversaries may interact with the native OS application programming interface (API) to execute behaviors. Native APIs provide a controlled means of calling low-level OS services within the kernel, such as those involving hardware/devices, memory, and processes. These native APIs are leveraged by the OS during system boot (when other system components are not yet initialized) as well as carrying out tasks and requests during routine operations. 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. .002 At Adversaries may abuse the at utility to perform task scheduling for initial or recurring execution of malicious code. The at utility exists as an executable within Windows, Linux, and macOS for scheduling tasks at a specified time and date. Although deprecated in favor of Scheduled Task’s schtasks in Windows environments, using at requires that the Task Scheduler service be running, and the user to be logged on as a member of the local Administrators group. .003 Cron Adversaries may abuse the cron utility to perform task scheduling for initial or recurring execution of malicious code. The cron utility is a time-based job scheduler for Unix-like operating systems. The crontab file contains the schedule of cron entries to be run and the specified times for execution. Any crontab files are stored in operating system-specific file paths. .005 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. .006 Systemd Timers Adversaries may abuse systemd timers to perform task scheduling for initial or recurring execution of malicious code. Systemd timers are unit files with file extension .timer that control services. Timers can be set to run on a calendar event or after a time span relative to a starting point. They can be used as an alternative to Cron in Linux environments. Systemd timers may be activated remotely via the systemctl command line utility, which operates over SSH. .007 Container Orchestration Job Adversaries may abuse task scheduling functionality provided by container orchestration tools such as Kubernetes to schedule deployment of containers configured to execute malicious code. Container orchestration jobs run these automated tasks at a specific date and time, similar to cron jobs on a Linux system. Deployments of this type can also be configured to maintain a quantity of containers over time, automating the process of maintaining persistence within a cluster. T1648 Serverless Execution Adversaries may abuse serverless computing, integration, and automation services to execute arbitrary code in cloud environments. Many cloud providers offer a variety of serverless resources, including compute engines, application integration services, and web servers. T1129 Shared Modules Adversaries may execute malicious payloads via loading shared modules. Shared modules are executable files that are loaded into processes to provide access to reusable code, such as specific custom functions or invoking OS API functions (i.e., Native API). T1072 Software Deployment Tools Adversaries may gain access to and use centralized software suites installed within an enterprise to execute commands and move laterally through the network. Configuration management and software deployment applications may be used in an enterprise network or cloud environment for routine administration purposes. These systems may also be integrated into CI/CD pipelines. Examples of such solutions include: SCCM, HBSS, Altiris, AWS Systems Manager, Microsoft Intune, Azure Arc, and GCP Deployment Manager. T1569 System Services Adversaries may abuse system services or daemons to execute commands or programs. Adversaries can execute malicious content by interacting with or creating services either locally or remotely. Many services are set to run at boot, which can aid in achieving persistence (Create or Modify System Process), but adversaries can also abuse services for one-time or temporary execution. .001 Launchctl Adversaries may abuse launchctl to execute commands or programs. Launchctl interfaces with launchd, the service management framework for macOS. Launchctl supports taking subcommands on the command-line, interactively, or even redirected from standard input. .002 Service Execution Adversaries may abuse the Windows service control manager to execute malicious commands or payloads. The Windows service control manager (services.exe) is an interface to manage and manipulate services. The service control manager is accessible to users via GUI components as well as system utilities such as sc.exe and Net. 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. .001 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. .002 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. .003 Malicious Image Adversaries may rely on a user running a malicious image to facilitate execution. Amazon Web Services (AWS) Amazon Machine Images (AMIs), Google Cloud Platform (GCP) Images, and Azure Images as well as popular container runtimes such as Docker can be backdoored. Backdoored images may be uploaded to a public repository via Upload Malware, and users may then download and deploy an instance or container from the image without realizing the image is malicious, thus bypassing techniques that specifically achieve Initial Access. This can lead to the execution of malicious code, such as code that executes cryptocurrency mining, in the instance or container. T1047 Windows Management Instrumentation Adversaries may abuse Windows Management Instrumentation (WMI) to execute malicious commands and payloads. WMI is designed for programmers and is the infrastructure for management data and operations on Windows systems. WMI is an administration feature that provides a uniform environment to access Windows system components.

The main tool for working with text logs is the Get-Content cmdlet, designed to display the contents of a text file. For example, to display the WSUS service log to the console, you can use the command:


Get-Content -Path ‘C:\Program Files\Update Services\LogFiles\SoftwareDistribution.log’ | Out-Host-Paging

To display the last lines of the log, there is a Tail parameter, which is paired with the parameter. Wait allows you to watch the magazine online. Let’s see how one system is updated:


>Get-Content -Path “C:\Windows\WindowsUpdate.log” -Tail 5 -Wait


Let’s look at the progress of Windows updates.


If we need to catch events in the settings logs, then the Select-String command will help, which allows you to display only strings that match the mask definition. Let’s look at the latest Windows Firewall blocks:


Select-String -Path “C:\Windows\System32\LogFiles\Firewall\pfirewall.log” -pattern ‘Drop’ | Select-Object-Last 20 | Format-table string


Let’s see who will try to climb onto our grandfather.


If you want to view the log lines before and after, you must use the Context parameter. For example, to print three lines after and three lines before the loss, you can use the command:


Select-String ‘C:\Windows\Cluster\Reports\Cluster.log’ -Pattern ‘err’ ‑Context 3

Both cmdlet products can be assumed. For example, to output lines 45 to 75 from netlogon.log, the following command will help:


Get-Content ‘C:\Windows\debug\netlogon.log’ | Select-Object-First 30-Skip 45

System logs are maintained in .evtx format and to work with existing international cmdlets. To work with classic logs (“Application”, “System”, etc.) Get-Eventlog is used. This cmdlet is useful, but it doesn’t allow you to work with application and service contact logs. To work with any logs, including classic ones, there is a more universal option - Get-WinEvent. Let’s look at it in more detail.


To get a list of available system logs, you can restore the following command:


Get-WinEvent -ListLog *


Displays available logs and information about them.


To view a specific journal, you just need to add its name. For example, we get the last 20 entries from the system command log:


Get-WinEvent -LogName “System” -MaxEvents 20


Latest entries in the System log.


To obtain certain events, all you need to do is use hash tables. You can read more about working with hash tables in PowerShell in the Technet material about_Hash_Tables.


For example, all events from the system log with event code 1 and 6013 are displayed.


Get-WinEvent -FilterHashTable @{LogName=‘System’;ID=‘1’,‘6013’}

If you need to receive events of a certain type - a relation or an error - you need to use a filter by importance (Level). Possible values:


0 ― always record;
1 - extreme;
2 - error;
3 - warning;
4 - information;
5 ― detailed (Verbose).

It’s not so easy to assemble a hash table with several importance values for one pair. If we want to get an error and refer to the system log, we can use additional filtering using Where-Object:


Get-WinEvent -FilterHashtable @{LogName=‘system’} | Where-Object -FilterScript {(_.Level -eq 2) -or (_.Level -eq 3)}


System log bugs and reviews.


In a similar way, you can collect a table, filtering directly by the text of events and by time.


You can read more about the operation of both cmdlets for working with system logs in the PowerShell documentation:


Get-EventLog.
Get-WinEvent.

PowerShell is a convenient and flexible mechanism, but it requires knowledge of the syntax and for complex conditions and processing a large number of files that require writing full-fledged scripts. But there is an option to use just SQL queries using the wonderful Log Parser.
Given the preparatory information on how to manipulate and read system logs with PowerShell and the MITRE execution technique detailing how adversaries might attempt to run malicious code on a system, the following Python script can be devised. This script aims to facilitate the detection of potential cyberattacks by scanning the Windows event log for specific signs of malicious activity as defined in the execution technique descriptions.

However, remember that detailed incident response and threat hunting typically require comprehensive analysis and context that simple scripts may not fully provide. Always use such tools as part of a broader security framework and strategy.

### Python Script: Detect Possible Cyberattacks in Windows System Logs

This Python script leverages the subprocess module to run PowerShell commands from Python. It scans for events related to PowerShell use, command-line interpreter abuse, and other suspicious activities outlined under the MITRE Execution technique.

import subprocess
import json

def run_powershell_command(command):
    “”“
    Execute a PowerShell command from Python and return the output
    “””
    process = subprocess.run([“powershell”, “-Command”, command], capture_output=True, text=True)
    return process.stdout

def scan_event_logs():
    “”“
    Scan Windows event logs for indications of cyberattacks based on specific patterns
    “””
    # List of event IDs and logs to check based on MITRE Execution techniques
    events_to_check = [
        {“log”: “Microsoft-Windows-PowerShell/Operational”, “id”: [400, 4103, 4104]},  # PowerShell script block logging, etc.
        {“log”: “Security”, “id”: [4688]},  # Process Creation including cmd, PowerShell.exe
        {“log”: “System”, “id”: [1, 6013]},  # System start-up events (for context)
    ]
    
    detected_threats = []

    for event in events_to_check:
        log_name = event[“log”]
        for event_id in event[“id”]:
            # Construct PowerShell command to fetch relevant event logs
            command = f"Get-WinEvent -FilterHashtable @{logname=‘{log_name}’; id={event_id}} | Select-Object TimeCreated, Id, Message | ConvertTo-Json"
            output = run_powershell_command(command)
            if output:
                try:
                    events = json.loads(output)
                    if type(events) is dict:  # If only one event is found, it will be a dict, not a list
                        events = [events]
                    for event <- You stopped here