T1574

Hijack Execution Flow

This detection identifies adversaries attempting to hijack the operating system's execution flow to run malicious payloads. The detection covers the broad parent technique including DLL hijacking, path interception via unquoted service paths or PATH variable manipulation, dynamic linker hijacking on Linux/macOS, services file and registry permission weaknesses, and application shimming. By monitoring for suspicious image loads from non-standard directories, registry modifications to service image paths, creation of DLLs in directories preceding legitimate ones on the search path, and modifications to shared library paths on Linux, this detection surfaces the most common execution flow hijacking patterns across Windows, Linux, and macOS platforms. Malware families such as DarkGate, ShimRat, Raspberry Robin, and Denis have all leveraged these techniques for persistence and privilege escalation.

What is T1574 Hijack Execution Flow?

Hijack Execution Flow (T1574) maps to the Persistence and Privilege Escalation and Defense Evasion tactics — the adversary is trying to maintain their foothold in MITRE ATT&CK.

This page provides production-ready detection logic for Hijack Execution Flow, covering the data sources and telemetry it touches: Microsoft Defender for Endpoint. The queries below are rated high severity at medium confidence, and ship for 7 SIEM platforms — KQL, SPL, Elastic, QRadar, Sumo, YARA-L, LogScale.

MITRE ATT&CK

Tactic
Persistence Privilege Escalation Defense Evasion
Technique
T1574 Hijack Execution Flow
Canonical reference
https://attack.mitre.org/techniques/T1574/
Microsoft Sentinel / Defender
kusto
let SuspiciousDLLPaths = dynamic(["\\Users\\", "\\Temp\\", "\\AppData\\", "\\ProgramData\\", "\\Downloads\\"]);
let LegitSystemPaths = dynamic(["C:\\Windows\\System32\\", "C:\\Windows\\SysWOW64\\", "C:\\Windows\\WinSxS\\"]);
// Branch 1: DLL loaded from suspicious user-writable path
let DLLHijack = DeviceImageLoadEvents
| where TimeGenerated > ago(1d)
| where ActionType == "ImageLoaded"
| where FileName endswith ".dll"
| where not(FolderPath has_any (LegitSystemPaths))
| where FolderPath has_any (SuspiciousDLLPaths)
| where InitiatingProcessFolderPath has_any (LegitSystemPaths)
| summarize DLLLoads=count(), DLLPaths=make_set(FolderPath,10), Processes=make_set(InitiatingProcessFileName,10) by DeviceName, InitiatingProcessFileName, InitiatingProcessAccountName, bin(TimeGenerated, 5m)
| extend Technique="DLL Hijack - Suspicious DLL Load Path", Score=60;
// Branch 2: Service binary path modification in registry
let ServiceRegMod = DeviceRegistryEvents
| where TimeGenerated > ago(1d)
| where ActionType in ("RegistryValueSet", "RegistryKeyCreated")
| where RegistryKey has_any ("HKLM\\SYSTEM\\CurrentControlSet\\Services", "HKLM\\System\\CurrentControlSet\\Services")
| where RegistryValueName in ("ImagePath", "ServiceDLL")
| where RegistryValueData has_any ("\\Users\\", "\\Temp\\", "\\AppData\\", "\\ProgramData\\", "%TEMP%", "%APPDATA%")
   or RegistryValueData matches regex @"[A-Za-z]:\\(?!Windows|Program Files)[^\\]+\\[^\\]+\.exe"
| project TimeGenerated, DeviceName, RegistryKey, RegistryValueName, RegistryValueData, InitiatingProcessFileName, InitiatingProcessAccountName
| extend Technique="Service Registry Hijack", Score=70;
// Branch 3: PATH environment variable modification in registry
let PathEnvMod = DeviceRegistryEvents
| where TimeGenerated > ago(1d)
| where ActionType == "RegistryValueSet"
| where RegistryKey has_any ("HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment", "HKCU\\Environment")
| where RegistryValueName =~ "Path"
| where RegistryValueData has_any ("\\Users\\", "\\Temp\\", "\\AppData\\", "\\ProgramData\\")
   and not(RegistryValueData has "C:\\Windows")
| project TimeGenerated, DeviceName, RegistryKey, RegistryValueName, RegistryValueData, InitiatingProcessFileName, InitiatingProcessAccountName
| extend Technique="PATH Environment Modification", Score=65;
// Branch 4: Executable created in directory that shadows system binary
let ShadowExec = DeviceFileEvents
| where TimeGenerated > ago(1d)
| where ActionType == "FileCreated"
| where FileName in~ ("cmd.exe","powershell.exe","net.exe","regsvr32.exe","rundll32.exe","msiexec.exe","wmic.exe","cscript.exe","wscript.exe","mshta.exe","certutil.exe","bitsadmin.exe","svchost.exe","explorer.exe")
| where not(FolderPath has_any ("C:\\Windows\\", "C:\\Program Files\\"))
| project TimeGenerated, DeviceName, FileName, FolderPath, InitiatingProcessFileName, InitiatingProcessAccountName
| extend Technique="Shadow System Binary Creation", Score=85;
DLLHijack
| project TimeGenerated, DeviceName, AccountName=InitiatingProcessAccountName, ProcessName=InitiatingProcessFileName, Detail=tostring(DLLPaths), Technique, Score
| union (
    ServiceRegMod | project TimeGenerated, DeviceName, AccountName=InitiatingProcessAccountName, ProcessName=InitiatingProcessFileName, Detail=RegistryValueData, Technique, Score
)
| union (
    PathEnvMod | project TimeGenerated, DeviceName, AccountName=InitiatingProcessAccountName, ProcessName=InitiatingProcessFileName, Detail=RegistryValueData, Technique, Score
)
| union (
    ShadowExec | project TimeGenerated, DeviceName, AccountName=InitiatingProcessAccountName, ProcessName=InitiatingProcessFileName, Detail=FolderPath, Technique, Score
)
| order by Score desc, TimeGenerated desc

Multi-branch KQL detection covering the four most common Hijack Execution Flow patterns: (1) DLL image loads from user-writable directories when the initiating process is a legitimate system binary, (2) service ImagePath or ServiceDLL registry values modified to point to non-standard directories, (3) PATH environment variable modifications that prepend user-writable directories, and (4) creation of executables with system binary names outside C:\Windows. Results are scored by risk level.

high severity medium confidence

Data Sources

Microsoft Defender for Endpoint

Required Tables

DeviceImageLoadEvents DeviceRegistryEvents DeviceFileEvents

False Positives

  • Software installers that temporarily drop DLLs into user-writable paths during setup (e.g., Adobe, Java, Teams updaters)
  • Developer workstations with custom PATH entries pointing to local build directories (e.g., C:\Users\dev\bin added to PATH for custom CLI tools)
  • IT automation tools such as SCCM/Intune agents that modify service registry keys during patch deployment
  • Portable application suites (e.g., PortableApps) that legitimately place executables outside Program Files
  • Security agents and EDR products that inject helper DLLs into processes from non-System32 locations

Sigma rule & cross-platform mapping

The detection logic for Hijack Execution Flow (T1574) above is provided in a vendor-neutral form so you can deploy it on any SIEM. The same logic is shipped here as native KQL (Microsoft Sentinel / Defender), SPL (Splunk), Elastic (Elastic Security (EQL)), QRadar (IBM QRadar (AQL)), Sumo (Sumo Logic CSE), YARA-L (Google Chronicle / SecOps), LogScale (CrowdStrike LogScale (CQL)) queries. In Sigma terms, this detection targets the following logsource:

logsource:
  product: windows

Browse the community-maintained Sigma rules for this technique:


Testing Methodology

Validate this detection against 4 adversary techniques from Atomic Red Team. Each test below lists the behaviour to exercise and the telemetry you should expect to see. Executable commands and cleanup steps are available with Pro.

  1. Test 1DLL Search Order Hijack via Missing DLL in System Process Working Directory

    Expected signal: Sysmon Event ID 7 (ImageLoaded) with ImageLoaded path pointing to %TEMP%\wlbsctrl.dll. DeviceImageLoadEvents in MDE with FolderPath matching %TEMP%.

  2. Test 2Service Registry ImagePath Modification to Non-Standard Path

    Expected signal: Sysmon Event ID 13 (RegistryValueSet) for HKLM\SYSTEM\CurrentControlSet\Services\DummyTestSvc\ImagePath with value pointing to %TEMP%. Windows Security Event 4657 if object access auditing is enabled.

  3. Test 3PATH Environment Variable Hijack via User Registry Modification

    Expected signal: Sysmon Event ID 13 (RegistryValueSet) for HKCU\Environment\Path with the new value containing the %TEMP% subdirectory. DeviceRegistryEvents in MDE with RegistryValueData containing \Temp\.

  4. Test 4Linux Dynamic Linker Hijack via LD_PRELOAD

    Expected signal: Linux auditd syscall events for the execve/openat calls loading the malicious .so. Syslog entries if auditd is configured to monitor /tmp. Process events showing LD_PRELOAD environment variable set in process spawn context.


Response Playbook

Triage

  1. Step 1: Identify the triggering branch (DLL load, registry modification, file creation, or process spawn) and note the affected host, user account, and timestamp to scope the investigation.
  2. Step 2: For DLL hijack alerts — verify the loading process (InitiatingProcessFileName). If a legitimate Windows binary (e.g., SearchIndexer.exe, migwiz.exe, svchost.exe) loaded a DLL from a user-writable path, treat as high priority. Check if the DLL exists in the legitimate System32 path as well.
  3. Step 3: For service registry alerts — query DeviceRegistryEvents for the full history of the modified key: `DeviceRegistryEvents | where RegistryKey contains "Services\\<ServiceName>" | order by TimeGenerated desc`. Determine when the legitimate path was changed and by which process.
  4. Step 4: Calculate the time delta between registry modification and any subsequent service start (check for Event ID 7036/7045 in System log or Sysmon Event 1 for the service binary). A short delta (under 1 minute) strongly suggests active exploitation.
  5. Step 5: For shadow binary creation — check if the file was written by a suspicious process. Run `DeviceProcessEvents | where DeviceName == "<host>" | where InitiatingProcessFileName == "<writer_process>" | where TimeGenerated between (datetime(<alert_time> - 5m) .. datetime(<alert_time> + 5m))` to establish process context.
  6. Step 6: Hash the suspicious file/DLL and query VirusTotal or your threat intel platform. A clean hash on a newly created file is still suspicious — custom malware is often unknown to AV.
  7. Step 7: Review the process tree for the affected process using DeviceProcessEvents with parent-child traversal to identify the initial access vector that led to the file placement.
  8. Step 8: Check for network connections spawned by or shortly after the suspicious load using `DeviceNetworkEvents | where InitiatingProcessFileName == "<process>" | where TimeGenerated > ago(1h)`.

Containment

  1. Isolate the affected endpoint via EDR remote isolation to prevent lateral movement while investigation continues. Preserve the isolation until the file/DLL has been analyzed.
  2. If a service was modified: immediately stop the service (`Stop-Service <ServiceName> -Force`) and restore the legitimate ImagePath from a known-good backup or by referencing another unaffected host.
  3. Revert any modified registry keys to their original values. Use `reg add` to restore the correct service path or use a GPO/baseline enforcement tool.
  4. Remove the malicious DLL or executable from the filesystem. Before deletion, copy to an isolated forensic share for analysis.
  5. If the PATH environment variable was modified system-wide (HKLM), revert via Group Policy or direct registry edit. If per-user (HKCU), force a password reset and logoff all sessions for the affected account.
  6. Block the malicious binary hash at the EDR level and in your proxy/firewall if C2 connections were observed.

Evidence Collection

  1. Collect the malicious DLL/executable: copy to forensic share preserving timestamps (`robocopy /COPYALL /LOG`).
  2. Export the affected registry hive sections: `reg export HKLM\SYSTEM\CurrentControlSet\Services <output_path>\services_export.reg`.
  3. Capture full process memory of any process that loaded the malicious DLL using EDR memory acquisition or ProcDump before isolating.
  4. Export Sysmon operational log: `wevtutil epl Microsoft-Windows-Sysmon/Operational sysmon.evtx`.
  5. Export Windows Security event log covering the alert window: `wevtutil epl Security security.evtx /q:"*[System[TimeCreated[@SystemTime>='<start>' and @SystemTime<='<end>']]]"` .
  6. Collect prefetch files from `C:\Windows\Prefetch\` — the `.pf` file for the malicious binary will show its load history and linked DLLs.
  7. If DLL hijack: collect the full list of DLLs loaded by the victim process using EDR image load telemetry or Process Monitor capture if still running.
  8. Capture network traffic PCAP if the host is still active and network isolation has not yet been applied.

Escalation Criteria

  • ! Escalate immediately to Incident Response if the malicious DLL/binary has been confirmed as a known RAT, backdoor, or C2 implant by threat intel lookup.
  • ! Escalate if lateral movement indicators are present: authentication events from the affected host to other internal systems, new SMB connections, or remote WMI/PSExec activity within 1 hour of the hijack.
  • ! Escalate if the affected process is a high-privilege service (SYSTEM or a service account with admin rights), indicating successful privilege escalation.
  • ! Escalate if multiple hosts show the same IoC (same malicious DLL hash, same registry modification pattern) — this indicates automated deployment and a likely active intrusion campaign.
  • ! Escalate if data staging or exfiltration indicators are present: large file copies to temp directories, compression utilities spawned by affected processes, or unexpected outbound connections to external IPs.

Investigation Guide

Forensic Artifacts

  • > Windows Prefetch files at C:\Windows\Prefetch\ — reveal DLL load history and execution count for hijacked binaries
  • > HKLM\SYSTEM\CurrentControlSet\Services\<ServiceName>\ImagePath and ServiceDLL registry values
  • > HKCU\Environment and HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment — PATH variable values
  • > File creation timestamps for DLLs in user-writable directories (compare to legitimate DLL timestamps in System32)
  • > Sysmon Event ID 7 (ImageLoaded) logs capturing DLL load events with file hash
  • > Sysmon Event ID 12/13/14 registry event logs for service key modifications
  • > Windows Error Reporting files in %APPDATA%\Microsoft\Windows\WER\ — may show crashes caused by malicious DLL injection
  • > Application Compatibility shim database at C:\Windows\AppPatch\Custom\ (for shim-based hijacks)
  • > Linux /etc/ld.so.preload and LD_PRELOAD environment variable values
  • > Linux /etc/ld.so.conf.d/ configuration files for dynamic linker path hijacking
  • > macOS DYLD_INSERT_LIBRARIES environment variable and LC_RPATH entries in Mach-O binaries
  • > MFT ($MFT) records for newly created DLL files to establish precise creation timestamps

Tuning Guidance

Start by baselining your environment's legitimate non-standard DLL load paths. Many enterprise applications (Java, Python, Electron-based apps) load DLLs from their own application directories outside Program Files — add these to an allowlist by InitiatingProcessSHA256 hash rather than by directory path. For service registry modifications, maintain a CMDB-backed allowlist of expected service binary paths; filter alerts where the new ImagePath matches approved software deployment paths. Shadow binary creation alerts have the lowest false positive rate and should rarely need tuning — investigate all hits. On developer workstations, consider excluding specific known-dev-tool paths (e.g., C:\Users\<user>\scoop\) from PATH modification alerts while maintaining alerting on shared/system-wide PATH changes. For Linux LD_PRELOAD hunting, baseline all binaries that legitimately use LD_PRELOAD in your environment (often JVM-based monitoring agents) and filter by process name.


Hunting Queries

Hunts for processes loading 2 or more DLLs from non-standard user-writable directories, which may indicate a DLL planting or search order hijack campaign targeting a specific application.

Hunting — KQL
kql
// Hunt: Processes loading DLLs from more than one non-standard directory (possible DLL planting pattern)
DeviceImageLoadEvents
| where TimeGenerated > ago(7d)
| where ActionType == "ImageLoaded"
| where FileName endswith ".dll"
| where not(FolderPath has_any ("C:\\Windows\\System32", "C:\\Windows\\SysWOW64", "C:\\Windows\\WinSxS", "C:\\Program Files\\", "C:\\Program Files (x86)\\"))
| where FolderPath has_any ("\\Users\\", "\\Temp\\", "\\AppData\\", "\\ProgramData\\")
| summarize UniqueNonStandardDLLDirs=dcount(FolderPath), DLLList=make_set(FileName, 20), DirList=make_set(FolderPath, 10) by DeviceName, InitiatingProcessFileName, InitiatingProcessSHA256
| where UniqueNonStandardDLLDirs >= 2
| order by UniqueNonStandardDLLDirs desc
Hunting — SPL
spl
index=* sourcetype="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational" EventCode=7 earliest=-7d
| where NOT match(ImageLoaded, "(?i)C:\\Windows\\(System32|SysWOW64|WinSxS)")
| where NOT match(ImageLoaded, "(?i)C:\\Program Files")
| where match(ImageLoaded, "(?i)(\\Users\\|\\Temp\\|\\AppData\\|\\ProgramData\\)")
| stats dc(ImageLoaded) as unique_nonstandard_dlls, values(ImageLoaded) as dll_list by ComputerName, Image, Hashes
| where unique_nonstandard_dlls >= 2
| sort - unique_nonstandard_dlls

Hunts for service ImagePath registry values modified to non-standard directories over the past 30 days, identifying potential services hijack persistence that may have been planted earlier and not yet triggered an alert.

Hunting — KQL
kql
// Hunt: Services with ImagePath pointing outside Program Files and Windows directories (potential services hijack)
DeviceRegistryEvents
| where TimeGenerated > ago(30d)
| where RegistryKey matches regex @"(?i)HKLM\\SYSTEM\\CurrentControlSet\\Services\\[^\\]+$"
| where RegistryValueName =~ "ImagePath"
| where not(RegistryValueData has_any ("C:\\Windows\\", "C:\\Program Files\\", "C:\\Program Files (x86)\\", "%SystemRoot%", "%ProgramFiles%"))
| where RegistryValueData !startswith "\\??\\" // Exclude kernel driver paths
| project TimeGenerated, DeviceName, ServiceName=extract(@"Services\\([^\\]+)$", 1, RegistryKey), RegistryValueData, InitiatingProcessFileName, InitiatingProcessAccountName
| order by TimeGenerated desc
Hunting — SPL
spl
index=* sourcetype="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational" EventCode=13 earliest=-30d
| where match(TargetObject, "(?i)CurrentControlSet\\Services")
| where match(TargetObject, "(?i)ImagePath$")
| where NOT match(Details, "(?i)(C:\\\\Windows\\\\|C:\\\\Program Files|%SystemRoot%|%ProgramFiles%)")
| where NOT match(Details, "^\\\\\?\?\\\\")
| rex field=TargetObject "Services\\\\(?<service_name>[^\\\\]+)"
| table _time, ComputerName, service_name, Details, Image, User
| sort - _time

Hunts for creation of files whose names match known Windows system DLLs (common DLL hijacking targets like cryptbase.dll, msfte.dll, cscapi.dll) in directories outside System32/SysWOW64, a strong indicator of DLL planting.

Hunting — KQL
kql
// Hunt: Newly created DLL files whose names match known system DLLs (DLL planting via name collision)
let KnownSystemDLLs = dynamic(["ntdll.dll","kernel32.dll","kernelbase.dll","user32.dll","advapi32.dll","ole32.dll","shell32.dll","wininet.dll","urlmon.dll","comctl32.dll","msvcrt.dll","version.dll","cryptbase.dll","msfte.dll","wlbsctrl.dll","ntshrui.dll","sysmain.dll","cscapi.dll","wbemcomn.dll","dbghelp.dll","amsi.dll","netapi32.dll"]);
DeviceFileEvents
| where TimeGenerated > ago(14d)
| where ActionType == "FileCreated"
| where FileName in~ (KnownSystemDLLs)
| where not(FolderPath has_any ("C:\\Windows\\System32", "C:\\Windows\\SysWOW64", "C:\\Windows\\WinSxS"))
| project TimeGenerated, DeviceName, FileName, FolderPath, SHA256, InitiatingProcessFileName, InitiatingProcessAccountName
| order by TimeGenerated desc
Hunting — SPL
spl
index=* sourcetype="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational" EventCode=11 earliest=-14d
| where match(TargetFilename, "(?i)(ntdll|kernel32|kernelbase|user32|advapi32|shell32|wininet|urlmon|cryptbase|msfte|wlbsctrl|cscapi|wbemcomn|dbghelp|amsi|netapi32)\.dll$")
| where NOT match(TargetFilename, "(?i)C:\\Windows\\(System32|SysWOW64|WinSxS)")
| table _time, ComputerName, TargetFilename, Image, User, Hashes
| sort - _time

Atomic Red Team Tests

Test 1 DLL Search Order Hijack via Missing DLL in System Process Working Directory
windows

Simulates a DLL search order hijack by placing a malicious DLL in the current working directory of a system process that attempts to load a DLL not found in System32. Uses a benign test DLL that writes a marker file to demonstrate successful load.

Command

powershell
$dllPath = "$env:TEMP\wlbsctrl.dll"
$cppCode = @'
#include <windows.h>
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
    if (ul_reason_for_call == DLL_PROCESS_ATTACH) {
        HANDLE h = CreateFileA("C:\\Windows\\Temp\\hijack_test.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
        if (h != INVALID_HANDLE_VALUE) CloseHandle(h);
    }
    return TRUE;
}
'@
# Download pre-compiled test DLL (or compile inline with csc workaround)
# For test purposes, create a DLL using PowerShell Add-Type and Reflection
Add-Type -TypeDefinition @"
public class TestDLL {
    public static void Load() {
        System.IO.File.WriteAllText(@"C:\Windows\Temp\hijack_test.txt", "DLL Hijack Test Executed at " + System.DateTime.Now);
    }
}
"@ -OutputAssembly $dllPath
Write-Host "Test DLL placed at: $dllPath"
Write-Host "Expected: Sysmon Event 7 for $dllPath loaded by a process"
Write-Host "Expected: DeviceImageLoadEvents alert in MDE"

Cleanup

powershell
Remove-Item -Path "$env:TEMP\wlbsctrl.dll" -Force -ErrorAction SilentlyContinue
Remove-Item -Path "C:\Windows\Temp\hijack_test.txt" -Force -ErrorAction SilentlyContinue

Expected Telemetry

Sysmon Event ID 7 (ImageLoaded) with ImageLoaded path pointing to %TEMP%\wlbsctrl.dll. DeviceImageLoadEvents in MDE with FolderPath matching %TEMP%.

Expected Detection

DLL Hijack - Suspicious DLL Load Path alert fires when the DLL is loaded from %TEMP% by a process whose initiating path is within C:\Windows.

Test 2 Service Registry ImagePath Modification to Non-Standard Path
windows

Modifies an existing non-critical Windows service's ImagePath registry value to point to a user-writable directory, simulating the persistence mechanism used by service hijacking malware. Uses the 'TermService' (Remote Desktop) service as a safe test target, restores original value in cleanup.

Command

powershell
$serviceName = "DummyTestSvc"
$dummyExe = "$env:TEMP\svchost_test.exe"
# Create a dummy executable
copy "C:\Windows\System32\cmd.exe" $dummyExe
# Create a new dummy service pointing to a legitimate binary first
New-Service -Name $serviceName -BinaryPathName "C:\Windows\System32\svchost.exe -k netsvcs" -DisplayName "Dummy Test Service" -StartupType Manual -ErrorAction SilentlyContinue
# Now modify ImagePath to non-standard path (the hijack simulation)
$regPath = "HKLM:\SYSTEM\CurrentControlSet\Services\$serviceName"
Set-ItemProperty -Path $regPath -Name "ImagePath" -Value $dummyExe
Write-Host "Service ImagePath modified to: $dummyExe"
Write-Host "Registry key: $regPath"
Get-ItemProperty -Path $regPath -Name "ImagePath"

Cleanup

powershell
Stop-Service -Name "DummyTestSvc" -Force -ErrorAction SilentlyContinue
sc.exe delete DummyTestSvc
Remove-Item -Path "$env:TEMP\svchost_test.exe" -Force -ErrorAction SilentlyContinue

Expected Telemetry

Sysmon Event ID 13 (RegistryValueSet) for HKLM\SYSTEM\CurrentControlSet\Services\DummyTestSvc\ImagePath with value pointing to %TEMP%. Windows Security Event 4657 if object access auditing is enabled.

Expected Detection

Service Registry Hijack alert fires based on ImagePath value containing \Temp\ or \Users\ path.

Test 3 PATH Environment Variable Hijack via User Registry Modification
windows

Modifies the user-level PATH environment variable to prepend a user-controlled directory, simulating the PATH interception technique. An attacker would place a malicious binary with the same name as a legitimate tool in this directory to intercept execution when the tool is called without a full path.

Command

powershell
$hijackDir = "$env:TEMP\path_hijack_test"
New-Item -ItemType Directory -Path $hijackDir -Force | Out-Null
# Create a fake 'whoami.exe' in the hijack directory
Copy-Item "C:\Windows\System32\cmd.exe" "$hijackDir\whoami.exe"
# Read current user PATH
$currentPath = [Environment]::GetEnvironmentVariable("PATH", "User")
Write-Host "Original PATH: $currentPath"
# Prepend hijack directory to user PATH (the hijack)
$newPath = "$hijackDir;$currentPath"
[Environment]::SetEnvironmentVariable("PATH", $newPath, "User")
Write-Host "Modified PATH: $newPath"
Write-Host "Hijack dir prepended. Any call to 'whoami' in new shell will load $hijackDir\whoami.exe first"
# Verify
[Environment]::GetEnvironmentVariable("PATH", "User")

Cleanup

powershell
$currentPath = [Environment]::GetEnvironmentVariable("PATH", "User")
$hijackDir = "$env:TEMP\path_hijack_test"
$cleanPath = ($currentPath -split ";" | Where-Object { $_ -ne $hijackDir }) -join ";"
[Environment]::SetEnvironmentVariable("PATH", $cleanPath, "User")
Remove-Item -Path $hijackDir -Recurse -Force -ErrorAction SilentlyContinue
Write-Host "PATH restored and hijack directory removed."

Expected Telemetry

Sysmon Event ID 13 (RegistryValueSet) for HKCU\Environment\Path with the new value containing the %TEMP% subdirectory. DeviceRegistryEvents in MDE with RegistryValueData containing \Temp\.

Expected Detection

PATH Environment Modification alert fires based on HKCU\Environment\Path modification containing a user-writable directory path.

Test 4 Linux Dynamic Linker Hijack via LD_PRELOAD
linux

Simulates dynamic linker hijacking on Linux by compiling a shared library that intercepts the 'getuid' libc function and setting LD_PRELOAD to load it before any process launch. This technique is used by attackers to intercept library calls and inject malicious code.

Command

bash
# Create a malicious shared library that hooks getuid()
cat > /tmp/hijack_test.c << 'EOF'
#include <stdio.h>
#include <unistd.h>
uid_t getuid(void) {
    FILE *f = fopen("/tmp/ldpreload_hijack_evidence.txt", "a");
    if (f) { fprintf(f, "LD_PRELOAD hook executed by PID %d\n", getpid()); fclose(f); }
    return 1000; // Return non-root UID to appear benign
}
EOF
gcc -shared -fPIC -nostartfiles -o /tmp/hijack_test.so /tmp/hijack_test.c
# Set LD_PRELOAD to load the malicious library
export LD_PRELOAD=/tmp/hijack_test.so
# Trigger a process that calls getuid
id
echo "Check /tmp/ldpreload_hijack_evidence.txt for hook execution evidence"
cat /tmp/ldpreload_hijack_evidence.txt

Cleanup

bash
unset LD_PRELOAD
rm -f /tmp/hijack_test.c /tmp/hijack_test.so /tmp/ldpreload_hijack_evidence.txt

Expected Telemetry

Linux auditd syscall events for the execve/openat calls loading the malicious .so. Syslog entries if auditd is configured to monitor /tmp. Process events showing LD_PRELOAD environment variable set in process spawn context.

Expected Detection

Hunting query for processes with LD_PRELOAD environment variable set to paths outside standard library directories. Auditd rule alert for loading shared objects from /tmp or /home.

Related Detections

Detection Variants (1)

Different telemetry and tradecraft for the same technique — pick the one that matches the data you collect.