Scheduled Task Tampering

Published by

on

The HAFNIUM threat actor is using an unconventional method to tamper scheduled tasks in order to establish persistence via modification of registry keys in their malware called Tarrask. The benefit of using registry keys is that enables the threat actor to create stealthy scheduled tasks for persistence by avoiding to utilize traditional execution methods. The technique has been identified by the Microsoft Detection and Response Team (DART) in collaboration with the Microsoft Threat Intelligence Center and the details have been disclosed in an article about Tarrask malware.

Even though the Scheduled Task technique (T1053.005) has been abused heavily across multiple threat actors and there are indicators of compromise and detection rules in the public domain, it is also critical to monitor techniques for any developments in order to identify new detection opportunities that will aid towards detection coverage. Chris Au released a proof of concept called GhostTask which implements the technique via a beacon object file and enables threat actors and red teams to use it within a command and control framework. However, the scheduled task tampering technique can be re-created by manually creating the associated registry keys. It should be noted that elevated privileges (SYSTEM) are required to modify or create a scheduled task from the registry.

Utilization of the GhostTask require a scheduled task that exist already in the target system, the arbitrary command or the beacon which is going to be executed, under which user the scheduled task will run and the date and time.

GhostTask.exe localhost add "Microsoft\Windows\Wininet\CacheTask" "cmd.exe" "/c C:\tmp\demon.x64.exe" purple\Chris.Hughes daily 11:00
Scheduled Task Tampering – GhostTask

As it has been displayed above, the following registry keys are modified since these are correlated with the Scheduled Tasks:

HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks

HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree

A system restart is required for the changes in the modified scheduled task to take effect. Alternatively, the schtasks utility can be executed to initiate the task and establish persistence.

shell schtasks /run /tn Microsoft\Windows\Wininet\CacheTask
Scheduled Task Tampering – schtasks

Windows Events

Prior to any detection attempts it is important to ensure that the necessary visibility is in place. The technique relies on the modification of registry keys, therefore registry events should be audited. This should be enabled from the Group Policy:

Group Policy Management Editor --> Advanced Audit Policy Configuration --> Audit Policies --> Object Access --> Audit Registry --> Success
Scheduled Task Tapering – Group Policy

New or modified scheduled tasks are stored in the TaskCache registry key. Therefore this key and any subkeys must be monitored for any changes.

Group Policy Management Editor --> Policies --> Windows Settings --> Registry --> Object Name --> MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache
Scheduled Task Tampering – Registry Object TaskCache
Scheduled Task Tampering – Auditing Registry

Auditing the registry and specifically the key of interest TaskCache will provide log visibility when a registry key is accessed or tampered. These actions are captured under the following Event ID’s:

ActionEvent ID
Registry Value Modification4657
Registry Object Access4663
Scheduled Task Tampering – Windows Event ID’s
Scheduled Task Tampering – Windows Event ID’s

The Event ID 4657 will disclose the scheduled task GUID which has been modified. Utilizing the GUID information to conduct a search in the registry will disclose the associated scheduled task. The Actions registry key stores information in binary blob format. This registry key contains the information of the arbitrary command or beacon.

Scheduled Task Tampering – Windows Event ID Tasks GUID

Furthermore, the Event ID 4663 will also contain information about the registry object accessed (GUID). Both Event ID’s will also disclose information about the process which was used to access the target GUID in the registry. This could provide a detection opportunity since scheduled tasks are running under the svchost process. Of course an attacker can migrate into this process to cover tracks, however this could be an indicator in a less sophisticated level threat actor.

Scheduled Task Tampering – Windows Event ID 4663
Scheduled Task Tampering – Windows Event ID 4657

Microsoft recommendation in the original article is to enable and centralize Scheduled Task logs in order to capture Event ID’s related to scheduled task creation (4698) and modification (4702). However, it is confirmed that these events are only generated when a scheduled task is created or updated from the task scheduler directly and not when registry keys are utilized. Therefore, this could lead to an excessive number of logs especially in corporate domains with high volume of assets and without giving a reliable detection opportunity. It is recommended threat hunting efforts to focus on registry events.

Scheduled Task Tampering – No Scheduled Task Events

The following Sigma rule was developed in order to aid threat hunting of scheduled task tampering by correlating Windows events 4657 and 4663.

title: Detect Scheduled Task Tampering in Registry
id: unique-rule-id
status: experimental
description: >
    Detects tampering with scheduled tasks by monitoring modifications to specific registry paths associated with scheduled tasks. This rule targets on Windows Event ID's 4657 and 4663 which are generated during registry key modifications.
level: high
logsource:
    category: windows
    product: windows
    service: security
detection:
    selection1:
        EventID:
          - 4657  
    selection2:
        EventID:
          - 4663  
    condition: selection1 OR selection2
falsepositives:
    - Legitimate scheduled task modifications
    - System or software updates
tags:
    - attack.persistence
    - attack.t1053  # Scheduled Task/Job

ChainSaw, a tool developed by the company WithSecure in order to quickly identify threats within the Windows Event logs can utilized in order to run this Sigma rule and identify the associated events to scheduled task tampering. It should be noted that a sophisticated threat actor can patch ETW (Event Tracing for Windows) in order to evade the generation of these windows events. However, in that occasion other indicators and artifacts will be present at the implant level.

.\chainsaw.exe hunt C:\Windows\System32\winevt\Logs\Security.evtx -s .\sigma.yml --mapping mappings/sigma-event-logs-all.yml
Scheduled Task Tampering – ChainSaw Windows Events

Elastic

From the perspective of a SIEM, Elastic can identify attempts to tamper scheduled tasks via registry manipulation. When a scheduled task is modified the following events will be generated:

Scheduled Task Tampering – Elastic Events

Examining the process tree of the event, will confirm that the parent process is svchost indicating that the system have been rebooted or the task scheduler service has been re-started and therefore the modification has been loaded into the memory of the process.

Scheduled Task Tampering – Elastic Process Tree

In a similar manner to Windows Event ID 4657 the registry object name will be captured in the event which contains the also the GUID. The GUID, can aid threat hunting activities in order to correlate the task in registry.

Scheduled Task Tampering – Elastic Registry Events

Sysmon

Sysmon has also the ability to capture registry related events. All registry key modifications are logged under Event ID 13. Specifically, Sysmon can enhance the logging visibility since events will contain all the associated registry keys of the arbitrary task such as:

  • Index
  • Id
  • SD
  • Actions
Scheduled Task Tampering – Sysmon Event ID 13
Scheduled Task Tampering – Sysmon Event ID 13 Index
Scheduled Task Tampering – Sysmon Event ID 13 Id
Scheduled Task Tampering – Sysmon Event ID 13 SD
Scheduled Task Tampering – Sysmon Event ID Actions

Sysmon will generate the following events once the task scheduler service is restarted. Any updates in the scheduled tasks will loaded in the memory of svchost process. SOC teams can correlate the timestamps as an indicator of scheduled task tampering since the date and time will be identical.

Scheduled Task Tampering – Sysmon Event ID’s

Sysmon Event ID 1 is correlated with process creation events. However, the tampered scheduled task will be captured on this event ID.

Scheduled Task Tampering – Sysmon Event ID 1

Scheduled Tasks are executed from the svchost process. Once the system is rebooted the new svchost process will run all the scheduled tasks according to the updated configuration. The arbitrary scheduled task action will disclosed in Sysmon Event ID where the parent process is svchost.

Scheduled Task Tampering – Sysmon Event ID 1 svchost Process

The following Events will also generated in Sysmon logs.

Scheduled Task Tampering – Sysmon Event ID 7
Scheduled Task Tampering – Sysmon Event ID 13

Upon system or scheduled task service re-start the following Sysmon Event ID’s will be generated:

ActionEvent ID
Process Creation1
Image Load7
Registry Value Set13
Scheduled Task Tampering – Sysmon Event ID’s

The company WithSecure developed a Sigma rule which can be utilized for threat hunting of scheduled task tampering in conjunction with their tool ChainSaw. The Sigma rule is targeting Sysmon logs in order to hunt for the Event ID 13 which is associated with registry events.

title: Task Tampering Detection
status: experimental
description: Detects manual Scheduled Task tampering via registry modification
author: Riccardo Ancarani
date: 03/05/2022
level: high
logsource:
    product: windows
    service: sysmon
detection:
    selection:
        EventID: 13
        TargetObject: 'HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\*'
    filter:
        - Image|endswith: '\svchost.exe'
    condition: selection and not filter

Execution of the following command will identify Sysmon events related to scheduled task tampering.

chainsaw.exe hunt C:\Windows\System32\winevt\Logs\Microsoft-Windows-Sysmon%40Operational.evtx --mapping C:\tmp\sigma-event-logs-all.yml -s .\sigma.yml
Scheduled Task Tampering – ChainSaw

Registry

Scheduled Tasks which are created via manipulation of registry keys doesn’t appear in the Task Scheduler or when the schtasks /query is executed. Threat actors or Red Teams can hide it by deleting the SD registry key. However, deletion of this key require elevated (SYSTEM) privileges which might lead to other detection opportunities related to privilege escalation. Specifically, Microsoft disclosed that the HAFNIUM threat actor utilized the technique token theft to obtain the required permissions from the lsass.exe process. It should be noted that all of the on-disk artifacts (i.e. associated registry keys and scheduled task XML file) can be deleted without disrupting the task from executing until the svchost process is terminated (system reboot) which will make any threat hunting activities more challenging.

Scheduled Task Tampering – Task Scheduler

Threat hunting should focus in the following registry keys:

HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks

HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree

The registry key Tree contains the names of the existing scheduled tasks. Any differentiation in the registry in comparison with the Task Scheduler is an indicator of an arbitrary scheduled task being created on the system. Registry keys which are associated with the Scheduled Tasks contain the Id which is the UUID value of the task, the Index which specifies the task type (Boot (1), Logon (2), Plain (3), Maintenance (4)) and the SD which is the security descriptor of the task (i.e which users are allowed to see the task).

Scheduled Task Tampering – Registry Tree

The GUID value can be utilized to map task information in the registry key Tasks such as the Trigger, what action is going to be performed upon execution and under the context of which user the task is going to run.

Scheduled Task Tampering – Registry Tasks

The Actions is a registry key of interest since any malicious command or beacon which has been used to establish persistence is stored here for any tampered scheduled tasks.

Scheduled Task Tampering – Registry Actions

Information regarding scheduled tasks is also stored in the following location in the form of an XML file. Similarly, opening the XML of the scheduled task which there are indicators of tampering can aid towards the identification of the arbitrary command.

C:\Windows\System32\Tasks
Scheduled Task Tampering – CacheTask XML File

Threat Hunting Queries

The followings rules and queries can aid defensive security teams towards the identification of this persistence method regardless of their technology stack deployed.

Sigma:

title: Scheduled Task Created - Registry
id: 93ff0ceb-e0ef-4586-8cd8-a6c277d738e3
status: experimental
description: Detects the creation of a scheduled task via Registry keys.
references:
    - https://center-for-threat-informed-defense.github.io/summiting-the-pyramid/analytics/task_scheduling/
    - https://posts.specterops.io/abstracting-scheduled-tasks-3b6451f6a1c5
author: Center for Threat Informed Defense (CTID) Summiting the Pyramid Team
date: 2023/09/27
tags:
    - attack.execution
    - attack.persistence
    - attack.privilege_escalation
    - attack.s0111
    - attack.t1053.005
    - car.2013-08-001
    - detection.threat_hunting
logsource:
    product: windows
    category: registry_event
detection:
    selection:
        TargetObject|contains:
            - '\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks\'
            - '\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree\'
    condition: selection
falsepositives:
    - Likely as this is a normal behaviour on Windows
level: low

Sentinel:

id: 6dd2629c-534b-4275-8201-d7968b4fa77e
name: Scheduled Task Hide
description: |
   'This query detects attempts by malware to hide the scheduled task by deleting the SD (Security Descriptor) value. Removal of SD value results in the scheduled task disappearing from schtasks /query and Task Scheduler.
    The query requires auditing to be turned on for HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree registry hive as well as audit policy for registry auditing to be turned on.
    Reference: https://www.microsoft.com/security/blog/2022/04/12/tarrask-malware-uses-scheduled-tasks-for-defense-evasion/
    Reference: https://4sysops.com/archives/audit-changes-in-the-windows-registry/'
severity: High
requiredDataConnectors:
  - connectorId: SecurityEvents
    dataTypes:
      - SecurityEvent
  - connectorId: WindowsSecurityEvents
    dataTypes:
      - SecurityEvent
queryFrequency: 1d
queryPeriod: 1d
triggerOperator: gt
triggerThreshold: 0
status: Available
tactics:
  - DefenseEvasion
relevantTechniques:
  - T1562
tags:
  - Tarrask
query: |
  SecurityEvent
  | where EventID == 4657
  | extend EventData = parse_xml(EventData).EventData.Data
  | mv-expand bagexpansion=array EventData
  | evaluate bag_unpack(EventData)
  | extend Key = tostring(column_ifexists('@Name', "")), Value = column_ifexists('#text', "")
  | evaluate pivot(Key, any(Value), TimeGenerated, TargetAccount, Computer, EventSourceName, Channel, Task, Level, EventID, Activity, TargetLogonId, SourceComputerId, EventOriginId, Type, _ResourceId, TenantId, SourceSystem, ManagementGroupName, IpAddress, Account)
  | extend ObjectName = column_ifexists('ObjectName', ""), OperationType = column_ifexists('OperationType', ""), ObjectValueName = column_ifexists('ObjectValueName', "")
  | where ObjectName has 'Schedule\\TaskCache\\Tree' and ObjectValueName == "SD" and OperationType == "%%1906"  // %%1906 - Registry value deleted
  | extend timestamp = TimeGenerated, HostCustomEntity = Computer, AccountCustomEntity = Account
entityMappings:
  - entityType: Account
    fieldMappings:
      - identifier: FullName
        columnName: AccountCustomEntity
  - entityType: Host
    fieldMappings:
      - identifier: FullName
        columnName: HostCustomEntity
version: 1.0.0
kind: Scheduled

Elastic:

{{
    "description": "Detects tampering with scheduled tasks by monitoring modifications to specific registry paths associated with scheduled tasks. This rule targets on Windows Event ID's 4657 and 4663 which are generated during registry key modifications.\n",
    "author": [
        ""
    ],
    "enabled": true,
    "false_positives": [
        "Legitimate scheduled task modifications",
        "System or software updates"
    ],
    "filters": [],
    "from": "now-360s",
    "immutable": false,
    "index": [],
    "interval": "5m",
    "rule_id": "unique-rule-id",
    "language": "lucene",
    "output_index": ".siem-signals-default",
    "max_signals": 100,
    "risk_score": 65,
    "name": "Detect Scheduled Task Tampering in Registry",
    "query": "EventID:4657 OR EventID:4663",
    "meta": {
        "from": "1m"
    },
    "severity": "high",
    "tags": [
        "attack.persistence",
        "attack.t1053"
    ],
    "to": "now",
    "type": "query",
    "threat": [
        {
            "tactic": {
                "id": "TA0003",
                "name": "Persistence",
                "reference": "https://attack.mitre.org/tactics/TA0003"
            },
            "framework": "MITRE ATT&CK",
            "technique": [
                {
                    "id": "T1053",
                    "name": "Scheduled Task/Job",
                    "reference": "https://attack.mitre.org/techniques/T1053"
                }
            ]
        }
    ],
    "version": 1,
    "references": [
        "https://thedfirreport.com/2021/03/29/sodinokibi-aka-revil-ransomware/",
        "https://labs.f-secure.com/blog/scheduled-task-tampering/"
    ],
    "license": "DRL 1.1"
}

Elastic Query:

EventID:4657 OR EventID:4663

CrowdStrike:

event_simpleName=ProcessRollup2 AND EventID="4657" OR EventID="4663"

Microsoft Defender:

union * | where EventID == 4657 or EventID == 4663

References

  1. https://www.microsoft.com/en-us/security/blog/2022/04/12/tarrask-malware-uses-scheduled-tasks-for-defense-evasion/
  2. https://pentestlab.blog/2023/11/20/persistence-scheduled-task-tampering/
  3. https://labs.withsecure.com/publications/scheduled-task-tampering
  4. https://github.com/netero1010/GhostTask
  5. https://github.com/WithSecureLabs/chainsaw

Leave a comment

Blog at WordPress.com.