tipssysmonetwdotnet-security

In-Memory DotNet Attack Detection with Sysmon & ETW

March 28, 202617 min read0 views
In-Memory DotNet Attack Detection with Sysmon & ETW

In-Memory DotNet Attack Detection with Sysmon & ETW

Fileless attacks have become increasingly sophisticated, particularly those leveraging .NET reflection to execute malicious payloads directly in memory. Traditional signature-based antivirus solutions often fail to detect these stealthy threats, making enhanced telemetry collection essential for effective threat hunting. Modern adversaries frequently employ frameworks like Donut loaders and Cobalt Strike BOFs to bypass security controls while maintaining persistence and executing post-exploitation activities.

This comprehensive guide explores how to configure Sysmon and leverage Event Tracing for Windows (ETW) providers to detect in-memory .NET-based attacks. We'll cover practical implementation strategies, sample detection rules, and tuning recommendations that security professionals can immediately apply in their environments. By understanding the telemetry generated by these attacks, defenders can significantly improve their ability to identify and respond to advanced threats.

Throughout this article, we'll examine real-world attack scenarios, demonstrate configuration techniques, and provide actionable guidance for implementing robust detection capabilities. Whether you're a seasoned threat hunter or a security engineer looking to enhance your monitoring infrastructure, this guide will equip you with the knowledge needed to combat fileless .NET attacks effectively.

How Can Sysmon Detect In-Memory .NET Attacks?

System Monitor (Sysmon) serves as a powerful Windows system service that provides detailed information about process creations, network connections, and file system changes. For detecting in-memory .NET attacks, Sysmon's event logging capabilities are particularly valuable when properly configured to capture relevant telemetry.

The foundation of effective detection lies in understanding which Sysmon events correlate with .NET attack vectors. Event ID 1 (Process Creation) is fundamental, as it captures when processes are launched, including those initiated through reflective loading techniques. However, for fileless attacks specifically targeting .NET execution, additional events become critical.

Event ID 3 (Network Connection) plays a vital role in identifying suspicious outbound connections that may indicate command and control communication from injected payloads. Event ID 7 (Image Load) becomes especially important when tracking DLL loads that might reveal reflective DLL injection or other in-memory execution techniques.

To maximize detection effectiveness, Sysmon should be configured with a custom configuration file that includes specific rules for capturing .NET-related activities. Here's a basic Sysmon configuration snippet focusing on .NET attack detection:

xml powershell.exe wscript.exe cscript.exe [Image blocked: No description]installutil.exe [Image blocked: No description]msbuild.exe clr.dll mscoree.dll

This configuration focuses on processes commonly abused for .NET execution and monitors for core .NET runtime components being loaded into memory. The inclusion criteria ensure that relevant events are captured without overwhelming the system with excessive logging.

Advanced configurations should also consider Event ID 10 (ProcessAccess) to detect potential process injection attempts. This event can reveal when one process accesses another with specific access rights that may indicate reflective injection or other memory manipulation techniques.

For optimal performance, it's crucial to balance comprehensive logging with system resources. Overly broad filters can generate excessive noise, while insufficient coverage may miss critical attack indicators. Regular review and refinement of Sysmon configurations based on observed attack patterns ensures continued effectiveness against evolving threats.

Key Insight: Properly configured Sysmon can serve as your first line of defense against in-memory .NET attacks by capturing essential telemetry that reveals malicious activity patterns.

What ETW Providers Are Essential for .NET Attack Monitoring?

Event Tracing for Windows (ETW) providers offer granular visibility into system activities that complement Sysmon's broader event logging. For .NET attack detection, several key ETW providers provide invaluable insights into runtime behavior and potential malicious activities.

The Microsoft-Windows-DotNETRuntime provider is fundamental for monitoring .NET application execution. It generates events related to assembly loading, JIT compilation, garbage collection, and exception handling. These events can reveal when suspicious assemblies are loaded into memory or when unusual execution patterns occur.

To enable this provider, administrators can use the logman utility:

cmd logman start DotNetTrace -p Microsoft-Windows-DotNETRuntime 0x10000000 -o C:\temp\dotnet.etl -ets

The Microsoft-Antimalware-Scan-Interface provider offers insights into real-time protection activities, including detections and exclusions. While primarily focused on traditional malware scanning, it can sometimes reveal attempts to execute malicious .NET code that triggers heuristic detections.

Microsoft-Windows-Kernel-Process provides low-level process creation and termination events, offering additional context around process spawning that might indicate reflective loading or process hollowing techniques used in .NET attacks.

Here's a PowerShell script to enable multiple ETW providers simultaneously:

powershell

Enable multiple ETW providers for .NET attack monitoring

$providers = @( "Microsoft-Windows-DotNETRuntime", "Microsoft-Antimalware-Scan-Interface", "Microsoft-Windows-Kernel-Process" )

foreach ($provider in $providers) { logman start "$($provider)Monitor" -p $provider -o "C:\temp$($provider).etl" -ets }

Comparison between Sysmon and ETW capabilities reveals complementary strengths:

AspectSysmonETW
Deployment ComplexityModerateHigh
Real-time ProcessingLimitedExcellent
Storage RequirementsHigherLower
Query FlexibilityGoodExcellent
Cross-platform SupportWindows OnlyWindows/Linux

The Microsoft-Windows-Threat-Intelligence provider is particularly valuable for detecting known malicious behaviors. It generates events when suspicious activities matching known attack patterns are observed, providing immediate alerts for investigation.

Microsoft-Windows-Security-Mitigations offers insights into exploit mitigation technologies, revealing when attackers attempt to bypass security controls or when defensive measures successfully block malicious activities.

Configuring ETW providers requires careful consideration of performance impact. Continuous tracing can consume significant system resources, so it's recommended to implement targeted tracing sessions that activate during specific monitoring windows or in response to suspicious activities detected through other means.

Actionable Tip: Combine ETW providers with Sysmon for comprehensive coverage. ETW provides deep runtime insights while Sysmon offers broader system context.

Which Process Creation Patterns Indicate .NET-Based Attacks?

Identifying malicious process creation patterns is crucial for detecting .NET-based attacks that utilize fileless execution techniques. Several distinct patterns consistently appear when attackers leverage .NET frameworks like Donut loaders or Cobalt Strike BOFs.

One common pattern involves legitimate Microsoft executables being used to execute malicious .NET code. Tools like InstallUtil.exe, MSBuild.exe, and RegAsm.exe are frequently abused because they're signed by Microsoft and often whitelisted by application control policies. When these tools spawn child processes or load unexpected modules, it's a strong indicator of malicious activity.

Consider this suspicious process tree example:

explorer.exe └───InstallUtil.exe └───cmd.exe └───powershell.exe

In this scenario, InstallUtil.exe typically doesn't spawn interactive shells, making this process chain highly suspicious. The presence of cmd.exe and powershell.exe as descendants suggests payload execution and potential lateral movement preparation.

Another telltale sign involves unusual parent-child relationships. Legitimate applications rarely spawn processes like rundll32.exe or regsvr32.exe with embedded .NET payloads. When these combinations appear, especially with obfuscated command lines, investigation is warranted.

Command-line analysis reveals additional patterns. Suspicious .NET attacks often involve base64-encoded strings, unusual parameter combinations, or references to temporary directories. For instance:

cmd InstallUtil.exe /logfile= /LogToConsole=false /U payload.dll

The /U parameter indicates uninstall mode, which InstallUtil abuses to execute arbitrary code without installing anything. Similarly, MSBuild.exe with project files containing inline tasks represents another common abuse pattern.

Memory analysis patterns also provide valuable indicators. Processes that rapidly allocate large amounts of memory or exhibit unusual memory access patterns may be hosting reflective loaders or decrypted payloads.

Hands-on practice: Try these techniques with mr7.ai's 0Day Coder for code analysis, or use mr7 Agent to automate the full workflow.

Network connection patterns following process creation can confirm malicious activity. Legitimate .NET applications rarely establish immediate outbound connections to suspicious domains or IP addresses upon launch. Correlating process creation with subsequent network events strengthens detection confidence.

Unusual working directory changes represent another red flag. Malicious .NET payloads often execute from temporary directories or user profile folders rather than expected application paths. Monitoring for processes that change their working directory to these locations helps identify suspicious activity.

Timing patterns also matter. Rapid succession of process creations, especially involving different executable types, suggests automated attack frameworks rather than legitimate user activities. Establishing baselines for normal process creation rates enables more effective anomaly detection.

Detection Strategy: Focus on process chains that combine trusted executables with suspicious descendants, unusual command-line parameters, and immediate network activity.

How to Configure Image Loading Events for Reflective Injection Detection?

Image loading events provide critical visibility into dynamic library loading that attackers exploit for reflective injection and other in-memory execution techniques. Properly configured image loading monitoring can reveal when malicious DLLs are injected into legitimate processes or when suspicious modules are loaded into memory.

Sysmon's Event ID 7 (Image Load) becomes particularly valuable when tracking reflective DLL injection. Attackers often inject malicious DLLs into trusted processes to evade detection, making image loading events essential for uncovering these activities. The key is configuring filters that capture suspicious loading patterns without generating excessive noise.

Effective image loading monitoring should focus on several critical aspects. First, track loading of modules from non-standard locations, particularly temporary directories, user profiles, or network shares. Legitimate system components rarely load from these locations, making such events worthy of investigation.

Second, monitor for unsigned or untrusted modules being loaded into privileged processes. When explorer.exe or svchost.exe loads unsigned DLLs, it often indicates successful injection attempts. Third, watch for rapid sequences of module loading, which may indicate reflective loader unpacking multiple components.

Configuration example for detecting suspicious image loads:

xml [Image blocked: No description]AppData\Local\Temp [Image blocked: No description]AppData\Roaming [Image blocked: No description]Public\Documents clrjit.dll mscorwks.dll [Image blocked: No description]C:\Windows\System32\dllhost.exe [Image blocked: No description]C:\Windows\System32\svchost.exe

This configuration captures loads from suspicious directories while excluding common legitimate patterns to reduce false positives. The inclusion of CLR-related DLLs helps track .NET runtime activities that might indicate malicious code execution.

Correlation with other events significantly enhances detection accuracy. When image loading events coincide with process access events showing memory manipulation, the likelihood of successful injection increases dramatically. Similarly, combining image load data with network connection events can reveal command and control communication from injected payloads.

Real-time analysis of image loading patterns requires efficient processing to avoid missing critical events. Implementing streaming analytics that can quickly identify suspicious loading sequences ensures timely detection of reflective injection attempts.

Advanced configurations should also consider hash-based filtering to detect known malicious modules. When combined with reputation services, hash-based detection can identify previously seen malicious DLLs regardless of their loading location or filename.

Best Practice: Configure image loading monitoring to capture loads from temporary directories and suspicious processes, then correlate with process access events for maximum detection effectiveness.

What Network Connection Patterns Reveal .NET Attack Activity?

Network connection patterns provide crucial evidence of successful .NET attack execution, particularly when distinguishing between initial compromise and post-exploitation activities. Understanding these patterns enables defenders to identify active threats and trace attack progression through compromised systems.

Command and control (C2) communication represents the most critical network pattern to detect. Successful .NET attacks typically establish outbound connections to attacker-controlled infrastructure within minutes of execution. These connections often use standard protocols like HTTP/HTTPS to blend with normal traffic, making detection challenging without proper monitoring.

Suspicious DNS queries frequently precede C2 communication establishment. Attackers often use domain generation algorithms (DGAs) or typosquatting techniques to create domains that appear legitimate but resolve to malicious infrastructure. Monitoring for high volumes of DNS queries or queries to recently registered domains can reveal beaconing attempts.

Consider this PowerShell command to extract suspicious network connections from Sysmon logs:

powershell

Extract potentially malicious network connections

Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Sysmon/Operational'; ID=3} | Where-Object { $.Properties[3].Value -like "temp" -or $.Properties[3].Value -like "appdata" -or [int]$.Properties[5].Value -gt 1024 } | Select-Object TimeCreated, @{Name='SourceProcess';Expression={$.Properties[10].Value}}, @{Name='DestinationIP';Expression={$.Properties[3].Value}}, @{Name='DestinationPort';Expression={$.Properties[5].Value}}_

This script identifies connections originating from temporary directories or using high-numbered ports, both common characteristics of malicious .NET payloads.

Comparison of legitimate versus malicious network patterns reveals distinct differences:

PatternLegitimateMalicious
Connection TimingRegular intervalsIrregular/beaconing
Port UsageStandard portsHigh-numbered ports
Domain NamesEstablished domainsRecently registered
Data VolumeConsistentBursty/sporadic
Protocol UsageApplication-specificGeneric HTTP/HTTPS

Staging and payload download activities represent another critical network pattern. Initial access tools often download additional components or second-stage payloads following successful execution. These downloads typically occur over encrypted channels to evade inspection.

Lateral movement activities generate distinctive network signatures as attackers move through networks. SMB connections to multiple hosts, WMI queries, or remote service creation all produce network traffic patterns that differ from normal administrative activities.

Exfiltration attempts create unique network patterns characterized by large data transfers, unusual timing, or connections to storage services. Modern exfiltration techniques often use cloud storage APIs or social media platforms to avoid detection.

Monitoring encrypted traffic presents additional challenges since payload contents remain hidden. However, metadata analysis including connection duration, packet sizes, and timing patterns can still reveal malicious activities even when content inspection isn't possible.

Strategic Approach: Focus on connection timing irregularities, destination port anomalies, and source process legitimacy rather than relying solely on domain reputation.

How to Create Effective Detection Rules for Donut Loaders?

Creating effective detection rules for Donut loaders requires understanding their specific operational characteristics and the artifacts they leave in system telemetry. Donut is a popular framework for creating position-independent shellcode from .NET assemblies, making detection particularly challenging due to its fileless nature.

Donut loaders typically operate through several distinct phases: initial delivery, reflective loading, payload execution, and C2 communication. Each phase generates specific telemetry patterns that can be leveraged for detection rule creation. The key is crafting rules that capture these patterns while minimizing false positives from legitimate activities.

Initial delivery often involves phishing emails or malicious websites that deliver the loader to target systems. At this stage, traditional endpoint protection may detect the delivery mechanism, but once the loader executes in memory, different detection approaches become necessary.

Reflective loading represents the core technique used by Donut loaders. This process involves injecting the payload into memory without writing it to disk, then executing it through reflective DLL loading mechanisms. The telemetry generated during this phase includes specific memory allocation patterns and unusual process behavior.

Here's a Sigma rule designed to detect Donut loader activity:

yaml title: Potential Donut Loader Execution id: 12345678-1234-1234-1234-123456789abc description: Detects potential execution of Donut loaders through suspicious process behavior status: experimental author: Security Researcher references: - https://github.com/TheWover/donut date: 2026/03/28 tags: - attack.execution - attack.t1055.002 logsource: product: windows service: sysmon detection: selection_process: EventID: 1 ParentImage|contains: - 'powershell.exe' - 'wscript.exe' - 'cscript.exe' Image|contains: - 'installutil.exe' - 'msbuild.exe' - 'regasm.exe' selection_network: EventID: 3 Initiated: 'true' SourceImage|contains: - 'installutil.exe' - 'msbuild.exe' - 'regasm.exe' DestinationPort: - 80 - 443 - 8080 - 8443 timeframe: 5m level: high

This rule combines process creation and network connection events to identify suspicious behavior patterns associated with Donut loaders. The correlation requirement helps reduce false positives by ensuring both conditions are met within a short timeframe.

Payload execution phase generates additional telemetry including memory access patterns, registry modifications, and file system interactions. Donut loaders often modify specific registry keys for persistence or configuration storage, creating additional detection opportunities.

C2 communication represents the final detection opportunity. Donut-generated payloads typically communicate with attacker infrastructure using HTTP/HTTPS protocols, often with customized user agents or specific URI patterns that can be detected through network monitoring.

Advanced detection rules should incorporate machine learning techniques to identify subtle patterns that might be missed by traditional signature-based approaches. Behavioral analysis can distinguish between legitimate and malicious .NET execution based on usage patterns and system interactions.

Tuning considerations include adjusting thresholds for acceptable behavior, incorporating environmental baselines, and regularly updating rules based on new threat intelligence. Effective detection requires continuous refinement to maintain accuracy against evolving attack techniques.

Rule Development Principle: Combine multiple telemetry sources and require temporal correlation to increase confidence while reducing false positive rates.

What Are the Best Practices for Tuning Detection Sensitivity?

Tuning detection sensitivity represents a delicate balance between catching real threats and avoiding alert fatigue from false positives. Effective tuning requires systematic analysis of detection performance, environmental baselines, and threat landscape evolution to optimize security monitoring effectiveness.

Baseline establishment forms the foundation of effective tuning. Organizations must understand their normal operational patterns including typical process creation rates, network connection frequencies, and user behavior patterns. Without accurate baselines, tuning efforts lack direction and may inadvertently disable critical detection capabilities.

Statistical analysis of historical data provides quantitative insights into normal versus anomalous behavior. Calculating mean and standard deviation for key metrics helps establish thresholds that adapt to changing operational conditions. For example, analyzing daily process creation counts can reveal natural variations that inform appropriate threshold settings.

PowerShell script for baseline calculation:

powershell

Calculate baseline metrics for process creation

$events = Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Sysmon/Operational'; ID=1} -MaxEvents 10000 $processCounts = $events | Group-Object TimeCreated -Property Hour | Select-Object Name, Count $mean = ($processCounts.Count | Measure-Object -Average).Average $stdDev = ($processCounts.Count | Measure-Object -StandardDeviation).StandardDeviation

Write-Host "Mean process creations per hour: $mean" Write-Host "Standard deviation: $stdDev" Write-Host "Recommended threshold: $($mean + (2 * $stdDev))"*

This approach establishes statistically sound thresholds that adapt to organizational needs while maintaining security effectiveness.

Threshold adjustment requires iterative refinement based on real-world performance. Starting with conservative settings and gradually increasing sensitivity as confidence grows helps prevent overwhelming security teams with false alarms while ensuring critical threats aren't missed.

Environmental factors significantly influence optimal tuning parameters. Different business units, operating hours, and seasonal variations all affect normal behavior patterns. Segmented tuning approaches that account for these differences provide more accurate detection across diverse organizational environments.

False positive reduction techniques include implementing contextual filters, correlation requirements, and reputation-based exclusions. Rather than simply lowering sensitivity, these approaches maintain detection capability while eliminating known benign activities from alerting.

Performance monitoring ensures tuning adjustments don't negatively impact system operations. Resource consumption, processing latency, and storage requirements all factor into sustainable tuning decisions. Regular performance reviews help maintain optimal balance between security effectiveness and operational efficiency.

Continuous improvement processes incorporate feedback from incident response activities, threat intelligence updates, and emerging attack trends. Regular tuning reviews ensure detection capabilities evolve alongside changing threat landscapes and organizational requirements.

Optimization Strategy: Establish statistical baselines, implement gradual threshold adjustments, and continuously refine based on real-world performance data.

Key Takeaways

• Sysmon configuration should focus on process creation, image loading, and network connection events to detect .NET-based attacks effectively • ETW providers like Microsoft-Windows-DotNETRuntime offer deep runtime insights that complement Sysmon's broader system monitoring • Suspicious process patterns include trusted executables spawning interactive shells and unusual parent-child relationships • Image loading monitoring should capture loads from temporary directories and correlate with process access events • Network connection analysis should focus on timing irregularities, port anomalies, and source process legitimacy • Detection rules for Donut loaders should combine multiple telemetry sources with temporal correlation requirements • Tuning requires statistical baselines, iterative refinement, and continuous performance monitoring

Frequently Asked Questions

Q: How much performance impact does Sysmon monitoring have on production systems?

Sysmon's performance impact varies based on configuration complexity and system activity levels. Typical deployments show 1-5% CPU overhead and minimal memory impact when properly tuned. Heavy filtering reduces overhead while maintaining security coverage.

Q: Can ETW monitoring detect encrypted C2 communications from .NET payloads?

Yes, ETW monitoring can detect encrypted C2 communications by analyzing connection timing, packet sizes, and protocol behaviors. While content inspection isn't possible, metadata analysis reveals suspicious communication patterns indicating malicious activity.

Q: What are the most common false positives when monitoring for .NET attacks?

Common false positives include legitimate software deployment tools, development environment activities, and administrative scripts. Proper baselining and contextual filtering significantly reduce these occurrences while maintaining detection effectiveness.

Q: How frequently should detection rules be updated for evolving .NET attack techniques?

Detection rules should be reviewed monthly and updated quarterly based on threat intelligence feeds and incident analysis. Critical vulnerabilities or newly discovered attack techniques require immediate rule updates and deployment.

Q: Is it possible to detect fileless .NET attacks without endpoint sensors?

Limited detection is possible through network monitoring and log analysis, but endpoint sensors provide essential telemetry for comprehensive detection. Hybrid approaches combining network and endpoint monitoring offer the most effective coverage against fileless attacks.


Automate Your Penetration Testing with mr7 Agent

mr7 Agent is your local AI-powered penetration testing automation platform. Automate bug bounty hunting, solve CTF challenges, and run security assessments - all from your own device.

Get mr7 Agent → | Get 10,000 Free Tokens →

Try These Techniques with mr7.ai

Get 10,000 free tokens and access KaliGPT, 0Day Coder, DarkGPT, and OnionGPT. No credit card required.

Start Free Today

Ready to Supercharge Your Security Research?

Join thousands of security professionals using mr7.ai. Get instant access to KaliGPT, 0Day Coder, DarkGPT, and OnionGPT.

We value your privacy

We use cookies to enhance your browsing experience, serve personalized content, and analyze our traffic. By clicking "Accept All", you consent to our use of cookies. Learn more