Persistence Removal
Eradication fails when persistence is missed. Attackers install multiple persistence mechanisms expecting some to be found and removed. Finding all of them — not just the obvious ones — is what prevents reinfection within hours of declaring the incident closed.
The IR team has spent three days cleaning 47 compromised endpoints. They removed Cobalt Strike beacons from each one, deleted the malware files, ran antivirus scans — all clean. They declare the incident eradicated and return normal operations. Eight hours later, the attacker's beacon is back on six of the hosts. Post-incident investigation reveals the sequence: the attacker had established four separate persistence mechanisms on each host. The IR team found and removed the primary beacon (scheduled task running a PowerShell cradle). They missed: a WMI event subscription that reinstalled the beacon if the scheduled task was deleted, a registry run key pointing to a second-stage loader disguised as a legitimate system DLL, a malicious COM object hijacking that loaded when any user opened Windows Explorer, and a modified Windows service set to delayed-start so it wouldn't fire during the initial cleanup scan. The attacker anticipated finding and removal of one or two mechanisms. The IR team didn't know to look for all four. Systematic persistence hunting — not sample-and-assume — is the only approach that works.
Windows Persistence Taxonomy
Windows provides dozens of legitimate mechanisms that applications use for persistence. Attackers abuse all of them. A comprehensive eradication requires checking every location where persistence can live, not just the locations where a specific attacker's tools are known to hide.
Windows Persistence Locations — Comprehensive Taxonomy
══════════════════════════════════════════════════════════════════════
REGISTRY — AUTO-RUN LOCATIONS
─────────────────────────────────────────────────────────────────
Run keys (per-user and per-machine):
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
Image File Execution Options (IFEO) — debugger hijacking:
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options
Abuse: set "Debugger" value for a legitimate process to attacker binary;
attacker binary launches instead of (or in addition to) the legitimate process.
Classic target: sethc.exe (Sticky Keys) → cmd.exe for unauthenticated shell.
AppInit_DLLs — DLL loaded into every user-mode process:
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows\AppInit_DLLs
Disabled by Secure Boot in modern Windows; still relevant on legacy systems.
COM object hijacking:
HKCU\Software\Classes\CLSID\{GUID}\InprocServer32
Overrides system COM object registration for current user; loaded when
any application instantiates the COM object.
SCHEDULED TASKS
─────────────────────────────────────────────────────────────────
Locations:
C:\Windows\System32\Tasks\
C:\Windows\SysWOW64\Tasks\
Registry: HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache
Common attacker patterns:
• Task named to mimic legitimate Windows tasks ("MicrosoftEdgeUpdate",
"WindowsUpdateScheduler", "SystemMaintenance")
• Task created at: account logon, system startup, or repeating interval
• Task action: PowerShell with encoded command, regsvr32, rundll32,
mshta, or a file in %APPDATA% or %TEMP%
• Task set with "Delete if no longer scheduled" = False (prevents easy deletion)
WINDOWS SERVICES
─────────────────────────────────────────────────────────────────
Registry: HKLM\SYSTEM\CurrentControlSet\Services\
Service binary path: look for paths pointing to non-standard locations
(C:\ProgramData, %TEMP%, %APPDATA%, unusual directories in C:\Windows\)
Service types used for persistence:
• New service created with attacker binary as ServiceImagePath
• Existing legitimate service's binary path modified to point to attacker binary
• DLL service: ServiceType = 0x20 with attacker DLL as ServiceDll
in HKLM\SYSTEM\CurrentControlSet\Services\[name]\Parameters\ServiceDll
WINDOWS MANAGEMENT INSTRUMENTATION (WMI)
─────────────────────────────────────────────────────────────────
WMI event subscriptions: three components must exist together:
• EventFilter — defines the trigger (e.g., "system startup", "process creation")
• EventConsumer — defines the action (CommandLineEventConsumer or
ActiveScriptEventConsumer)
• FilterToConsumerBinding — links filter to consumer
WMI subscriptions survive reboots and are invisible to casual inspection.
They do not appear in Autoruns by default unless "WMI" checkbox is enabled.
They survive reimaging only if the WMI repository is preserved.
BOOT/PRE-OS PERSISTENCE
─────────────────────────────────────────────────────────────────
Bootkit (MBR/VBR modification):
Extremely rare in modern IR (Secure Boot prevents on UEFI systems)
but present in some sophisticated state actor tooling.
UEFI/firmware implants:
Nation-state actor capability. Survives OS reinstall.
Detection: Chipsec, ESET's UEFI scanner.
LOGON TRIGGERS
─────────────────────────────────────────────────────────────────
Winlogon notification packages:
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\
Values: "Shell" (default: explorer.exe), "Userinit" (runs at logon),
"Notify" (DLL that receives logon events)
Active Setup:
HKLM\SOFTWARE\Microsoft\Active Setup\Installed Components\{GUID}
Runs once per user profile; used for per-user first-run setup.
Attacker abuse: create a new GUID entry with StubPath pointing to
malicious executable; runs when each user first logs in.
DLL PERSISTENCE
─────────────────────────────────────────────────────────────────
DLL search order hijacking:
Applications search for DLLs in a defined order; placing a malicious
DLL with the same name as a legitimate DLL earlier in the search path
causes the malicious DLL to load instead.
DLL side-loading:
Legitimate application (with code signing) loads an unsigned DLL from
its own directory; attacker places malicious DLL in the application
directory with the correct name.
Systematic Methodology: Autoruns and EDR
There are two approaches to persistence hunting: tool-assisted (running Sysinternals Autoruns to enumerate all persistence locations) and EDR telemetry-based (querying EDR for persistence installation events across the fleet). Both have advantages; using them together provides the most complete coverage.
| Approach | What it finds | Limitations | Best use |
|---|---|---|---|
| Sysinternals Autoruns | Current state of all persistence locations on a specific host: registry run keys, scheduled tasks, services, WMI subscriptions, browser extensions, LSA providers, Winlogon entries, and more. Shows the binary hash and VirusTotal check for each entry. | Point-in-time snapshot of one host. Must be run on each host individually. Requires access to the live system. Does not show historical persistence that has already been removed. | Thorough single-host persistence audit during eradication. Best run after initial containment when the host is isolated. |
| Velociraptor persistence hunt | Fleet-wide query for all persistence locations simultaneously. Run the Windows.Persistence.PersistenceSniper or equivalent artifact across all confirmed-compromised hosts. Returns centralized results for analysis. | Requires Velociraptor deployment. Analysis of fleet-wide results requires additional triage to separate attacker persistence from legitimate applications. | Scaling persistence hunting to 50+ hosts during a large incident. Identifies which hosts have persistence and which do not. |
| EDR telemetry — historical persistence events | When persistence was installed: process that created the run key, scheduled task, or service. Exact timestamp. Command used. Who ran it. | Only shows events the EDR captured and retained. Does not show current state (if persistence was deleted by the attacker to cover tracks). | Establishing the timeline of when the attacker installed persistence and using that timeline to find other activity at the same time. |
| Manual artifact analysis (Shimcache, Amcache, Prefetch) | Evidence of execution — files that have been executed even if they no longer exist on disk. Crucial for persistence that has been manually cleaned before the IR team arrived. | Shows execution evidence, not current persistence state. Requires offline artifact analysis. | Finding "ghost persistence" — malware that was installed and removed but left execution traces. |
The mistake in persistence hunting is running Autoruns, looking at entries that have red VirusTotal ratings or obvious malicious names, deleting those, and declaring the host clean. Sophisticated attackers deliberately use inconspicuous persistence: legitimate-looking task names, paths that look like Windows directories, binaries that look like Windows system files (same name, same location, slightly different hash). The right approach: build the complete list of everything Autoruns found, then subtract the known-good baseline (a known-clean image of the same OS version and software configuration). What remains — the delta — is potentially attacker-installed persistence. Every item in that delta requires manual review, not just the items that look obviously malicious. The known-good baseline comparison is what separates systematic eradication from optimistic spot-checking.
Secondary Persistence Philosophy
Sophisticated attackers install multiple persistence mechanisms, expecting some to be found. This is not paranoia — it is operational security based on the attacker's experience with IR teams removing obvious persistence while missing subtle persistence. The concept of secondary (and tertiary) persistence means that finding and removing persistence mechanism #1 does not mean the host is clean.
Secondary Persistence Patterns
══════════════════════════════════════════════════════════════════════
REINSTALLER PATTERN
─────────────────────────────────────────────────────────────────
Primary: scheduled task that runs the beacon
Secondary: WMI subscription that detects if the scheduled task
no longer exists and reinstalls it
Effect: IR team deletes the scheduled task → WMI subscription
re-creates it within minutes
Detection: WMI subscription must be found and removed before
or simultaneously with the primary persistence
FALLBACK C2 PATTERN
─────────────────────────────────────────────────────────────────
Primary: beacon beaconing to C2 domain A
Secondary: same beacon with backup C2 domain B embedded
Effect: block domain A → beacon switches to domain B
Detection: memory analysis of the beacon binary to extract
all hardcoded C2 domains; block all of them simultaneously
SECONDARY IMPLANT PATTERN
─────────────────────────────────────────────────────────────────
Primary: Cobalt Strike beacon for active operations
Secondary: lightweight sleeper implant (different tool, different
path, different persistence mechanism) that activates
only if primary C2 goes silent for 72+ hours
Effect: IR team removes primary beacon, blocks C2 →
secondary implant activates after 72 hours
Detection: requires thorough persistence hunting beyond the primary
beacon; Autoruns comparison against clean baseline;
network monitoring for new C2 after incident is "closed"
GPO-BASED PERSISTENCE (AD environments)
─────────────────────────────────────────────────────────────────
Attacker modifies an existing GPO (or creates a new one) to deploy
persistence to all machines in scope
Effect: even after cleaning individual hosts, the GPO reapplies
attacker persistence on next Group Policy refresh (90 min)
Detection: EDR Events for GPO modifications; Active Directory
PowerShell audit of all GPOs changed in the incident window;
GPO content review for unexpected scheduled tasks or scripts
Eradication Verification Before Declaring Clean
Declaring a host "clean" without verification is one of the most consequential mistakes in IR. Verification has a specific methodology — it is not just "ran AV, found nothing."
| Verification check | What it confirms |
|---|---|
| Autoruns baseline comparison against clean image | No new persistence mechanisms remain that weren't present on a known-clean version of the same build |
| Hash verification of critical system binaries | No Windows system DLLs or executables have been replaced with attacker versions (compare against Microsoft file hash database or a known-clean reference) |
| Network connection check after re-enabling network | When containment is lifted, monitor outbound connections for 24 hours. Any C2 beacon would appear here as an anomalous outbound connection. |
| EDR agent health verification | The EDR agent was not tampered with and is reporting correctly; its process tree and telemetry stream are intact |
| WMI subscription audit | No WMI EventFilters, EventConsumers, or FilterToConsumerBindings exist outside expected system defaults |
| Scheduled task audit against baseline | No scheduled tasks exist outside the expected set for the host's build and software configuration |
A manufacturing company's IR investigation uncovered a WMI subscription that had been active for three years. The persistence had been installed during an initial intrusion that the company didn't know had occurred. Quarterly antivirus scans had run on the host for three years. The AV had never flagged the WMI subscription because it wasn't looking for WMI-based persistence — it was looking for malicious file signatures. The WMI subscription itself contained no file on disk. The attacker's payload was stored as a Base64-encoded string in the WMI repository, decoded and executed in memory by the ActiveScriptEventConsumer at system startup. No file was ever written to disk during the entire 3-year dwell time. The binary that the attacker's beacon process ran existed only in WMI's CIM database. The company discovered it during an IR engagement for an unrelated incident, when the IR team ran a comprehensive WMI subscription audit as part of their standard eradication methodology.
Q & A
Should you reimage a host or manually clean it during eradication?
The default recommendation in most IR engagements is reimaging for any host with confirmed malware execution, because reimaging provides a known-clean state that manual cleaning cannot guarantee. Manual cleaning works on a specific list of identified artifacts — if anything is missed, the host is not clean. Reimaging wipes everything and starts from a known baseline. The practical constraints on reimaging: it takes time (the reimaging process, reinstallation of applications, user profile restoration), it requires a clean gold image to reimage from, and it may not be operationally acceptable for servers with complex configurations. A pragmatic approach: reimage workstations (relatively standardized, easier to reimage), perform deep manual cleaning plus verification for servers (complex configurations that are difficult to quickly reimage). For any host where a rootkit or firmware-level implant is suspected, reimaging the OS is insufficient — hardware inspection or replacement may be required. If there is any doubt about whether manual cleaning is complete, reimaging is the safer choice.
How do you detect malicious WMI subscriptions in practice?
The authoritative source for WMI subscriptions is the WMI repository, queried using WMIC or PowerShell. The specific query is: Get-WMIObject -Namespace root\subscription -Class __EventFilter for filters, __EventConsumer for consumers, and __FilterToConsumerBinding for the bindings. On a clean Windows system with no third-party software that uses WMI subscriptions, these queries return empty results or a small number of known-good entries. Any unexpected EventFilter or EventConsumer should be investigated. Autoruns (with the WMI checkbox enabled under Options) also enumerates WMI subscriptions alongside all other persistence mechanisms. EDR products specifically alert on WMI subscription creation — these alerts appear in the incident timeline and are a detection signal that WMI-based persistence was likely installed. The combination of EDR alert history and current WMI subscription audit covers both historical and current WMI persistence.
What is the difference between eradication and recovery, and when do you transition?
Eradication means removing all attacker presence from the environment: deleting malware, removing persistence mechanisms, revoking compromised credentials, closing backdoors. The attacker can no longer access the environment via any of their established footholds. Recovery means restoring normal business operations and confidence in the environment's security state: reimaging compromised hosts, restoring from clean backups if needed, re-enabling services, returning systems to production status. The transition from eradication to recovery is appropriate when: all confirmed compromised hosts have been cleaned or reimaged, all identified persistence mechanisms have been removed and verified removed, all confirmed compromised credentials have been rotated and sessions terminated, monitoring is in place to detect re-intrusion attempts, and legal/compliance has confirmed that notification obligations are handled. The verification step is the gate — do not declare eradication complete without going through the verification checklist. Re-entering recovery and discovering a re-intrusion because eradication was incomplete is significantly more disruptive than extending the eradication phase by a few hours to complete thorough verification.
If an attacker had SYSTEM-level access on a host, can you trust that the operating system kernel was not modified?
SYSTEM-level access on Windows provides very high privileges — higher than standard administrator. From SYSTEM, an attacker can load kernel drivers (with appropriate signing, or by disabling driver signature enforcement), modify kernel data structures in memory (DKOM — Direct Kernel Object Manipulation), and install rootkits that hide processes and files from the OS. If SYSTEM-level access occurred on a host and a rootkit is suspected: manual cleanup is insufficient and unreliable — a rootkit can hide its own presence from the very tools you're using to find it. Reimaging the OS is the minimum response. If the threat actor is known to use UEFI-level implants (certain nation-state actors): a UEFI scan using tools like Chipsec is warranted, and hardware replacement may ultimately be required for the highest-sensitivity hosts. For most corporate IR engagements (ransomware, criminal actors, insider threat), SYSTEM-level access is common but kernel-level rootkits are rare — reimaging is sufficient. The elevated concern applies specifically when the incident indicators point to sophisticated nation-state actors.
How do you handle eradication on cloud-native workloads (containers, serverless) where "reimaging" doesn't apply in the same way?
Cloud-native workloads operate on a different model than traditional hosts: containers are (or should be) stateless and immutable, serverless functions are deployed from source, and infrastructure is defined in code. Eradication in this context means: (1) for containers — stop and delete all running containers from the compromised image, pull the clean image, redeploy; if the container image registry was compromised (attacker modified the base image), rebuild the image from scratch from a known-clean Dockerfile; (2) for serverless — redeploy from the verified clean source code; if the source code repository was compromised, restore from a known-clean commit; (3) for persistent cloud resources (databases, storage) that were accessed — audit their access logs (S3 access logs, Azure Blob audit logs) to determine what data was accessed, and determine whether the data itself was modified; (4) for the cloud control plane (IAM) — identity containment (as in Chapter 9) is the eradication step; there is no "host" to clean when the attacker's access was purely via IAM. The principle in cloud-native environments is that immutable infrastructure makes eradication easier in theory (destroy and redeploy), but identity and data-layer eradication is just as complex as in traditional environments.