Skip to content

Instantly share code, notes, and snippets.

@tostercx
Created February 5, 2017 01:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tostercx/6c7f61841284152ad09d5ad52bc7e30f to your computer and use it in GitHub Desktop.
Save tostercx/6c7f61841284152ad09d5ad52bc7e30f to your computer and use it in GitHub Desktop.
#include <io.h>
#include <fcntl.h>
#include <windows.h>
#include <stdio.h>
typedef int (__stdcall *PY_ISINITIALIZED)();
typedef int (__stdcall *PYRUN_SIMPLESTRING)(const char *str);
typedef DWORD* (__stdcall *PYGILSTATE_ENSURE)();
typedef void (__stdcall *PYGILSTATE_RELEASE)(DWORD *gstate);
PY_ISINITIALIZED Py_IsInitialized;
PYRUN_SIMPLESTRING PyRun_SimpleString;
PYGILSTATE_ENSURE PyGILState_Ensure;
PYGILSTATE_RELEASE PyGILState_Release;
HMODULE hModule;
void init()
{
// get python
hModule = GetModuleHandle("python27.dll");
Py_IsInitialized = (PY_ISINITIALIZED) GetProcAddress(hModule, "Py_IsInitialized");
PyGILState_Ensure = (PYGILSTATE_ENSURE) GetProcAddress(hModule, "PyGILState_Ensure");
PyGILState_Release = (PYGILSTATE_RELEASE) GetProcAddress(hModule, "PyGILState_Release");
PyRun_SimpleString = (PYRUN_SIMPLESTRING) GetProcAddress(hModule, "PyRun_SimpleString");
// make a console
AllocConsole();
freopen("CONOUT$", "w", stdout);
freopen("CONERR$", "w", stderr);
freopen("CONIN$", "r", stdin);
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
// display debug info
printf("PyGILState_Ensure: %X\n", (unsigned int)PyGILState_Ensure);
printf("PyGILState_Release: %X\n", (unsigned int)PyGILState_Release);
printf("PyRun_SimpleString: %X\n", (unsigned int)PyRun_SimpleString);
printf("Py_IsInitialized: %X\n", (unsigned int)Py_IsInitialized);
printf("\n");
}
DWORD WINAPI shell_thread(LPVOID lpParam)
{
while(!Py_IsInitialized())
Sleep(100);
DWORD *gstate = PyGILState_Ensure();
PyRun_SimpleString("import sys");
PyRun_SimpleString("import code");
PyRun_SimpleString("import blue");
PyRun_SimpleString("code.interact(local=locals())");
PyGILState_Release(gstate);
// fallback
while(true)
{
printf("thread dead\n");
Sleep(10000);
}
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
init();
CreateThread(
0, // default security attributes
0, // use default stack size
shell_thread, // thread function name
0, // argument to thread function
0, // use default creation flags
0 // returns the thread identifier
);
break;
case DLL_PROCESS_DETACH:
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment