monoxgas / sRDI

Shellcode implementation of Reflective DLL Injection. Convert DLLs to position independent shellcode
Other
2.12k stars 459 forks source link

static template class dll will crash #21

Open luom opened 3 years ago

luom commented 3 years ago

this is my code dllmain.cpp

#include <windows.h>
#include "template.h"

void go();

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        go();
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

void go()
{
    string sa = "sasas";

    static test<string>* t = new test<string>();
    printf("t ptr: 0x%x\n", t);
    t->add(&sa);
    printf("count: %d\n", t->count());
}

template.h

#pragma once
#include <stdio.h>
#include <map>
#include <string>
#include <windows.h>

using namespace std;

template <class T>
class test
{
public:
    test() = default;

    int add(T *ptr)
    {
        LPEXCEPTION_POINTERS info = NULL;
        DWORD code;
        __try
        {
            m_map[m_count] = ptr;
            return m_count++;
        }
        __except (code = GetExceptionCode(), info = GetExceptionInformation(), EXCEPTION_EXECUTE_HANDLER)
        {

            printf("Exception happene code: 0x%x, %d\n", code, info->ExceptionRecord->ExceptionInformation[1]);
            //info->ExceptionRecord->ExceptionInformation
            exit(0);
        }

    }

    int count()
    {
        return m_count;
    }

private:
    int m_count = 0;
    map<int, T*> m_map;
};

Natice Loader.cpp

...
    if (VirtualProtect(finalShellcode, sysInfo.dwPageSize, PAGE_EXECUTE_READWRITE, &dwOldProtect1)) {
        RDI rdi = (RDI)(finalShellcode);
        printf("[+] Executing RDI\n");
        HANDLE t = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)finalShellcode, NULL, 0, NULL);
        //WaitForSingleObject(t, INFINITE);
        getchar();
        free(finalShellcode); // Free the RDI blob. We no longer need it.
    }

when i remote inject via ProcessHacker work ok,but i use Native.exe load this dll is crash. when i change static test<string>* t = new test<string>(); to test<string>* t = new test<string>(); in dllmain.cpp both work ok the ptr always is NULL when i use static

this is result ProcessHacker:

t ptr: 0xad7a0
count: 1

Native.exe Loader:

[+] File is a DLL, attempting to convert
[+] Successfully Converted
[+] Executing RDI
t ptr: 0x0
Exception happene code: 0xc0000005, 8
monoxgas commented 3 years ago

Thanks for the report on this!

I generally don't have a ton of bandwidth to look into issues like this, but I'll try to find some time to dig in.

injertao commented 2 years ago

Maybe the problem is CRT initialization

romanholidaypancakes commented 1 year ago

@monoxgas You can check this project bb107/MemoryModulePP, which supports exception handling