This chapter covers persistence mechanisms in Windows environments, specifically focusing on scheduled tasks and registry run keys. Persistence is a critical phase of the penetration testing lifecycle, ensuring that access to a compromised system is maintained even after reboots or credential changes. On the PT0-002 exam, approximately 5-10% of questions relate to persistence mechanisms, often integrated into scenario-based questions about post-exploitation and maintaining access. Understanding the exact registry keys, command-line tools, and detection methods is essential for both offensive and defensive tasks.
Jump to a section
Imagine you are a security auditor for a large office building. A persistent intruder has broken in and wants to ensure they can always get back inside even if you change the locks. They have two main tricks. First, they bribe the building's automated cleaning crew—a robot that runs every night at 3 AM—to unlock a specific window every time it cleans. Even if you lock that window during the day, the robot's schedule (a scheduled task) will unlock it again at 3 AM. Second, they hide a key under the doormat of the main entrance. Every time the building manager resets the electronic lock system, the system checks the 'doormat' (a registry run key) and finds the key, letting the intruder in. The intruder's persistence relies on these automated mechanisms that are part of the building's normal operations. As a pentester, you must understand how to find and remove these persistence mechanisms during an assessment and how to create them to maintain access. On the PT0-002 exam, you will be tested on the specific registry keys, scheduled task creation tools, and the commands to detect and remove persistence.
What Are Persistence Mechanisms and Why Do They Exist?
Persistence mechanisms are techniques used by attackers to ensure continued access to a compromised system after initial exploitation. In the context of the PT0-002 exam, persistence is part of the 'Attacks and Exploits' domain (Objective 3.4: 'Given a scenario, perform post-exploitation techniques'). The goal is to maintain access even if the system is rebooted, the user logs off, or credentials are changed. Without persistence, an attacker would need to re-exploit the system after every reboot, which is unreliable and noisy.
Scheduled Tasks: How They Work Internally
Windows Task Scheduler is a built-in service that allows users to schedule automated tasks. An attacker can create a scheduled task that executes a payload (e.g., a reverse shell) at a specific time or triggered by an event (e.g., system startup, user logon).
Key Components:
- Task Scheduler Service (Schedule): Runs as svchost.exe and manages task execution.
- Task XML Definition: Tasks are stored in %SystemRoot%\System32\Tasks as XML files. The XML contains triggers, actions, conditions, and settings.
- Triggers: Common triggers for persistence include:
- TimeTrigger: At a specific time (e.g., every day at 3 AM).
- LogonTrigger: When any user logs on.
- BootTrigger: At system startup.
- RegistrationTrigger: When the task is created or modified.
- Actions: Typically execute a program (e.g., cmd.exe /c payload.exe).
- Security Context: Tasks can run as SYSTEM, Administrator, or a specific user. For stealth, attackers often use high-integrity accounts.
Creation Tools: - schtasks.exe: The command-line tool for creating, querying, and deleting tasks. - Create a task that runs at logon:
schtasks /create /tn "Updater" /tr "C:\Users\Public\malware.exe" /sc onlogon /ru SYSTEM- Create a task that runs every hour:
schtasks /create /tn "Updater" /tr "C:\Users\Public\malware.exe" /sc hourly /mo 1 /ru SYSTEM- PowerShell: New-ScheduledTask, Register-ScheduledTask cmdlets.
$action = New-ScheduledTaskAction -Execute "C:\Users\Public\malware.exe"
$trigger = New-ScheduledTaskTrigger -AtStartup
Register-ScheduledTask -TaskName "Updater" -Action $action -Trigger $trigger -RunLevel HighestWMI: __EventFilter and CommandLineEventConsumer can also trigger execution, but this is less common for persistence on modern systems.
Detection and Removal: - List all tasks:
schtasks /query /fo LIST /v- Delete a task:
schtasks /delete /tn "Updater" /f- PowerShell:
Get-ScheduledTask | Where-Object {$_.TaskPath -notlike "\Microsoft\*"} | Unregister-ScheduledTask -Confirm:$falseEvent Logs: Task scheduling events are recorded in Event ID 106 (Task registered) and 129 (Task started) under Microsoft-Windows-TaskScheduler/Operational.
Registry Run Keys: How They Work Internally
Registry run keys are locations in the Windows Registry that specify programs to run automatically when a user logs on or when the system starts. Attackers add entries to these keys to execute their payloads.
Key Locations:
- Current User (HKCU):
- HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
- HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce
- Local Machine (HKLM):
- HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run
- HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce
- HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServices (for services, less common)
- 64-bit vs 32-bit: On 64-bit systems, there are also Wow6432Node paths for 32-bit applications:
- HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Run
Mechanism:
- During user logon, winlogon.exe loads the user's profile and processes the Run and RunOnce keys. For HKLM, the system processes these keys at boot time.
- RunOnce keys are executed once and then deleted, but attackers can abuse them by setting a value that re-creates the key after execution.
- Values are typically REG_SZ or REG_EXPAND_SZ containing the path to the executable.
Creation Tools: - reg.exe: Command-line registry editor.
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "Backdoor" /t REG_SZ /d "C:\Users\Public\malware.exe"- PowerShell:
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "Backdoor" -Value "C:\Users\Public\malware.exe"VBScript/JavaScript: Can also modify the registry via WScript.Shell.
Detection and Removal:
- Use reg query to list keys:
reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Run"- Delete a value:
reg delete "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "Backdoor" /f- Autoruns (Sysinternals): The autorunsc.exe tool lists all auto-start locations, including registry run keys, scheduled tasks, services, etc. This is the gold standard for detection.
autorunsc.exe -a -c -h > autoruns.csvEvent Logs: Registry modifications are logged in Event ID 4657 (Registry value modified) under Security if auditing is enabled.
Interaction with Other Persistence Mechanisms
Scheduled tasks and registry run keys are often used together. For example, an attacker might use a scheduled task to re-add a registry run key if it gets deleted. Additionally, other persistence mechanisms like service creation (sc.exe), startup folder entries, and WMI event subscriptions can complement these methods. On the exam, you may be asked to identify which persistence mechanism is being used based on the description of the trigger or storage location.
Default Values and Timers
Scheduled Task Defaults: The default security context for tasks created via schtasks without /ru is the user who created the task. The task scheduler service starts automatically on Windows.
Registry Run Keys: There is no built-in delay; the program runs as soon as the user logs on. However, attackers often add a small delay using cmd /c timeout /t 5 && malware.exe to evade detection.
RunOnce: The key is deleted after execution, but if the program fails, it may not be deleted. Attackers sometimes set the value to re-add itself.
Common Pitfalls on the Exam
Confusing HKCU and HKLM: HKCU runs only for the current user; HKLM runs for all users. The exam may ask which key to modify to affect all users.
Scheduled Task Triggers: AtLogon runs when any user logs on; AtStartup runs at system boot before any user logs on. OnIdle runs when the system is idle.
RunOnce vs Run: RunOnce runs once and is deleted; Run runs every logon. The exam may test that RunOnce is not suitable for long-term persistence unless re-created.
64-bit vs 32-bit: On 64-bit systems, 32-bit applications read from Wow6432Node keys. The exam may present a scenario where a 32-bit payload is not executing because the entry is in the wrong node.
Verification Commands
- Check scheduled task status:
schtasks /query /tn "Updater" /v | findstr "Status"- Check registry run keys for all users:
reg query "HKLM\Software\Microsoft\Windows\CurrentVersion\Run"
reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Run"- Use PowerShell to search for common persistence locations:
Get-CimInstance -ClassName Win32_StartupCommand | Select-Object Name, Command, Location, UserSummary of Key Technical Details
Scheduled Task XML Path: C:\Windows\System32\Tasks\
Registry Run Key Default: REG_SZ value type
Common Attack Tools: schtasks, reg, PowerShell, wmic
Detection Tools: autorunsc, Sysinternals Suite, Event Viewer
Exam Focus: Identify persistence mechanism from description, know exact registry paths, and understand the difference between user-level and system-level persistence.
Gain Initial Access and Reconnaissance
After compromising a target system via a vulnerability (e.g., EternalBlue, phishing), the attacker performs reconnaissance to understand the system's architecture: OS version, installed software, user privileges, and existing security controls. This step determines which persistence mechanisms are viable. For example, on a Windows 10 system with UAC enabled, registry run keys under HKCU may not require administrator privileges, while HKLM keys and scheduled tasks often do. The attacker checks current user context using `whoami` and `net localgroup Administrators`.
Select Persistence Mechanism Based on Privileges
Based on the privilege level, the attacker chooses a persistence method. If the attacker has user-level access, they can modify HKCU registry run keys or create user-level scheduled tasks (which run only when the user is logged on). If they have administrator privileges, they can use HKLM run keys or system-level scheduled tasks that run as SYSTEM. The attacker also considers stealth: registry run keys are easier to detect via Autoruns, while scheduled tasks can be hidden by using obscure names or mimicking legitimate system tasks.
Create the Persistence Entry
The attacker creates the persistence entry using command-line tools. For a scheduled task, they use `schtasks /create` with appropriate triggers (e.g., `onlogon` or `onstart`). For registry run keys, they use `reg add` to set a value under the chosen key. The payload is typically placed in a writable directory like `C:\Users\Public\` or `%TEMP%`. The attacker may also obfuscate the payload path to avoid detection, e.g., using environment variables or short file names (8.3 format).
Test Persistence by Rebooting or Logging Off
To verify persistence works, the attacker triggers the event that should execute the payload. For scheduled tasks, they can run `schtasks /run /tn "TaskName"` to test immediately. For registry run keys, they log off and log back on, or use `runas` to simulate a new logon session. The attacker checks for callback (e.g., reverse shell connecting back) or checks process list for the payload. If it fails, they troubleshoot by checking event logs (Event ID 106 for task registration, 4657 for registry modification).
Clean Up and Cover Tracks
After the assessment, the attacker removes persistence to leave the system clean. They delete scheduled tasks using `schtasks /delete` and remove registry values using `reg delete`. They also clear relevant event logs to hide evidence of their activity. In a penetration test, this step is documented in the report. The attacker may also restore any modified security settings (e.g., disabled antivirus).
Enterprise Scenario 1: Banking Sector - Maintaining Access After Phishing
A penetration tester successfully phishes an employee at a regional bank and gains a foothold on a workstation. The tester needs to maintain access for lateral movement to the core banking server. The workstation has endpoint protection that scans new files but does not monitor scheduled tasks. The tester creates a scheduled task named 'AdobeFlashUpdate' that runs every hour as the current user, executing a PowerShell one-liner that downloads and runs a reverse shell from a command-and-control server. The task is hidden by placing it in the \Microsoft\Windows\ task folder (e.g., \Microsoft\Windows\Update\), which is often ignored by administrators. The tester also adds a registry run key under HKCU as a backup, but the scheduled task is the primary persistence because it survives reboots and runs even if the user logs off (if set to run as SYSTEM). The key consideration: the task must run with sufficient privileges to allow lateral movement. The tester uses schtasks /create /ru SYSTEM to escalate privileges via the task.
Enterprise Scenario 2: Healthcare - Registry Run Keys for Legacy Systems
A hospital still runs Windows 7 on some medical devices. A tester exploits a vulnerability in a legacy application and gains SYSTEM access. Because the system is heavily locked down with group policies that restrict scheduled task creation, the tester opts for registry run keys under HKLM. They add a value under HKLM\Software\Microsoft\Windows\CurrentVersion\Run that launches a service installer (sc.exe create Backdoor binPath= "C:\ProgramData\malware.exe"). The service starts automatically, providing persistence. However, the tester must be careful: on Windows 7, the Run key is processed before the user logs on, so the payload runs as SYSTEM. The tester also adds a RunOnce key that re-creates the Run key if it is deleted. In production, this method is noisy because it modifies the registry, but on legacy systems without advanced monitoring, it is effective.
Common Misconfiguration: Scheduled Task with Wrong Trigger
A common mistake is using the 'AtLogon' trigger when the attacker wants persistence at boot. 'AtLogon' runs when a user logs on, but if the system is set to auto-logon, it works. However, if the system is a server that rarely has interactive logons, the task may never run. The correct trigger for boot-time persistence is 'AtStartup'. In one engagement, a tester used 'AtLogon' on a domain controller that had no interactive logons; the task never executed. The fix was to change the trigger to 'AtStartup' and run as SYSTEM.
PT0-002 Exam Focus: Persistence Mechanisms
This topic falls under Objective 3.4: 'Given a scenario, perform post-exploitation techniques.' The exam expects you to identify the correct persistence mechanism based on a description of the system and the attacker's goals. Common exam scenarios include:
- 'An attacker wants to execute a payload every time a specific user logs on. Which registry key should they modify?' Answer: HKCU\Software\Microsoft\Windows\CurrentVersion\Run.
- 'Which tool can create a scheduled task that runs at system startup?' Answer: schtasks.exe.
Most Common Wrong Answers:
1. Confusing HKCU and HKLM: Candidates often choose HKLM when the scenario specifies a single user, or vice versa. Remember: HKCU affects only the current user; HKLM affects all users.
2. Selecting 'RunOnce' for persistent access: RunOnce runs once and is deleted. For long-term persistence, use 'Run' (not RunOnce) unless the scenario explicitly mentions re-creating the key.
3. Choosing the wrong trigger for scheduled tasks: 'AtStartup' runs at boot; 'AtLogon' runs at user logon. The exam may describe a server that reboots but no one logs on, so 'AtStartup' is correct.
4. Ignoring Wow6432Node: On 64-bit systems, 32-bit applications read from Wow6432Node. If a 32-bit payload is not executing, the entry might be in the wrong node.
Specific Numbers and Values:
- Registry key paths must be memorized exactly: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run (abbreviated as HKCU\...\Run).
- Scheduled task creation: schtasks /create /tn "TaskName" /tr "PayloadPath" /sc onlogon /ru SYSTEM.
- The sc parameter for schedule: onstart, onlogon, hourly, daily, etc.
- Autoruns tool: autorunsc.exe is the command-line version.
Edge Cases: - Windows 10 and 11: UAC can block write access to HKLM even for administrators unless running elevated. The exam may test that an administrator must run CMD as administrator to modify HKLM run keys. - Group Policy: Some enterprise environments disable scheduled task creation via GPO. The exam may ask which persistence method works if scheduled tasks are blocked (answer: registry run keys or startup folder). - Persistence via WMI: While not as common, WMI event subscriptions can provide persistence. The exam may include it as a distractor.
How to Eliminate Wrong Answers:
- If the scenario mentions 'every time the system boots', eliminate any answer that runs at user logon (e.g., HKCU Run, AtLogon task).
- If the scenario mentions 'stealth' or 'avoid detection', look for methods that are less monitored, such as scheduled tasks in the \Microsoft\Windows\ folder vs. registry run keys which are commonly scanned.
- If the scenario mentions 'user-level access without admin', eliminate HKLM, system-level scheduled tasks, and services.
Persistence mechanisms ensure continued access after reboots or logoffs; common methods include scheduled tasks and registry run keys.
Scheduled tasks can be created with schtasks.exe and triggered at startup (onstart) or logon (onlogon).
Registry run keys are located under HKCU (current user) and HKLM (all users) in the Run subkey.
RunOnce keys execute once and are deleted; not suitable for long-term persistence unless re-created.
On 64-bit systems, 32-bit applications use the Wow6432Node registry path for run keys.
Autoruns (Sysinternals) is the primary detection tool for persistence mechanisms.
Event IDs 106 (task registered) and 4657 (registry modified) log persistence creation if auditing is enabled.
These come up on the exam all the time. Here's how to tell them apart.
Scheduled Tasks
Stored as XML files in C:\Windows\System32\Tasks.
Can be triggered by system events (boot, logon, idle, etc.).
Can run as SYSTEM even if created by a standard user (with admin rights).
More flexible: can run with different user contexts and conditions.
Detectable via schtasks /query or Autoruns.
Registry Run Keys
Stored as registry values under HKCU or HKLM keys.
Trigger only at user logon (or system boot for HKLM).
Run with the privileges of the user who owns the key (HKCU) or SYSTEM (HKLM).
Simpler to create but less flexible.
Detectable via reg query or Autoruns; very commonly monitored.
Mistake
Registry run keys under HKCU require administrator privileges to modify.
Correct
HKCU keys are user-specific and can be modified by the user without elevation. Only HKLM keys require administrative privileges.
Mistake
Scheduled tasks created with 'AtLogon' trigger run at system startup before any user logs on.
Correct
'AtLogon' runs when a user logs on. For system startup persistence, use the 'AtStartup' trigger.
Mistake
The RunOnce key is ideal for long-term persistence because it runs every time the user logs on.
Correct
RunOnce runs only once and is then deleted. For persistent access, use the Run key or re-create the RunOnce entry after execution.
Mistake
On 64-bit Windows, all registry entries under HKLM\Software\Microsoft\Windows\CurrentVersion\Run affect both 32-bit and 64-bit applications.
Correct
32-bit applications read from the Wow6432Node path. To affect 32-bit applications, the entry must be placed under HKLM\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Run.
Mistake
The 'schtasks /create' command with '/ru SYSTEM' requires the current user to be SYSTEM.
Correct
Any administrator can create a task that runs as SYSTEM using the '/ru SYSTEM' option, as long as they run the command with elevated privileges.
Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.
HKCU (HKEY_CURRENT_USER) run keys affect only the currently logged-on user and can be modified without administrator privileges. HKLM (HKEY_LOCAL_MACHINE) run keys affect all users and require administrative rights to modify. On the exam, if the scenario describes a single user's workstation, HKCU is likely correct; for system-wide persistence, use HKLM.
Use the command: `schtasks /create /tn "TaskName" /tr "C:\path\to\payload.exe" /sc onstart /ru SYSTEM`. The `/sc onstart` parameter specifies that the task runs at system startup. The `/ru SYSTEM` runs the task with the highest privileges. Ensure you run the command as an administrator.
RunOnce keys execute the associated program once and then delete the value. Attackers can abuse it by setting the value to a command that re-creates the RunOnce entry after execution, ensuring persistence. For example, the value could be `cmd /c C:\payload.exe & reg add HKCU\...\RunOnce /v Backdoor /t REG_SZ /d "cmd /c C:\payload.exe"`. This way, the payload runs every logon.
Autoruns (autorunsc.exe) from Sysinternals is the best tool for detecting persistence. It scans all auto-start locations, including scheduled tasks, registry run keys, services, startup folders, and more. Run `autorunsc.exe -a -c -h > autoruns.csv` to output all entries in CSV format for analysis.
Use the command: `schtasks /delete /tn "TaskName" /f`. The `/f` forces deletion without confirmation. You can also use PowerShell: `Unregister-ScheduledTask -TaskName "TaskName" -Confirm:$false`. Ensure you have administrative privileges to delete system tasks.
Wow6432Node is a registry path on 64-bit Windows that stores 32-bit application settings. When a 32-bit application reads the Run key, it looks under `HKLM\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Run` instead of the standard path. If you are deploying a 32-bit payload, you must add the entry to the Wow6432Node path for it to execute automatically.
Yes, by placing the task in a system folder like `\Microsoft\Windows\` (e.g., `\Microsoft\Windows\Update\`), the task may not appear in the default view of the Task Scheduler GUI. However, it can still be seen with `schtasks /query` or Autoruns. Attackers often use this to evade casual inspection.
You've just covered Persistence Mechanisms: Scheduled Tasks, Registry — now see how well it sticks with free PT0-002 practice questions. Full explanations included, no account needed.
Done with this chapter?