This is something I’ve wanted to do for some time: take a command interpreter and transform it from an EXE into a DLL.
Why you ask? Well, because it’s a fun challenge 😉
But also because a DLL is loaded into a process. In a restricted environment, it can be injected into a legitimate process and thus bypass the restriction mechanisms.
Metasploit’s Meterpreter is another example of a command interpreter in DLL form.
cmd.exe from Microsoft is closed source, but there is an open-source variant available from the ReactOS project.
Compiling cmd.exe from ReactOS is simple: download the source-code and the ReactOS build environment. Install it, start the build environment and issue command make cmd. That’s all you need to do to compile cmd.exe (I used version 0.3.11).
Transforming the source code to generate a DLL in stead of an EXE is simple. You need to change 3 files.
Edit file cmd.rbuild and make these changes to the module element:
<module name="cmd" type="win32dll" installbase="system32" installname="cmd.dll" unicode="yes" crt="msvcrt">
Because I want to use this DLL in GUI-processes without console, I need to create a console. Edit file cmd.c and add AllocConsole(); to function cmd_main:
SetFileApisToOEM(); InputCodePage= 0; OutputCodePage = 0; AllocConsole(); hConsole = CreateFile(_T("CONOUT$"), GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
And because a DLL has another entry-function than an EXE, edit file main.c and replace function main with function DllMain:
#include <precomp.h> INT WINAPI DllMain( IN PVOID hInstanceDll, IN ULONG dwReason, IN PVOID reserved) { switch (dwReason) { case DLL_PROCESS_ATTACH: cmd_main(0, NULL); break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: break; } return TRUE; }
That’s it. Recompile with make cmd to generate cmd.dll
There are still some improvements we can make, but that’s for a later version: error messages are not displayed, exiting the shell terminates the host process, …
You can download the modified source files and compiled cmd.dll here.
This is a screenshot of cmd.dll injected inside Excel with my memory module shellcode: