Post

Windows Persistence: Run Keys, Services, Scheduled Tasks and WMI

How common Windows persistence mechanisms work internally: Registry Run keys, Startup folders, services, scheduled tasks and permanent WMI event subscriptions. Execution context, artifacts, telemetry, investigation and hardening from a blue-team perspective.

Windows Persistence: Run Keys, Services, Scheduled Tasks and WMI

Introduction

Persistence is the ability to regain execution after a reboot, logoff, process termination or interruption of the original access path. On Windows, many persistence mechanisms are not exploits: they are legitimate operating system facilities designed to start applications, background services, maintenance jobs and event-driven automation.

That dual use changes the defender’s problem. The existence of a Run value, a service or a scheduled task is weak evidence by itself. Investigation must answer four questions:

  1. Trigger: what event causes execution?
  2. Principal: which access token will the code receive?
  3. Action: what executable, script, COM object or command is invoked?
  4. Provenance: who created or changed the persistence object, and was that change expected?
flowchart LR
    C[Configuration artifact] --> T[Trigger]
    T --> B[Windows broker]
    B --> P[Configured principal<br/>and access token]
    B --> A[Action or payload]
    P --> E[Persistent execution]
    A --> E

    C1[Run key or Startup entry] --> T1[Interactive logon]
    C2[Service] --> T2[Boot, demand or service trigger]
    C3[Scheduled task] --> T3[Time, logon, boot or event]
    C4[WMI subscription] --> T4[WQL event match]

Figure 1 — The common persistence model. A stored configuration binds a trigger to an action and a security context; the broker differs for each mechanism.

The techniques in this article map to MITRE ATT&CK T1547.001 (Registry Run Keys / Startup Folder), T1543.003 (Windows Service), T1053.005 (Scheduled Task) and T1546.003 (WMI Event Subscription).1234 They cover only a small part of Windows persistence. COM hijacking, Winlogon extensions, authentication packages, DLL search-order abuse and drivers have different trust boundaries; the COM article examines one of those families.

Persistence is not automatically privilege escalation. A mechanism may preserve only the attacker’s existing user context. It becomes a privilege transition only when the resulting action runs under a more powerful principal or crosses another security boundary.

A comparison before the details

Mechanism Typical trigger Default or configured context Common privilege requirement to create
HKCU Run / RunOnce That user logs on Logged-on user User can normally change their own key
HKLM Run / RunOnce A user logs on The user who logs on, not SYSTEM Normally administrative write access
Per-user Startup folder That user logs on Logged-on user User can normally write their own folder
Common Startup folder Any user logs on The user who logs on, not SYSTEM Normally administrative write access
Windows service Boot, demand or service trigger Configured service account Normally administrator or delegated SCM access
Scheduled task Time, boot, logon, event or manual Configured task principal Depends on target principal, logon type and task ACL
Permanent WMI subscription WQL event becomes true WMI consumer context; sensitive consumers are privileged Local administrative authority for security-sensitive permanent consumers

The Windows identity article explains why the principal matters: the effective access token, not the name of the persistence mechanism, determines what the resulting process may do.

Registry Run keys

Mechanics

Windows supports four primary Run and RunOnce locations:5

1
2
3
4
HKCU\Software\Microsoft\Windows\CurrentVersion\Run
HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce
HKLM\Software\Microsoft\Windows\CurrentVersion\Run
HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce

Each value name is a label and its data is a command line. Run entries are considered at every applicable user logon. RunOnce entries are intended for one-time setup work and are normally deleted before execution. Execution order between multiple values is not guaranteed, and Windows may delay their launch to avoid competing with the foreground logon experience. HKLM\...\RunOnce has additional semantics: it runs when a member of Administrators logs on after a reboot.5

sequenceDiagram
    participant W as Writer process
    participant R as Registry
    participant L as Windows logon infrastructure
    participant U as User session

    W->>R: Create or modify Run value
    Note over R: value name = label<br/>value data = command line
    U->>L: Interactive logon
    L->>R: Enumerate applicable HKCU and HKLM entries
    L->>U: Start command in logged-on user's context
    Note over U: HKLM changes scope,<br/>not the execution token

Figure 2 — Run keys persist a command until logon. Machine scope does not mean LocalSystem execution: the command normally inherits the logging-on user’s security context.

On 64-bit systems, defenders must also account for registry-view differences and Wow6432Node locations used by 32-bit software. The registry value may point directly to an executable, but it may also invoke a script host, DLL loader or signed system binary. Detection should resolve environment variables, quotes and arguments before evaluating the destination.

Read-only triage

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$runKeys = @(
    'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run',
    'HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce',
    'HKLM:\Software\Microsoft\Windows\CurrentVersion\Run',
    'HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce',
    'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Run',
    'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\RunOnce'
)

foreach ($key in $runKeys) {
    if (Test-Path $key) {
        Get-ItemProperty -LiteralPath $key |
            Select-Object @{n='Key';e={$key}}, *
    }
}

The interesting questions are not just what is the value name? but:

  • Is the target signed, expected and present on comparable systems?
  • Is it located in a user-writable or temporary directory?
  • Was the value created shortly after a download, document execution or script-engine process?
  • Does the command contain unusual interpreters, encoded content, remote paths or broken quoting?
  • Does the target exist, or is the orphaned entry evidence of incomplete cleanup?

Startup folders

Startup folders implement the same logon-trigger idea with filesystem objects instead of registry values. The standard paths are represented by known-folder IDs rather than being safely hard-coded:6

Scope Known folder Default path
Per user FOLDERID_Startup %APPDATA%\Microsoft\Windows\Start Menu\Programs\StartUp
All users FOLDERID_CommonStartup %ProgramData%\Microsoft\Windows\Start Menu\Programs\StartUp

Entries may be executables, scripts or shortcuts. A shortcut is especially important during triage: its visible name may look normal while its target, arguments, working directory or icon points elsewhere.

flowchart LR
    W[File or shortcut written] --> S{Startup scope}
    S -->|Per user| U[User Startup folder]
    S -->|Common| C[Common Startup folder]
    U --> L[That user logs on]
    C --> L2[Any user logs on]
    L --> X[Shell processes startup entry<br/>as logged-on user]
    L2 --> X

Figure 3 — The common Startup folder broadens which logons trigger an entry, but each launch still runs in the corresponding interactive user’s context.

Resolve the folders through the shell abstraction, then inspect metadata and shortcut destinations:

1
2
3
4
5
$startup = [Environment]::GetFolderPath('Startup')
$commonStartup = [Environment]::GetFolderPath('CommonStartup')

Get-ChildItem -LiteralPath $startup, $commonStartup -Force |
    Select-Object FullName, Length, CreationTimeUtc, LastWriteTimeUtc

Sysinternals Autoruns combines these entries with many other autostart locations and can verify signatures and calculate hashes. Hiding signed Microsoft entries is useful for triage, but it is a view filter—not proof that every remaining item is malicious or every hidden item is safe.7

Windows services

Configuration and execution

The Service Control Manager (SCM), hosted by services.exe, maintains the service database and mediates service creation, configuration, start and stop operations. A service definition includes more than a binary path:8

Field Security significance
Service name and display name Names can imitate legitimate products; neither proves provenance
ImagePath / binary path Executable and arguments that SCM starts
Service type Own process, shared process, driver and other variants
Start type Boot, system, automatic, delayed automatic, demand or disabled
Service account LocalSystem, LocalService, NetworkService, virtual account, gMSA or custom account
Dependencies and triggers Additional conditions controlling startup
Service DACL Who may query, reconfigure, start, stop or delete the service
sequenceDiagram
    participant C as Configuration process
    participant S as Service Control Manager
    participant D as Service database
    participant P as Service process

    C->>S: Create or modify service
    S->>D: Store ImagePath, start type,<br/>account, type and security descriptor
    Note over S: Trigger may be boot,<br/>demand or service trigger
    S->>P: Start configured image
    Note over P: Token belongs to configured<br/>service account

Figure 4 — A service is an SCM-managed security object. It runs as LocalSystem only when LocalSystem is the configured service account.

Creating an auto-start service configured as LocalSystem combines persistence with privileged execution, but only a caller with sufficient SCM rights can do so. A service configured for a low-privilege virtual account preserves a very different security context. The image must also behave as the configured service type expects; an arbitrary console program may start and then fail because it never connects to the service control dispatcher.

Modifying an existing service can be as important as creating one. Dangerous patterns include an unexpected ImagePath, a writable service binary or directory, an unquoted path with spaces, a start-type change, weakened service DACLs and service-account replacement.

Read-only triage

1
2
3
Get-CimInstance -ClassName Win32_Service |
    Select-Object Name, DisplayName, State, StartMode, StartName, PathName |
    Sort-Object Name

For a suspicious service, preserve the complete configuration, registry key, service security descriptor, binary hash, signature, timestamps and recent event history before changing it. A display name resembling “Windows Update” is not useful attribution; compare the canonical service name, executable path and signer with a known-good system or configuration inventory.

Scheduled tasks

Task Scheduler separates four concepts that a one-line command tends to hide:

  • registration: task path, author, XML definition and ACL;
  • trigger: boot, logon, time, idle, event or another condition;
  • principal: account, logon type and requested run level;
  • action: executable, arguments and working directory.
flowchart LR
    R[Registered task] --> T[Trigger set]
    R --> P[Principal and logon type]
    R --> A[Action and arguments]
    R --> S[Settings and conditions]
    T --> TS[Task Scheduler service]
    S --> TS
    TS --> X[Launch action]
    P --> X
    A --> X

Figure 5 — The task name is only a label. Detection must parse the trigger, principal, action, arguments, run level and conditions from the task XML.

A logon-triggered task can behave like a Run key, but tasks can also execute without an interactive session, repeat on an interval, start at boot, react to an event or run only when network and power conditions are met. They do not inherently run as SYSTEM: the task definition selects the principal. Registering a task for a more privileged principal requires the corresponding authority and a compatible logon type.3

Read-only triage

1
2
3
4
5
6
7
8
9
10
11
12
Get-ScheduledTask | ForEach-Object {
    [pscustomobject]@{
        Path      = $_.TaskPath
        Name      = $_.TaskName
        State     = $_.State
        Principal = $_.Principal.UserId
        RunLevel  = $_.Principal.RunLevel
        Actions   = ($_.Actions | ForEach-Object {
            "{0} {1}" -f $_.Execute, $_.Arguments
        }) -join '; '
    }
} | Sort-Object Path, Name

High-value anomalies include tasks created in the library root, misleading vendor names, hidden tasks, actions in user-writable directories, script hosts with encoded or remote content, unexpected SYSTEM principals and short repeat intervals. A task that is deleted immediately after execution can still be reconstructed from its creation event if the Security log was collected in time.

Permanent WMI event subscriptions

Filter, consumer and binding

WMI supports temporary subscriptions that exist only while a client is connected and permanent subscriptions stored in the WMI repository. A permanent subscription can survive a reboot and react even when no user is logged on.9

It consists of three persistent objects:

  1. __EventFilter contains the WQL query and event namespace—the trigger.
  2. A logical consumer, such as CommandLineEventConsumer or ActiveScriptEventConsumer, describes the action.
  3. __FilterToConsumerBinding associates the filter with the consumer.
flowchart LR
    E[Event provider] --> F[__EventFilter<br/>WQL trigger]
    F -->|matching event| B[__FilterToConsumerBinding]
    B --> C[Logical event consumer]
    C --> W[WMI consumer provider]
    W --> A[Command, script, log or other action]

    R[(WMI repository)] --- F
    R --- B
    R --- C

Figure 6 — A permanent WMI subscription is not one object. Persistence exists because a filter, consumer and binding form a complete chain in the repository.

The binding is the activation edge. Removing it deactivates that filter-to- consumer relationship, while leaving the filter or consumer behind as an orphaned forensic artifact. Conversely, inspecting consumers alone can miss a suspicious binding to a benign-looking shared filter.10

Security-sensitive permanent consumers require administrative authority, and the creator SID must be consistent across the filter, consumer and binding. Permanent subscriptions are designed to function without an interactive user and may execute through WMI provider infrastructure under a powerful context; this is why WMI persistence can combine durability with privilege.11

Read-only triage

1
2
3
4
5
6
7
8
9
10
11
12
13
$namespace = 'root\subscription'

Get-CimInstance -Namespace $namespace -ClassName __EventFilter |
    Select-Object Name, EventNamespace, Query, CreatorSID

Get-CimInstance -Namespace $namespace -ClassName CommandLineEventConsumer |
    Select-Object Name, ExecutablePath, CommandLineTemplate, CreatorSID

Get-CimInstance -Namespace $namespace -ClassName ActiveScriptEventConsumer |
    Select-Object Name, ScriptingEngine, ScriptFileName, ScriptText, CreatorSID

Get-CimInstance -Namespace $namespace -ClassName __FilterToConsumerBinding |
    Select-Object Filter, Consumer, CreatorSID

Do not delete every subscription that invokes a command. Management and monitoring products also use WMI. Compare names, CreatorSIDs, queries and consumer content with endpoint role, installed software and a known-good fleet baseline.

Telemetry: observe creation and execution

A persistence object has at least two useful moments: installation or modification, and later activation. A robust detection connects both.

flowchart LR
    I[Initial process] --> M[Persistence artifact created or changed]
    M --> Q[Quiet interval, logoff or reboot]
    Q --> T[Trigger fires]
    T --> B[Windows broker launches action]
    B --> P[Persistent process]

    I -. process telemetry .-> SIEM[Correlation]
    M -. registry, file, SCM,<br/>task or WMI telemetry .-> SIEM
    P -. process, network and<br/>image telemetry .-> SIEM

Figure 7 — Installation and activation may be separated by hours or days. Preserve stable identifiers, paths, hashes and task/service names across the quiet interval.

Mechanism Configuration telemetry Activation telemetry
Run keys Security 4657 when a matching registry SACL is configured; Sysmon 12–14 Security 4688, Sysmon 1, EDR process lineage
Startup folders Security 4663 with a matching filesystem SACL; Sysmon 11 file creation Security 4688, Sysmon 1, shell/logon lineage
Services Security 4697; System/SCM 7045; SCM 7040 for start-type changes; registry monitoring under HKLM\SYSTEM\CurrentControlSet\Services SCM state events, Security 4688, Sysmon 1, EDR service/process relationship
Scheduled tasks Security 4698 create, 4699 delete, 4700 enable, 4701 disable, 4702 update; Task Scheduler Operational log Task Scheduler action events, Security 4688, Sysmon 1
WMI subscriptions Sysmon 19 filter, 20 consumer, 21 binding; WMI-Activity and EDR telemetry Child or follow-on activity from WMI provider infrastructure, Sysmon 1, network and script telemetry

Service event 4697 records the installed image, start type and configured service account when the corresponding audit subcategory is enabled. Scheduled task lifecycle events belong to Audit Other Object Access Events and must also be enabled deliberately.1213

Security event 4657 is not automatic registry telemetry. It is generated only when Audit Registry is enabled and the target key has a matching SACL. Likewise, file-object events require both the audit policy and appropriate SACLs. Sysmon registry and file rules should be narrowly targeted to persistence locations to retain signal without collecting every routine write.1415

Security 4698 contains the task XML, including its action, trigger and principal. On newer event versions it also contains client-process information, making it valuable for tying registration back to the creating process. Collect it centrally before an attacker can delete the task or clear the local log.16

Detection patterns

Rare writer plus rare target. A Run value written by an installer is common. The same value written by a document reader, browser child, script host or process in a temporary directory is materially different. Combine writer prevalence with target signer, path and fleet prevalence.

User-writable payload with privileged broker. Prioritize services, SYSTEM tasks and WMI consumers whose action resolves into a user profile, temporary directory, download cache, writable network share or directory modifiable by non-administrators.

Masquerading. Names such as “WindowsUpdate” or “SecurityHealth” are cheap. Compare binary signer, file version metadata, canonical path, service/task folder, creation time and presence on peers. Do not allow a familiar label to outweigh an anomalous action.

Change followed by delayed execution. Join the configuration event to the first later process execution using normalized path, hash, service or task name, WMI consumer and host. The quiet interval is a feature of persistence, not evidence that the events are unrelated.

Short-lived registration. A task, service or WMI binding created, executed and deleted within minutes is often more suspicious than a long-lived object. Centralized event collection retains the installation trail after the local artifact is gone.

Unexpected principal. Alert when a persistence object moves from a user context to LocalSystem, a service account or a high-value domain identity. Correlate with logon ID and the identity model described in the access-token article.

Incident response and removal

Removing only the payload leaves a broken autorun; removing only the autorun leaves the payload and initial-access path. Treat persistence as a relationship between configuration, trigger, principal and action.

  1. Preserve evidence first. Export the registry value, task XML, complete service configuration or WMI objects. Record ACLs, owner, CreatorSID, timestamps, hashes, signatures and relevant event logs.
  2. Contain the execution path. Isolate the endpoint when appropriate and stop further activation. For WMI, break the binding before removing the consumer and filter; for a service, stop and disable it before deletion when safe; for tasks, disable before removing the definition.
  3. Quarantine the action. Preserve a forensic copy under incident-response procedure, then remove or block the executable, script, shortcut and any secondary loader.
  4. Find the installer. Trace the writer process, user, logon ID, parent chain, download origin and remote-management session. Otherwise the same mechanism may be recreated.
  5. Search the fleet. Hunt by normalized path, hash, signer, task/service name, WMI query, consumer text and creator—not just by the visible label.
  6. Revalidate. Reboot or reproduce the trigger in a controlled manner, confirm the object is gone, and watch for attempted recreation.

The exact deletion order matters most for WMI. Removing a consumer before its binding can leave invalid references; deleting only the binding deactivates the subscription but leaves forensic objects. Capture all three before making changes.

Hardening

Control Security effect
Remove local administrator rights from daily-use accounts Prevents routine creation of machine-wide autoruns, privileged services, SYSTEM tasks and sensitive WMI consumers
Use WDAC or AppLocker with managed script policy Prevents an autorun from becoming useful when its unsigned or unapproved action cannot execute
Protect service and task ACLs Stops low-privilege users from reconfiguring an existing privileged execution path
Keep service binaries and parent directories non-writable by unprivileged users Prevents replacement of a trusted service action without changing SCM configuration
Use virtual accounts or gMSAs and least privilege for services and tasks Limits impact when the persistent process is compromised
Inventory autostarts continuously Makes creation time and fleet rarity visible instead of relying on periodic manual review
Enable process creation with command line and central collection Connects persistence configuration with later activation
Target Sysmon registry, file and WMI events Provides high-value change telemetry without indiscriminate event volume
Audit scheduled-task and service creation Captures task XML, service image path, account and creator for investigation
Enable the Defender ASR rule Block persistence through WMI event subscription after audit-mode testing Blocks a specific WMI persistence path; Configuration Manager environments require careful compatibility testing17
Baseline signed software and known management subscriptions Reduces false positives without allowlisting solely by name
Monitor telemetry health and policy changes Detects gaps created by stopped agents, cleared logs or modified Sysmon/EDR configuration

Disabling WMI, Task Scheduler or the Service Control Manager is not a practical hardening strategy; Windows and enterprise-management software depend on them. The goal is to restrict who may configure privileged execution, constrain what may run, and make every configuration change attributable.

Summary

Run keys and Startup folders are logon autostarts. Their machine-wide variants broaden scope but normally still execute as the user who logs on. Services are SCM-managed objects whose start condition, image, account and DACL determine their power. Scheduled tasks combine triggers, principals, actions and settings in an XML-backed definition. Permanent WMI subscriptions form a three-object chain—filter, consumer and binding—that can survive reboot and react without an interactive session.

For defenders, the strongest signal is the relationship between the writer, artifact, trigger and later process. Capture creation events, configuration content and process telemetry centrally; normalize paths and identities; score the configured principal and target location; and retain evidence before removing the persistence chain. A familiar name is weak evidence. A rare writer creating a privileged autostart that points into a user-writable path is not.

References

This post is licensed under CC BY 4.0 by the author.

© 0xabadface. Some rights reserved.

Using the Chirpy theme for Jekyll.