diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3783df8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ + +chapters/.DS_Store diff --git a/Build/Sysmon.md b/Build/Sysmon.md new file mode 100644 index 0000000..c4c63f0 --- /dev/null +++ b/Build/Sysmon.md @@ -0,0 +1,2389 @@ +![cover image](cover.png) + +# 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 + + +## 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. + +The driver is loaded by a service at system startup and a secondary service then queries the cached information. + +![Sysmon Driver Behaviour](./media/image1.png ) + +For all file system operations, the driver registers as a Minifilter driver that is attached to volumes allowing it to see all actions taken by APIs before they are processed by the file system. + +![Minifilter](./media/image2.png) + +Sysmon sets multiple callbacks on kernel objects in addition to using telemetry APIs and ETW. + +![kernel hook1](./media/image3.png) + +![kernel hook2](./media/image4.png) + +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) + +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 + +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. + +* **Sysmon64.exe** - 64bit only version. + +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 informationn. + +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 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: + +* Decompresses and saves driver and copy of itself in to **%systemroot%** + +* Registers event log manifest + +* Creates a service + +* Enables a default configuration (ProcessCreation, ProcessTermination, DriverLoad , FileCreationTimeChanged, SHA1 for Images) if no configuration file is passed using the **-c \** parameter + +The Installation process allows for some obfuscation: + +* Driver name can be changed + +* Service name can be changed + +* Sysmon binary name can be renamed. + +These obfuscation changes will also affect registry paths for the driver and processes service keys. All of the obfuscation methods are part of the installation option set. + +The installation options are: + +* Default -- Driver is installed and named SysmonDrv and service Sysmon + +```shell +sysmon.exe --i --accepteula + +``` + +* Renamed Driver -- The driver file and registry entry are renamed. Name has an 8-character limit. + +```shell +sysmon.exe -i -d +``` + +* Renamed Service -- The executable name defines the service name. + +```shell +.exe -i -d +``` + +The installation process on a x64 system with the binary named sysmon.exe that is intended to work across x64 and x86 architectures is shown below. This is important since some of the actions may cause confusion or trigger alerts on monitoring systems. + +One important thing to keep in mind when obfuscating the driver name and service name is that certain characteristics remain the same. + +* Service description remains the same. (This can be modified post-install.) + +* Driver Altitude number remains the same. + +* 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. + +* SysmonDrv - Kernel Driver Service, this service loads the Sysmon driver with an altitude number of 385201 + +The settings for each service are: + +Main Service: + +* Name: **Name of the executable (default Sysmon or Sysmon64)** + +* LogOn: **Local System** + +* Description: **System Monitor service** + +* Startup: **Automatic** + +* ImagePath: **%windir%\\\** + +Driver Service: + +* Name: **SysmonDrv unless --d \ is** + +* LogOn: **Local System** + +* Description: **System Monitor driver** + +* Startup: **Automatic** + +* 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 +``` + +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. + +```shell +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** + +``` + +SSome basic filtering can be done also from the command line. Only filtering by process name can be done for NetworkConnect, ImageLoad, and ProcessAccess via the command line. + +* **NetworkConnect** - Track network connections. + +```shell +sysmon.exe -i -c -n [] +``` + +* **ImageLoad** - DLL loading by processes. + +```shell +sysmon.exe -i -c -l [] +``` + +* **ProcessAccess** - Processes whose memory is accessed. + +```shell +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. + +```shell +sysmon.exe -u +``` + +When executed the command will run a series of steps to uninstall the service, driver and remove files for the tool. + +![Uninstall Process](./media/image8.png) + +There is an undocumented value that can be passed to the **-u** parameter of **"force"** to force the removal of the services even if a stop was not possible. + +```shell +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: + +* Keep a repository of Sysmon versions archived; Microsoft does not provide older versions for download. + +* Sysmon is very dependent on the version of the binary for its configuration. The install/upgrade script should check the binary version for: + + * Upgrade + + * Version for applying initia 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: + +```sql +SELECT * FROM CIM_Datafile WHERE (Name="c:\\Windows\\Sysmon64.exe" OR Name="c:\\Windows\\Sysmon.exe") AND version="10.0.4.1" +``` + +* Check file versions they don't match release versioning. + +* It is better to not push configuration as an XML that gets run from a share or dropped on disk with a scheduled task: + + * Credentials are left that can be recovered via DPAPI for deleted scheduled tasks. + + * The file can be read more easily by an attacker if controls are not properly placed + + * There is a higher chance of human error + + * Better to push values via GPO or other methods with file version checking. + +# 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. + +When we look at the XML representation of the schema, we see the manifest element has two attributes for versioning: + +* **schemaversion** - The version number of the schema + +* **binaryversion** - The binary version number of the compiled schema + +Under this manifest element are two main elements: + +* **configuration** - Command line switches for the executable and the filtering operators +* **events** - This section defines each event type and field we can filter on + +![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. + +The main attributes for each of the command-line options: + +* **switch** - the command line switch to use. + +* **name** - name of the switch. + +* **argument** - is the argument optional or mandatory + +![Configuration File Parameters](./media/image10.png) + +The main arguments that can be passed are: + +* **-i** : Install Sysmon + +```shell +sysmon.exe -i [configfile path] +``` + +* **-c** : apply config + +```shell +sysmon.exe -c [configfile path] +``` + +* **-u** : un-install Sysmon + +```shell +sysmon.exe -u [force] +``` + +* **-m** : Install event manifest + +```shell +sysmon.exe -m +``` + +* **-t** : Debug mode + +```shell +sysmon.exe -t [configfile path] +``` + +* **-s** : Print schema + +```shell +sysmon.exe -s [schema version] +``` + +* **-nologo** : don't show sysmon logo + +```shell +sysmon.exe -nologo +``` + +* **-accepteula** : Accepts the license agreement + +```shell + sysmon.exe -accepteula +``` + +* **--** : Resets the configuration to the default + +```shell +sysmon.exe -- +``` + +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. + +```shell +sysmon.exe -c -h +``` + +* **-r** : Check for signature certificate revocation + +```shell +sysmon.exe -c -r +``` + +* **-n** : Track network connections for specified process/processes + +```shell +sysmon.exe -c -n [] +``` + +* **-k** : Track when a specified process/processes memory are accessed + +```shell +sysmon.exe -c -k [] +``` + +* **-l** : Track modules (DLLs) loaded by a specified process/processes. + +```shell +sysmon.exe -c -k [] +``` + +* **-d** : Rename the sysmon driver during install (8 character limit) + +```shell +sysmon.exe -i -c -d +``` + +> **-g** and **--dns** switches are listed but as of the current version, they +> do not update the configuration. + +## Filter Operators + +In the filters element under configuration is the list of operators that can be used to filter against the fields of each event type. + +| **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 ";" ) + +Each of these operators execute against the value in a given field for each of the event types. + +## Event Schema + +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: + +* **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 + +## 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. + +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. + +### RuleGroups + +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) + +Remember: You can only have one single EventType per RuleGroup. Sysmon will not error if you have more than one, but only the first EventType filters will be loaded. + +In a RuleGroup element, the name attribute is not used to populate the RuleName field of an event when one is created. While it may be used for a description, XML comments are a better option. When choosing the name to go in the RuleName field, the order of precedence for RuleName is Filter -> RuleGroup name attributes. It is recommended that names be placed on the individual filters to be able to leverage the field more efficiently when filtering logs on a SIEM platform. One thing to keep in mind is that when multiple filters are in a Rule element, only the first filter name attribute is used. + +When using AND in a Rule element, the name used to populate the RuleName will be based on the order of the filters as they appear on the schema where the last matching one is the one used. When using OR in a Rule element, the name used to populate the RuleName will be the filter that matches. + +Rules are processed in the order they are placed in the configuration file. This is important because once a Rule matches and the information for that EventType is included in the Windows EventLog, no other rule will be processed against that action. Filters that are not in a Rule element will be processed in the order that they appear in the schema. This also applies to multiple filters inside a Rule where the schema order is used. + +![](./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. + +![](./media/image18.png) + +For RuleGroups, Rules and Filters use comments to organize filters and to provide information on what each filter is doing. + +![](./media/image19.png) + +Hash configurations that are deployed and keep a log of them for later +verification. + +Hash configurations that are deployed and keep a log of them for later verification. +On a system where the Sysmon service process consumes a lot of CPU resources, the number of filters and operators should be reviewed. The operators that use slightly more CPU are: + +* contains + +* contains all + +* contains any + +A method for checking applied configuration is hashing the configuration +in the registry. + + +![](./media/image20.png) + +Since getting stated can be complex, some great resources that serve as starting points for Rule development and reference include: + +* Swift On Security configuration example + + +* Olaf Hartong Sysmon Configuration Modules + + +### Configuration Tampering + +One of the actions an attacker takes is the identification of controls and logging on a system. + +Due to initial footprint and safety, most advanced attackers limit their actions to enumerate controls to the most common actions that elements that will trigger a monitoring solution. The most common methods used are: + +* Service list. + +* Process list. + +* Listing of installed applications from the registry. + +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. + + **Indicator** | **Can it be Changed** + ----------------------------| ----------------------- + |Driver Name| YES + |Service Name| YES + |Registry Config Path| YES + |Driver altitude Number| NO + |EventLog Path and Name| NO + |Sysmon Service Description| NO (Manually) + +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. + +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: + +* **ProcessCreation** + +* **ProcessTermination** + +* **DriverLoad** + +* **FileCreationTimeChanged** + +* **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: + +* Execute tasks not logged. + +* Execute tasks that would blend in with normal logged actions + +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 + +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. + +### Deployment Script + +On most of these environments, the deployment of Sysmon is managed by using scripts, with PowerShell being the most flexible one. + +An install script should + +* Check if Sysmon is installed; if not, Install. + +* If Sysmon is installed, check the version and upgrade if needed. + +* After an uninstall, ensure the registry key and files are removed before upgrading. (There have been issues in the past.) + +```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 + # Check if the version on host is the approved one. + $HostVersion = (Get-Item "C:\Windows\$($DriverName)").VersionInfo.FileVersion + if ($CurrentVersion -eq $HostVersion) { + Write-Host -Object "[+] Sysmon is current approved version." -ForegroundColor Green + } else { + # Execute upgrade process. + Write-Host -Object "[-] Sysmon needs upgrade." -ForegroundColor Red + -U + -I + } +} else { + # Execute install process. +} +``` + +### GPO Configuration Deployment + +Group Policy remains one of the most used methods in the enterprise network for the control of configuration setting. + +The following are instructions on how to create a GPO for an existing applied configuration. + +1. In the Group Policy Management Console (**gpmc.msc**) + +2. Create a new (or edit an existing) GPO and assign it to the appropriate Active Directory Organizational Unit. + +3. Right click on the GPO and select **Edit** + +4. Expand **Configuration -\> Preferences -\>Windows Settings -\> Registry** + +5. Right Click on Registry **New -\> Registry Wizard** + + ![GPO Registry](./media/image23.png){width="6.5in" height="3.3125in"} + +6. Select if local or remote machine. + +7. Navigate and select the key **HKLM\\SYSTEM\\CurrentControlSet\\Services\\SysmonDrv\\Parameters** and all parameters under it. + + ![GPO Select Settings](./media/image24.png) + +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. + +![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 + +|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 Error](./media/image28.png) + + +### Service State Change + +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. + +Fields for the event are: + +* **UtcTime**: Time the service state changed. + +* **State**: Started or Stopped + +* **Version**: Version of the Sysmon binary + +* **SchemaVersion**: Schema Version of the Sysmon binary. + +Example: + +![stop example](./media/image29.png) + +![start example](./media/image30.png) + +## Process Events + +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. + +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. + +![ProcessGUID Source](./media/image31.png) + +When a user logs onto on a modern version of Windows (Windows 2016/10) +they will have 2 Logon IDs assigned if: + +* User is a member of local Administrator Group. + +* UAC (User Access Control) is enabled. + +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. + +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. + +![ProcessGUID Relation](./media/image32.png) + +The only Event Types that will not reference a ProcessGuid or one of its +derived names are + +* WMI events + +* 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. + +![Image Relation](./media/image33.png) + + +### Process Creation + +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 fields on a process creation event are: + +* **ProcessGuid** -- Unique process GUID generated by Sysmon. + +* **ProcessId** -- Process ID represented as a integer number. + +* **Image** -- Full path of the executable image that was executed. + +* **FileVersion** -- File version filed in the image metadata. + +* **Description** -- Description field in the image metadata. + +* **Product** -- Product field in the image metadata. + +* **Company** - Company field in the image metadata. + +* **OriginalFileName** -- Original image name if renamed. + +* **CommandLine** -- Command line that executed the image. + +* **CurrentDirectory** -- Directory under which the image was + executed. + +* **User** - Name of the account who created the process (child) . It + usually contains domain name and user name + +* **LogonGuid** - Logon GUID of the user who created the new process. + +* **LogonId** -Login ID of the user who created the new process. + +* **TerminalSessionId** - ID of the session the user belongs to + +* **IntegrityLevel** - Integrity label assigned to a process + +* **Hashes** - Full hash of the file with the algorithms in the + HashType field. + +* **ParentProcessGuid** - ProcessGUID of the process that + spawned/created the main process (child) + +* **ParentProcessId** - Process ID of the process that spawned/created + the main process (child) + +* **ParentImage -** File path that spawned/created the main process. + +* **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 + +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: + +* **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, 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. + +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. + +Sysmon generates this event using ObRegisterCallbacks leveraging its +driver. The main 2 filtering fields recommended are: + +* **TargetImage** - File path of the executable being accessed by + another process. + +* **GrantedAccess** - The access flags (bitmask) associated with the + process rights requested for the target process + +As a minimum it is recommended to filter including critical processes, +as a minimum: + +* C:\\Windows\\system32\\lsass.exe + +* C:\\Windows\\system32\\csrss.exe + +* C:\\Windows\\system32\\wininit.exe + +* C:\\Windows\\system32\\winlogon.exe + +* C:\\Windows\\system32\\services.exe + +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. + +|Access | Mask | +|--------------------------------------|------------ +| PROCESS\_CREATE\_PROCESS |0x0080| +| PROCESS\_CREATE\_THREAD |0x0002| +| PROCESS\_DUP\_HANDLE |0x0040| +| PROCESS\_SET\_INFORMATION |0x0200| +| PROCESS\_SET\_QUOTA |0x0100| +| PROCESS\_QUERY\_LIMITED\_INFORMATION |0x1000| +| SYNCHRONIZE |0x00100000| +| PROCESS\_QUERY\_INFORMATION |0x0400| +| PROCESS\_SUSPEND\_RESUME |0x0800| +| PROCESS\_TERMINATE |0x0001| +| PROCESS\_VM\_OPERATION |0x0008| +| PROCESS\_VM\_READ |0x0010| +| PROCESS\_VM\_WRITE |0x0020| + +The PSGumshoe PowerShell module has a function for creating and parsing +mask strings. + + +The fields for the even are: + +* **RuleName**: Rule that triggered the event + +* **UtcTime**: Time in UTC when event was created + +* **SourceProcessGUID**: Process Guid of the source process that + opened another process. + +* **SourceProcessId**: Process ID used by the OS to identify the + source process that opened another process. + +* **SourceThreadId**: ID of the specific thread inside of the source + process that opened another process + +* **SourceImage**: File path of the source process that created a + thread in another process + +* **TargetProcessGUID**: Process Guid of the target process + +* **TargetProcessId**: Process ID used by the OS to identify the + target process + +* **TargetImage**: File path of the executable of the target process + +* **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 + +Example: + +```xml + + + + + + + + C:\Windows\system32\lsass.exe + + 0x1FFFFF + + + + C:\Windows\system32\lsass.exe + + 0x1F1FFF + + + + C:\Windows\system32\lsass.exe + + 0x1010 + + + + C:\Windows\system32\lsass.exe + + 0x143A + + + + + + C:\Windows\system32\csrss.exe + 0x1F1FFF + + + + C:\Windows\system32\wininit.exe + 0x1F1FFF + + + + C:\Windows\system32\winlogon.exe + 0x1F1FFF + + + + 0x1F1FFF + C:\Windows\system32\services.exe + + + 0x0810 + + + + + 0x0800 + 0x800 + + + + 0x0820 + 0x820 + + + + + +``` + +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 + +## File Events + +### 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 defender to filter for: + +* Dropping of files for later execution (PowerShell, Office Apps, certutil.exe) + +* Modification of system configurations (Scheduled Tasks, WMI) + +* Detection of malicious behaviors that create temporary or log files (.Net compile and run, DotNet2JS) + +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. + +![minifilter](./media/image36.png) + +The file creation 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 created the file + +* **ProcessId**: Process ID used by the OS to identify the process that created the file (child) + +* **Image**: File path of the process that created the file + +* **TargetFilename**: Name of the file that was created + +* **CreationUtcTime**: File creation time + +Example monitoring for script file creation by extension: + +```XML + + + + + + + .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 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. + +The fields for the event: + +* RuleName: Name of rule that triggered the event + +* UtcTime: Time in UTC when the event was created + +* ProcessGuid: Process GUID of the process that changed the file creation time + +* ProcessId: Process ID used by the OS to identify the process changing the file creation time + +* Image: File path of the process that changed the file creation time + +* TargetFilename: Full path name of the file + +* CreationUtcTime: New creation time of the file + +* PreviousCreationUtcTime: Previous creation time of the file + +Example: + +```xml + + + + + + + C:\Users + + + + + + + + + + OneDrive.exe + C:\Windows\system32\backgroundTaskHost.exe + + setup + install + Update\ + redist.exe + msiexec.exe + TrustedInstaller.exe + + + + + +``` + +### 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. + +Each record in NTFS on a drive is subdivided into a list of variable length attributes: + +* \$STANDARD\_INFORMATION + +* \$FILE\_NAME + +* \$DATA + +* \$INDEX\_ROOT + +* \$BITMAP + +* \$INDEX\_ALLOCATION + +* \$ATTRIBUTE\_LIST + +Alternate Data Streams (ADS) are implemented by having multiple \$Data +attributes + +* The Default data stream is unnamed + +* Alternate streams are named ones. + +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 with a second named stream: + +![stream2](./media/image42.png) + +Some execution examples: + +* Execution Rundll32 example + +* Cscript Example + +* PowerShell Example + +More execution examples at + by +Oddvar Moe + +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. + +We can use PowerShell Get-Item and Get-Content cmdlets to check is a Zone.Identifier stream exist and show its content. + +![process](./media/image63.png) + + +The fields for the event: + +* **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. + + +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. + +![process](./media/image43.png) + +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. + +```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 + + + + +``` +### 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: + +* Dropper / stager that removes itself after execution (T1193 or T1064 and loads more) or attackers doing it manually + +* Wiper software (T1485 and T1488) + +* Ransomware (T1486) + +![minifilter](./media/image36.png) + +#### Archive directory + +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. + +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```. + +``` +PS C:\> (Get-Acl C:\Sysmon\).access + + +FileSystemRights : FullControl +AccessControlType : Allow +IdentityReference : NT AUTHORITY\SYSTEM +IsInherited : False +InheritanceFlags : None +PropagationFlags : None +``` + +#### Event information + +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 deletec the file + +* **ProcessId**: Process ID used by the OS to identify the process that deleted the file (child) + +* **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 saved file in the ArchiveDirectory + +* **Archived**: States whether the archival action was succesful + +Example monitoring for script file creation by extension: + +```XML + +SysmonIsAwesome + + + + + + \Downloads\ + + \Content.Outlook\ + \AppData\Local\Temp\ + + \AppData\Local\Microsoft\ + C:\Windows\Temp + + + .exe;.ps1;.js;.xls;.xlsm;.docm + + + + +``` + + +## 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. + +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. + +Sysmon will generate a events + +* **EventID 17** when a named pipe server is created. + +* **EventID 18** when a client connects to a named piper server. + +For named pipes there are 2 approaches that can be taken: + +* Include all events and exclude known good. + +* 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. + +The process for PipeName values should be constant process. + +![process](./media/image45.png) + +Initial rule for collecting PipeEvent events + +```xml + + + + + + + + + + + + + + + + + + +``` + +Collect unique PipeName field values for building filters + +The fields for the Pipe Create Event are: + +* **RuleName**: Name of rule that triggered the event. + +* **EventType**: ***[CreatePipe]{.underline}*** + +* **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 are: + +* **RuleName**: Name of rule that triggered the event. + +* **EventType**: ***[ConnectPipe]{.underline}*** + +* **UtcTime**: Time in UTC when event was created + +* **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 + +* **PipeName**: Name of the pipe connected + +* **Image**: File path of the process that connected the pipe + +Example excluding known good Pipe Names + +```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 + + + + + +``` + +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. + + +## 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 provide code signing information allowing filtering on those fields. Sysmon can also check if a certificate the driver signed has been revoked. + +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. + +![process](./media/image48.png) + +Initial rule for collecting DriverLoad events + +```xml + + + + + + + + + + + + + + + + + + +``` + +Collect unique Signature field values for building filters + +The event fields are: + +* **RuleName**: Name of rule that triggered the event. + +* **UtcTime**: Time in UTC when event was created + +* **ImageLoaded**: File path of the driver loaded + +* **Hashes**: Hashes captured by Sysmon driver + +* **Signed**: Is the driver loaded signed + +* **Signature**: Signer name of the driver + +* **SignatureStatus**: Status of the signature + +Example filtering out drivers signed by Microsoft, Intel and VMware for +a VDI environment + +```xml + + + + + + + + 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 + +* **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. + +Sysmon uses abbreviated versions of Registry root key names, with the following mappings: + +|**Key name** |**Abbreviation** | +|---------------------------------------------|--------------------------------- +| HKEY\_LOCAL\_MACHINE |HKLM| +| HKEY\_USERS |HKU| +| HKEY\_LOCAL\_MACHINE\\System\\ControlSet00x |HKLM\\System\\CurrentControlSet| +| HKEY\_LOCAL\_MACHINE\\Classes |HKCR| + +Registry Add/Delete Fields: + +* **RuleName**: Name of rule that triggered the event + +* **UtcTime**: Time in UTC when event was created + +* **EventType**: CreateKey or DeleteKey + +* **ProcessGuid**: Process GUID of the process that created or deleted a registry key + +* **ProcessId**: Process ID used by the OS to identify the process that created or deleted a registry key + +* **Image**: File path of the process that created or deleted a registry key + +* **TargetObject**: Complete path of the registry key + +Registry Set Value Fields: + +* **RuleName**: Name of rule that triggered the event + +* **UtcTime**: Time in UTC when event was created + +* **EventType**: SetValue + +* **ProcessGuid**: Process GUID of the process that modified a registry value + +* **ProcessId**: Process ID used by the OS to identify the process that modified a registry value + +* **Image**: File path of the process that modified a registry value + +* **TargetObject**: Complete path of the modified registry key + +* **Details**: Details added to the registry key + +Registry Rename Fields: + +* **RuleName**: Name of rule that triggered the event + +* **UtcTime**: Time in UTC when event was created + +* **EventType**: RenameKey + +* **ProcessGuid**: Process GUID of the process that renamed a registry value and key + +* **ProcessId**: Process ID used by the OS to identify the process that renamed a registry value and key + +* **Image**: File path of the process that renamed a registry value and key + +* **TargetObject**: Complete path of the renamed registry key + +* **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. + +Default key values are named \"\\(Default)\" + +When filtering for keys or values in HKCU, use **contains** or **ends with** when filtering against **TargetObject** since the SID of the user is appended after the Hive name. + +![HKCU Test](./media/image51.png) + +![HKCU Test Event](./media/image52.png) + +Since the value name is appended when specifying a registry path in **TargetObject**, where we also want to catch modification of values under the key, the **contains** operator is better suited than **ends with**. For value events, the **Detail** element of the event will contain the type of value. + +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 + +```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 + + + + +``` + +## 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. + +The 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 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 + +* **ImageLoaded**: Path of the image loaded + +* **FileVersion**: Version of the image loaded + +* **Description**: Description of the image loaded + +* **Product**: Product name the image loaded belongs to + +* **Company**: Company name the image loaded belongs to + +* **OriginalFileName**: OriginalFileName from the PE header, added on compilation + +* **Hashes**: Full hash of the file with the algorithms in the HashType field + +* **Signed**: State whether the image loaded is signed + +* **Signature**: The signer name + +* **SignatureStatus**: status of the signature + +Example of libraries leveraged by attackers + +```xml + + + + + + + + jscript9.dll + mshta.exe + + + + wshom.ocx + scrrun.dll + vbscript.dll + + + + System.Management.Automation.ni.dll + System.Management.Automation.dll + + + + scrobj.dll + + + + + +``` + +## 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 confifuration file. + +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. + +The fields for the event are: + +* **RuleName**: Name of rule that triggered the event + +* **UtcTime**: Time in UTC when event was created + +* **ProcessGuid**: Process GUID of the process that made the network connection + +* **ProcessId**: Process ID used by the OS to identify the process that made the network connection + +* **Image**: File path of the process that made the network connection + +* **User**: Name of the account who made the network connection + +* **Protocol**: Protocol being used for the network connection + +* **Initiated**: Indicated process-initiated TCP connection + +* **SourceIsIpv6**: Is the source IP an Ipv6 + +* **SourceIp**: Source IP address that made the network connection + +* **SourceHostname**: DNS name of the host that made the network connection + +* **SourcePort**: Source port number + +* **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 tracking connections for attacker "Living off the land" + +```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 + + + + +``` + +## 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. + +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 of use/abuse of CreateRemoteThread + +* Use **OpenProcess( )** to open a target process. + +* Use **VirtualAllocEx( )** allocate a chunk of memory in the process. + +* Use **WriteProcessMemory( )** write the payload to the newly + allocated section. + +* User **CreateRemoteThread( )** to create a new thread in the remote + process to execute the shellcode. + +There are multiple Process Injection techniques, Sysmon monitors for the +most common one used. The infographic from + + +Illustrates the different techniques. + +![process injection infograph](./media/image57.png) + +The fields for the event are: + +* **RuleName**: Name of rule that triggered the event. + +* **UtcTime**: Time in UTC when event was created + +* **SourceProcessGuid**: Process Guid of the source process that + created a thread in another process + +* **SourceProcessId**: Process ID used by the OS to identify the + source process that created a thread in another process + +* **SourceImage**: File path of the source process that created a + thread in another process + +* **TargetProcessGuid**: Process Guid of the target process + +* **TargetProcessId**: Process ID used by the OS to identify the + target process + +* **TargetImage**: File path of the target process + +* **NewThreadId**: Id of the new thread created in the target process + +* **StartAddress**: New thread start address + +* **StartModule**: Start module determined from thread start address + mapping to PEB loaded module list + +* **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. + +![process](./media/image58.png) + +Example where known processes that use the API call are excluded + +```xml + + + + + + + + + Google\Chrome\Application\chrome.exe + + + C:\Windows\System32\wbem\WmiPrvSE.exe + + + C:\Windows\System32\svchost.exe + + + C:\Windows\System32\wininit.exe + + + C:\Windows\System32\csrss.exe + + + C:\Windows\System32\services.exe + + + C:\Windows\System32\winlogon.exe + + + C:\Windows\System32\audiodg.exe + + + C:\windows\system32\kernel32.dll + + + + + +``` + + +## 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. + +The fields for the event are: + +* **RuleName**: Name of rule that triggered the event + +* **UtcTime**: Time in UTC when event was created + +* **ProcessGuid**: Process GUID of the process that conducted reading operations from the drive + +* **ProcessId**: Process ID used by the OS to identify the process that conducted reading operations from the drive + +* **Image**: File path of the process that conducted reading operations from the drive + +* **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 + +![collect all](./media/image60.png) + +## 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 + +The fields for the event are: + +* **RuleName**: Name of rule that triggered the event. + +* **UtcTime**: Time in UTC when event was created + +* **ProcessGuid**: Process Guid of the process that made the DNS query + +* **ProcessId**: Process ID of the process that made the DNS query + +* **QueryName**: DNS name that was queries + +* **QueryStatus**: Query result status code + +* **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. + +```xml + + + * + + + + + + + + + .mozaws.net + + + .mozilla.com + + + .mozilla.net + + + .mozilla.org + + + + + clients1.google.com + + + clients2.google.com + + + clients3.google.com + + + clients4.google.com + + + clients5.google.com + + + clients6.google.com + + + safebrowsing.googleapis.com + + + + + + -pushp.svc.ms + + + .b-msedge.net + + + + .bing.com + + + .hotmail.com + + + .live.com + + + .live.net + + + .s-microsoft.com + + + .microsoft.com + + + .microsoftonline.com + + + .microsoftstore.com + + + .ms-acdc.office.com + + + .msedge.net + + + .msn.com + + + .msocdn.com + + + .skype.com + + + .skype.net + + + .windows.com + + + .windows.net.nsatc.net + + + .windowsupdate.com + + + .xboxlive.com + + + login.windows.net + + + + + +``` + + +## 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. + +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) + +* **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 + +* **Consumer** - An action to take upon triggering the filter + +* **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. + +Fields for the Filter creation, modification, or deletion are: + +* **RuleName**: Rule name for filter + +* **EventType**: Will always be *WmiFilterEvent* + +* **UtcTime**: Time event happened + +* **Operation**: Created, modified or deleted + +* **User**: User that performed the action + +* **EventNamespace**: WMI Namespace where object was created + +* **Name**: Name of the filter + +* **Query**: Query defined for the filter + +The fields for Consumer creation, modification, or deletion are: + +* **RuleName**: Rule name for filter + +* **EventType**: Will always be *WmiConsumerEvent* + +* **UtcTime**: Time event happened + +* **Operation**: Created, modified, or deleted + +* **User**: User that performed the action + +* **Name**: Name of the consumer + +* **Type**: Type of consumer + +* **Destination**: Command or Script being executed + +The fields for filter to consumer binding are: + +* **RuleName**: Rule name for filter + +* **EventType**: Will always be *WmiBindingEvent* + +* **UtcTime**: Time event happened + +* **Operation**: Created, modified, or deleted + +* **User**: User that performed the action + +* **Consumer**: Consumer 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, +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) + +It is recommended to log all instances of this event type. + +```XML + + + * + + + + + + + + +``` diff --git a/Build/bullet_style.tex b/Build/bullet_style.tex new file mode 100644 index 0000000..be0d10a --- /dev/null +++ b/Build/bullet_style.tex @@ -0,0 +1,14 @@ +% https://stackoverflow.com/questions/22156999/how-to-change-the-style-of-bullets-in-pandoc-markdown + +\usepackage{enumitem} +\usepackage{amsfonts} + +\setlist[itemize,1]{label=$\bullet$} +\setlist[itemize,2]{label=$\circ$} +\setlist[itemize,3]{label=$\star$} + +%% \setlist[itemize,2]{label=$\diamond$} +%% \setlist[itemize,1]{label=$\star$} +%% \setlist[itemize,1]{label=$\bullet$} +%% \setlist[itemize,1]{label=$\checkmark$} + diff --git a/Build/chapter_break.tex b/Build/chapter_break.tex new file mode 100644 index 0000000..5954354 --- /dev/null +++ b/Build/chapter_break.tex @@ -0,0 +1,10 @@ +%% 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 +\usepackage{sectsty} +\sectionfont{\clearpage} + +% accepted answer gave error +%\usepackage{titlesec} +%\newcommand{\sectionbreak}{\clearpage} + diff --git a/Build/inline_code.tex b/Build/inline_code.tex new file mode 100644 index 0000000..fbb5952 --- /dev/null +++ b/Build/inline_code.tex @@ -0,0 +1,13 @@ +%% https://stackoverflow.com/questions/40975004/pandoc-latex-change-backtick-highlight +\usepackage{fancyvrb,newverbs,xcolor} + +%\definecolor{Light}{gray}{.90} +%% https://martin-thoma.com/colors-in-latex/ +%% https://en.wikibooks.org/wiki/LaTeX/Colors +\definecolor{Light}{HTML}{F4F4F4} + +\let\oldtexttt\texttt +\renewcommand{\texttt}[1]{ + \colorbox{Light}{\oldtexttt{#1}} +} + diff --git a/Build/listings-setup.tex b/Build/listings-setup.tex new file mode 100644 index 0000000..933439f --- /dev/null +++ b/Build/listings-setup.tex @@ -0,0 +1,113 @@ +\lstset{ + basicstyle=\ttfamily, + numbers=left, + numberstyle=\footnotesize, + stepnumber=1, + numbersep=5pt, + backgroundcolor=\color[RGB]{248,248,248}, + showspaces=false, + showstringspaces=false, + showtabs=false, + tabsize=2, + captionpos=b, + breaklines=true, + breakatwhitespace=true, + breakautoindent=true, + escapeinside={\%*}{*)}, + linewidth=\textwidth, + basewidth=0.5em, + postbreak=\mbox{\textcolor{red}{$\hookrightarrow$}\space}, +} + +\definecolor{maroon}{rgb}{0.5,0,0} +\definecolor{darkgreen}{rgb}{0,0.5,0} + +\lstdefinelanguage{XML} +{ + basicstyle=\ttfamily, + morestring=[s]{"}{"}, + morecomment=[s]{?}{?}, + morecomment=[s]{!--}{--}, + commentstyle=\color{darkgreen}, + moredelim=[s][\color{black}]{>}{<}, + moredelim=[s][\color{red}]{\ }{=}, + stringstyle=\color{blue}, + identifierstyle=\color{maroon} +} + +\definecolor{dkgreen}{rgb}{0,0.6,0} +\definecolor{ltgray}{rgb}{0.5,0.5,0.5} + +\usepackage{listings} +\lstset{% + backgroundcolor=\color{white}, + basicstyle=\footnotesize, + breakatwhitespace=false, + breaklines=true, + captionpos=b, + commentstyle=\color{dkgreen}, + deletekeywords={...}, + escapeinside={\%*}{*)}, + extendedchars=true, + frame=single, + keepspaces=true, + keywordstyle=\color{blue}, + language=SQL, + morekeywords={*,modify,MODIFY,...}, + numbers=left, + numbersep=15pt, + numberstyle=\tiny, + rulecolor=\color{ltgray}, + showspaces=false, + showstringspaces=false, + showtabs=false, + stepnumber=1, + tabsize=4, + title=\lstname +} + +\lstdefinelanguage{powershell}{ + morekeywords={Add-Content,Add-PSSnapin,Clear-Content,% + Clear-History,Clear-Host,Clear-Item,% + Clear-ItemProperty,Clear-Variable,% + Compare-Object,Connect-PSSession,ConvertFrom-String,% + Convert-Path,Copy-Item,Copy-ItemProperty,% + Disable-PSBreakpoint,Disconnect-PSSession,% + Enable-PSBreakpoint,Enter-PSSession,Exit-PSSession,% + Export-Alias,Export-Csv,Export-PSSession,ForEach-Object,% + Format-Custom,Format-Hex,Format-List,Format-Table,% + Format-Wide,Get-Alias,Get-ChildItem,Get-Clipboard,% + Get-Command,Get-ComputerInfo,Get-Content,Get-History,% + Get-Item,Get-ItemProperty,Get-ItemPropertyValue,Get-Job,% + Get-Location,Get-Member,Get-Module,Get-Process,% + Get-PSBreakpoint,Get-PSCallStack,Get-PSDrive,Get-PSSession,% + Get-PSSnapin,Get-Service,Get-TimeZone,Get-Unique,Get-Variable,% + Get-WmiObject,Group-Object,help,Import-Alias,Import-Csv,% + Import-Module,Import-PSSession,Invoke-Command,Invoke-Expression,% + Invoke-History,Invoke-Item,Invoke-RestMethod,Invoke-WebRequest,% + Invoke-WmiMethod,Measure-Object,mkdir,Move-Item,Move-ItemProperty,% + New-object,New-Alias,New-Item,New-Module,New-PSDrive,New-PSSession,% + New-PSSessionConfigurationFile,New-Variable,Out-GridView,% + Out-Host,Out-Printer,Pop-Location,powershell_ise.exe,% + Push-Location,Receive-Job,Receive-PSSession,Remove-Item,% + Remove-ItemProperty,Remove-Job,Remove-Module,Remove-PSBreakpoint,% + Remove-PSDrive,Remove-PSSession,Remove-PSSnapin,Remove-Variable,% + Remove-WmiObject,Rename-Item,Rename-ItemProperty,Resolve-Path,% + Resume-Job,Select-Object,Select-String,Set-Alias,Set-Clipboard,% + Set-Content,Set-Item,Set-ItemProperty,Set-Location,% + Set-PSBreakpoint,Set-TimeZone,Set-Variable,Set-WmiInstance,% + Show-Command,Sort-Object,Start-Job,Start-Process,Start-Service,% + Start-Sleep,Stop-Job,Stop-Process,Stop-Service,Suspend-Job,% + Tee-Object,Trace-Command,Wait-Job,Where-Object,Write-Output% + }, + morekeywords={Do,Else,For,ForEach,Function,If,In,Until,While}, + alsodigit={-}, + sensitive=false, + morecomment=[l]{\#}, + morecomment=[n]{<\#}{\#>}, + morestring=[b]{"}, + morestring=[b]{'}, + morestring=[s]{@'}{'@}, + morestring=[s]{@"}{"@} +} + diff --git a/Build/md2pdf.sh b/Build/md2pdf.sh new file mode 100644 index 0000000..4182803 --- /dev/null +++ b/Build/md2pdf.sh @@ -0,0 +1,60 @@ +#!/bin/bash +# Script based on https://learnbyexample.github.io/tutorial/ebook-generation/customizing-pandoc/ + +Help() +{ + # Display Help + echo "Generate guide PDF from a master MarkDown file." + echo + echo "Syntax: md2pdf.sh ./Build/ " + echo + exit +} + +while getopts ":h" option; do + case $option in + h | *) # display Help + Help + exit;; + esac +done + +if [ -z "$1" ] +then + Help + exit +fi + +SCRIPT=$(readlink -f "$0") +SCRIPTPATH=$(dirname "$SCRIPT") +echo -e "\e[1;32m Running Pandoc to generate the LaTex file. \e[0m" +pandoc "$1" \ + -f gfm \ + --toc \ + --listings \ + --include-in-header ${SCRIPTPATH}/Build/chapter_break.tex \ + --include-in-header ${SCRIPTPATH}/Build/inline_code.tex \ + --include-in-header ${SCRIPTPATH}/Build/bullet_style.tex \ + --include-in-header ${SCRIPTPATH}/Build/pdf_properties.tex \ + --include-in-header ${SCRIPTPATH}/Build/listings-setup.tex \ + --highlight-style ${SCRIPTPATH}/Build/pygments.theme \ + -V toc-title='Table of contents' \ + -V linkcolor:blue \ + -V geometry:a4paper \ + -V geometry:margin=2cm \ + -V mainfont="DejaVu Serif" \ + -V monofont="DejaVu Sans Mono" \ + --pdf-engine=xelatex \ + -o /tmp/temp.tex + +echo -e "\e[1;32m Running Perl to format the output. \e[0m" +fn="${2%.*}" + +perl -0777 -pe 's/begin\{document\}\n\n\K(.*?^\}$)(.+?)\n/$2\n\\thispagestyle{empty}\n\n$1\n/ms' /tmp/temp.tex > ${SCRIPTPATH}/${fn}.tex + +echo -e "\e[1;32m Generating PDF. \e[0m" +xelatex ${SCRIPTPATH}/${fn}.tex > ${SCRIPTPATH}/pdfgen.log + +echo -e "\e[1;32m Cleanning temp files. \e[0m" +rm /tmp/temp.tex "$fn".{tex,toc,aux,log} + diff --git a/metadata.yml b/Build/metadata.yml similarity index 100% rename from metadata.yml rename to Build/metadata.yml diff --git a/pandoc.css b/Build/pandoc.css similarity index 100% rename from pandoc.css rename to Build/pandoc.css diff --git a/Build/pdf_properties.tex b/Build/pdf_properties.tex new file mode 100644 index 0000000..f27538b --- /dev/null +++ b/Build/pdf_properties.tex @@ -0,0 +1,11 @@ +% https://tex.stackexchange.com/questions/23235/eliminate-edit-pdf-properties-added-by-pdflatex + +\usepackage{hyperref} + +\hypersetup{ + pdftitle={Sysmon Community Guide}, + pdfauthor={Carlo Perez}, + pdfsubject={Sysinternals Sysmon}, + pdfkeywords={Sysmon} +} + diff --git a/Build/pygments.theme b/Build/pygments.theme new file mode 100644 index 0000000..338a12c --- /dev/null +++ b/Build/pygments.theme @@ -0,0 +1,211 @@ +{ + "text-color": null, + "background-color": "#f8f8f8", + "line-number-color": "#aaaaaa", + "line-number-background-color": null, + "text-styles": { + "Other": { + "text-color": "#007020", + "background-color": null, + "bold": false, + "italic": false, + "underline": false + }, + "Attribute": { + "text-color": "#7d9029", + "background-color": null, + "bold": false, + "italic": false, + "underline": false + }, + "SpecialString": { + "text-color": "#bb6688", + "background-color": null, + "bold": false, + "italic": false, + "underline": false + }, + "Annotation": { + "text-color": "#60a0b0", + "background-color": null, + "bold": true, + "italic": true, + "underline": false + }, + "Function": { + "text-color": "#06287e", + "background-color": null, + "bold": false, + "italic": false, + "underline": false + }, + "String": { + "text-color": "#4070a0", + "background-color": null, + "bold": false, + "italic": false, + "underline": false + }, + "ControlFlow": { + "text-color": "#007020", + "background-color": null, + "bold": true, + "italic": false, + "underline": false + }, + "Operator": { + "text-color": "#666666", + "background-color": null, + "bold": false, + "italic": false, + "underline": false + }, + "Error": { + "text-color": "#ff0000", + "background-color": null, + "bold": true, + "italic": false, + "underline": false + }, + "BaseN": { + "text-color": "#40a070", + "background-color": null, + "bold": false, + "italic": false, + "underline": false + }, + "Alert": { + "text-color": "#ff0000", + "background-color": null, + "bold": true, + "italic": false, + "underline": false + }, + "Variable": { + "text-color": "#19177c", + "background-color": null, + "bold": false, + "italic": false, + "underline": false + }, + "BuiltIn": { + "text-color": null, + "background-color": null, + "bold": false, + "italic": false, + "underline": false + }, + "Extension": { + "text-color": null, + "background-color": null, + "bold": false, + "italic": false, + "underline": false + }, + "Preprocessor": { + "text-color": "#bc7a00", + "background-color": null, + "bold": false, + "italic": false, + "underline": false + }, + "Information": { + "text-color": "#60a0b0", + "background-color": null, + "bold": true, + "italic": true, + "underline": false + }, + "VerbatimString": { + "text-color": "#4070a0", + "background-color": null, + "bold": false, + "italic": false, + "underline": false + }, + "Warning": { + "text-color": "#60a0b0", + "background-color": null, + "bold": true, + "italic": true, + "underline": false + }, + "Documentation": { + "text-color": "#ba2121", + "background-color": null, + "bold": false, + "italic": true, + "underline": false + }, + "Import": { + "text-color": null, + "background-color": null, + "bold": false, + "italic": false, + "underline": false + }, + "Char": { + "text-color": "#4070a0", + "background-color": null, + "bold": false, + "italic": false, + "underline": false + }, + "DataType": { + "text-color": "#902000", + "background-color": null, + "bold": false, + "italic": false, + "underline": false + }, + "Float": { + "text-color": "#40a070", + "background-color": null, + "bold": false, + "italic": false, + "underline": false + }, + "Comment": { + "text-color": "#9c9c9c", + "background-color": null, + "bold": false, + "italic": false, + "underline": false + }, + "CommentVar": { + "text-color": "#60a0b0", + "background-color": null, + "bold": true, + "italic": true, + "underline": false + }, + "Constant": { + "text-color": "#880000", + "background-color": null, + "bold": false, + "italic": false, + "underline": false + }, + "SpecialChar": { + "text-color": "#4070a0", + "background-color": null, + "bold": false, + "italic": false, + "underline": false + }, + "DecVal": { + "text-color": "#40a070", + "background-color": null, + "bold": false, + "italic": false, + "underline": false + }, + "Keyword": { + "text-color": "#007020", + "background-color": null, + "bold": true, + "italic": false, + "underline": false + } + } +} diff --git a/README.md b/README.md index 5f45076..b50cb64 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,12 @@ -

- +

# TrustedSec Sysmon Community Guide - -

Creative Commons License

This work is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/), please attribute to TrustedSec LLC - ###### You are free to: **Share** — copy and redistribute the material in any medium or format. @@ -19,53 +15,68 @@ This work is licensed under a [Creative Commons Attribution-ShareAlike 4.0 Inter The authors encourage you to redistribute this content as widely as possible, but require that you give credit to the primary authors below, and that you notify us on GitHub of any improvements you make. - Table of Contents ================= -* [What is Sysmon](./what-is-sysmon.md) +* [What is Sysmon](./chapters/what-is-sysmon.md) + +* Sysmon on Windows + + * [The Sysmon Driver](./chapters/the-sysmon-driver.md) -* [The Sysmon Driver](./the-sysmon-driver.md) + * [Install and Configuration](./chapters/install_windows.md) -* [Install and Configuration](./install-and-configuration.md) +* Sysmon on Linux + + * [sysinternalsEBPF](./chapters/eBPF.md) + + * [Install and Configuration](./chapters/install_linux.md) + +* [Configuration](./chapters/configuration.md) * Sysmon Events - * [Process Events](./process-events.md) + * [Process Events](./chapters/process-events.md) - * [Process Creation](./process-creation.md) + * [Process Creation](./chapters/process-creation.md) - * [Process Termination](./process-termination.md) + * [Process Termination](./chapters/process-termination.md) - * [Process Access](./process-access.md) + * [Process Access](./chapters/process-access.md) * File Events - * [File Create](./file-create.md) + * [File Create](./chapters/file-create.md) + + * [File Create Time Change](./chapters/file-create-time-change.md) - * [File Create Time Change](./file-create-time-change.md) + * [File Stream Creation Hash](./chapters/file-stream-creation-hash.md) - * [File Stream Creation Hash](./file-stream-creation-hash.md) - - * [File Delete](./file-delete.md) + * [File Delete](./chapters/file-delete.md) - * [Named Pipes](./named-pipes.md) + * [File Delete Detected](./chapters/file_delete_detected.md) - * [Driver Loading](./driver-loading.md) + * [Named Pipes](./chapters/named-pipes.md) - * [Registry Actions](./registry-actions.md) + * [Driver Loading](./chapters/driver-loading.md) - * [Image Loading](./image-loading.md) + * [Registry Actions](./chapters/registry-actions.md) - * [Network Connections](./network-connections.md) + * [Image Loading](./chapters/image-loading.md) - * [Create Remote Thread](./create-remote-thread.md) + * [Network Connections](./chapters/network-connections.md) - * [Raw Access Read](./raw-access-read.md) + * [Create Remote Thread](./chapters/create-remote-thread.md) - * [DNS Query](./dns-query.md) + * [Raw Access Read](./chapters/raw-access-read.md) - * [WMI Events](./WMI-events.md) + * [DNS Query](./chapters/dns-query.md) + + * [WMI Events](./chapters/WMI-events.md) + + * [Clipboard Capture](./chapters/clipboard-capture.md) + + * [Process Image Tampering](./chapters/process-tampering.md) ## Current State: diff --git a/Sysmon.md b/chapters/Sysmon.md similarity index 74% rename from Sysmon.md rename to chapters/Sysmon.md index ad317c9..dcd6d89 100644 --- a/Sysmon.md +++ b/chapters/Sysmon.md @@ -2,11 +2,11 @@ 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. -For ease of collecting the logs, all of the events generated are saved in Microsoft-Windows-Sysmon/Operational EventLog, which allows current security products that already leverage collection from the EventLog in Windows. +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 evet types and event ID for each. +The table below shows the event types and event ID for each. | EventType| EventId| |---|---| @@ -33,13 +33,15 @@ The table below shows the evet types and event ID for each. |WMI Event Consumer|20 |WMI Consumer to Filter|21 |DNS Query|22 +|File Delete|23 |Error|255 + ## 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 attitude 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. +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. The driver is loaded by a service at system startup and a secondary service then queries the cached information. @@ -428,6 +430,7 @@ Each of these operators execute against the value in a given field for each of t ## Event Schema + 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 @@ -494,7 +497,8 @@ Previous schemas can be used in newer releases of the binary allowing for upgrad ![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. +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. @@ -516,7 +520,7 @@ This type of configuration is only good with Schema 4.22 and above. It is recomm 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. -![RuleGroup](./media/image16.png) +![](./media/image16.png) Remember: You can only have one single EventType per RuleGroup. Sysmon will not error if you have more than one, but only the first EventType filters will be loaded. @@ -526,22 +530,25 @@ When using AND in a Rule element, the name used to populate the RuleName will be Rules are processed in the order they are placed in the configuration file. This is important because once a Rule matches and the information for that EventType is included in the Windows EventLog, no other rule will be processed against that action. Filters that are not in a Rule element will be processed in the order that they appear in the schema. This also applies to multiple filters inside a Rule where the schema order is used. +![](./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. -![Comment Header](./media/image18.png) +![](./media/image18.png) For RuleGroups, Rules and Filters use comments to organize filters and to provide information on what each filter is doing. -![XML Comments](./media/image19.png) +![](./media/image19.png) Hash configurations that are deployed and keep a log of them for later verification. -Hash configurations that are deployed and keep a log of them for later verification. On a system where the Sysmon service process consumes a lot of CPU resources, the number of filters and operators should be reviewed. The operators that use slightly more CPU are: +Hash configurations that are deployed and keep a log of them for later verification. +On a system where the Sysmon service process consumes a lot of CPU resources, the number of filters and operators should be reviewed. The operators that use slightly more CPU are: * contains @@ -553,7 +560,7 @@ A method for checking applied configuration is hashing the configuration in the registry. -![Get-SysmonRuleHash](./media/image20.png) +![](./media/image20.png) Since getting stated can be complex, some great resources that serve as starting points for Rule development and reference include: @@ -579,20 +586,21 @@ This does not mean that an attacker will not use more advanced methods to enumer Detection of Sysmon is achieved by looking at the areas that cannot be changed. - **Indicator** **Can it be Changed** - ---------------------------- ----------------------- - Driver Name YES - Service Name YES - Registry Config Path YES - Driver altitude Number NO - EventLog Path and Name NO - Sysmon Service Description NO (Manually) + **Indicator** | **Can it be Changed** + ----------------------------| ----------------------- + |Driver Name| YES + |Service Name| YES + |Registry Config Path| YES + |Driver altitude Number| NO + |EventLog Path and Name| NO + |Sysmon Service Description| NO (Manually) 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. -Sysmon can be configured to monitor its own conjuration 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. +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) @@ -620,7 +628,7 @@ Existing tools for parsing rules out of the registry break often as Sysmon is up ## Configuration Deployment -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. +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. ### Deployment Script @@ -648,7 +656,7 @@ if ($Present) { } else { # Execute upgrade process. Write-Host -Object "[-] Sysmon needs upgrade." -ForegroundColor Red - -U + -U -I } } else { @@ -713,6 +721,7 @@ The table below shows the evet types and event ID for each. |WMI Event Consumer|20 |WMI Consumer to Filter|21 |DNS Query|22 +|File Delete|23 |Error|255 ## Sysmon Operational Events @@ -764,17 +773,23 @@ If the Sysmon binary running as a service encounters any error in its operation, * An application or attacker has modified the configuration in a way that cannot be parsed by the service Fields for the Event: - -* **UtcTime**: Time when the error was logged. - -* **ID**: The error ID - -* **Description**: Description of what caused the error. +#### Known errors + +|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 Error](./media/image28.png) + ### Service State Change 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. @@ -795,6 +810,295 @@ Example: ![start example](./media/image30.png) +## Process Events + +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. + +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. + +![ProcessGUID Source](./media/image31.png) + +When a user logs onto on a modern version of Windows (Windows 2016/10) +they will have 2 Logon IDs assigned if: + +* User is a member of local Administrator Group. + +* UAC (User Access Control) is enabled. + +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. + +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. + +![ProcessGUID Relation](./media/image32.png) + +The only Event Types that will not reference a ProcessGuid or one of its +derived names are + +* WMI events + +* 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. + +![Image Relation](./media/image33.png) + + +### Process Creation + +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 fields on a process creation event are: + +* **ProcessGuid** -- Unique process GUID generated by Sysmon. + +* **ProcessId** -- Process ID represented as a integer number. + +* **Image** -- Full path of the executable image that was executed. + +* **FileVersion** -- File version filed in the image metadata. + +* **Description** -- Description field in the image metadata. + +* **Product** -- Product field in the image metadata. + +* **Company** - Company field in the image metadata. + +* **OriginalFileName** -- Original image name if renamed. + +* **CommandLine** -- Command line that executed the image. + +* **CurrentDirectory** -- Directory under which the image was + executed. + +* **User** - Name of the account who created the process (child) . It + usually contains domain name and user name + +* **LogonGuid** - Logon GUID of the user who created the new process. + +* **LogonId** -Login ID of the user who created the new process. + +* **TerminalSessionId** - ID of the session the user belongs to + +* **IntegrityLevel** - Integrity label assigned to a process + +* **Hashes** - Full hash of the file with the algorithms in the + HashType field. + +* **ParentProcessGuid** - ProcessGUID of the process that + spawned/created the main process (child) + +* **ParentProcessId** - Process ID of the process that spawned/created + the main process (child) + +* **ParentImage -** File path that spawned/created the main process. + +* **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 + +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: + +* **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, 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. + +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. + +Sysmon generates this event using ObRegisterCallbacks leveraging its +driver. The main 2 filtering fields recommended are: + +* **TargetImage** - File path of the executable being accessed by + another process. + +* **GrantedAccess** - The access flags (bitmask) associated with the + process rights requested for the target process + +As a minimum it is recommended to filter including critical processes, +as a minimum: + +* C:\\Windows\\system32\\lsass.exe + +* C:\\Windows\\system32\\csrss.exe + +* C:\\Windows\\system32\\wininit.exe + +* C:\\Windows\\system32\\winlogon.exe + +* C:\\Windows\\system32\\services.exe + +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. + +|Access | Mask | +|--------------------------------------|------------ +| PROCESS\_CREATE\_PROCESS |0x0080| +| PROCESS\_CREATE\_THREAD |0x0002| +| PROCESS\_DUP\_HANDLE |0x0040| +| PROCESS\_SET\_INFORMATION |0x0200| +| PROCESS\_SET\_QUOTA |0x0100| +| PROCESS\_QUERY\_LIMITED\_INFORMATION |0x1000| +| SYNCHRONIZE |0x00100000| +| PROCESS\_QUERY\_INFORMATION |0x0400| +| PROCESS\_SUSPEND\_RESUME |0x0800| +| PROCESS\_TERMINATE |0x0001| +| PROCESS\_VM\_OPERATION |0x0008| +| PROCESS\_VM\_READ |0x0010| +| PROCESS\_VM\_WRITE |0x0020| + +The PSGumshoe PowerShell module has a function for creating and parsing +mask strings. + + +The fields for the even are: + +* **RuleName**: Rule that triggered the event + +* **UtcTime**: Time in UTC when event was created + +* **SourceProcessGUID**: Process Guid of the source process that + opened another process. + +* **SourceProcessId**: Process ID used by the OS to identify the + source process that opened another process. + +* **SourceThreadId**: ID of the specific thread inside of the source + process that opened another process + +* **SourceImage**: File path of the source process that created a + thread in another process + +* **TargetProcessGUID**: Process Guid of the target process + +* **TargetProcessId**: Process ID used by the OS to identify the + target process + +* **TargetImage**: File path of the executable of the target process + +* **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 + +Example: + +```xml + + + + + + + C:\Windows\system32\lsass.exe + 0x1FFFFF + + + C:\Windows\system32\lsass.exe + 0x1F1FFF + + + C:\Windows\system32\lsass.exe + 0x1010 + + + C:\Windows\system32\lsass.exe + 0x143A + + + + + C:\Windows\system32\csrss.exe + 0x1F1FFF + + + C:\Windows\system32\wininit.exe + 0x1F1FFF + + + C:\Windows\system32\winlogon.exe + 0x1F1FFF + + + C:\Windows\system32\services.exe + 0x1F1FFF + + + 0x0810 + + + + + 0x0800 + 0x800 + + + + 0x0820 + 0x820 + + + + + +``` + +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 + ## File Events ### File Create @@ -950,7 +1254,7 @@ Example: ### 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 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: @@ -991,7 +1295,16 @@ Some execution examples: * PowerShell Example -More execution examples at by Oddvar Moe +More execution examples at + by +Oddvar Moe + +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. + +We can use PowerShell Get-Item and Get-Content cmdlets to check is a Zone.Identifier stream exist and show its content. + +![process](./media/image63.png) + The fields for the event: @@ -1003,11 +1316,15 @@ The fields for the event: * **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. + 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. ![process](./media/image43.png) +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. ```xml @@ -1028,12 +1345,95 @@ Example: Exclude common processes that create alternate data streams. ``` +### 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: + +* Dropper / stager that removes itself after execution (T1193 or T1064 and loads more) or attackers doing it manually + +* Wiper software (T1485 and T1488) + +* Ransomware (T1486) + +![minifilter](./media/image36.png) + +#### Archive directory + +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. + +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```. + +``` +PS C:\> (Get-Acl C:\Sysmon\).access + + +FileSystemRights : FullControl +AccessControlType : Allow +IdentityReference : NT AUTHORITY\SYSTEM +IsInherited : False +InheritanceFlags : None +PropagationFlags : None +``` + +#### Event information + +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 deletec the file + +* **ProcessId**: Process ID used by the OS to identify the process that deleted the file (child) + +* **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 saved file in the ArchiveDirectory + +* **Archived**: States whether the archival action was succesful + +Example monitoring for script file creation by extension: + +```XML + +SysmonIsAwesome + + + + + \Downloads\ + \Content.Outlook\ + \AppData\Local\Temp\ + \AppData\Local\Microsoft\ + C:\Windows\Temp + + + + .exe;.ps1;.js;.xls;.xlsm;.docm + + + + +``` + ## 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. +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. +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. Sysmon will generate a events @@ -1047,7 +1447,11 @@ For named pipes there are 2 approaches that can be taken: * 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. +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. The process for PipeName values should be constant process. @@ -1089,7 +1493,8 @@ The fields for the Pipe Create Event are: * **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 +* **ProcessId**: Process ID used by the OS to identify the process + that created the pipe * **PipeName**: Name of the pipe created @@ -1105,7 +1510,8 @@ The fields for the Pipe Connect Event are: * **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 +* **ProcessId**: Process ID used by the OS to identify the process + that connected the pipe * **PipeName**: Name of the pipe connected @@ -1146,7 +1552,10 @@ Example excluding known good Pipe Names ``` -One thing to consider is that Sysmon uses a minifilter just like the file events, any AV or EDR with a higher altitude number if it triggers on the named pipe and block Sysmon will not log the event. +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. + ## Driver Loading @@ -1234,7 +1643,7 @@ a VDI environment ## Registry Actions -Sysmon has the capability to monitor for three major actions against Registry +Sysmon has the capability to monitor for three major actions against the Registry * **EventID 12** - Registry object added or deleted @@ -1310,7 +1719,7 @@ In registry events, the value name is appended to the full key path with a \"\\\ Default key values are named \"\\(Default)\" -When filtering for keys or values in HKCU, use **contains** or **end with** when filtering against **TargetObject** since the SID of the user is appended after the Hive name. +When filtering for keys or values in HKCU, use **contains** or **ends with** when filtering against **TargetObject** since the SID of the user is appended after the Hive name. ![HKCU Test](./media/image51.png) @@ -1424,7 +1833,11 @@ Example of libraries leveraged by attackers ## 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. 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. +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 confifuration file. + +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. The fields for the event are: @@ -1464,6 +1877,7 @@ The fields for the event are: * **DestinationPortName**: Name of the destination port + Example tracking connections for attacker "Living off the land" ```xml @@ -1529,11 +1943,15 @@ Process of use/abuse of CreateRemoteThread * Use **VirtualAllocEx( )** allocate a chunk of memory in the process. -* Use **WriteProcessMemory( )** write the payload to the newly allocated section. +* Use **WriteProcessMemory( )** write the payload to the newly + allocated section. -* User **CreateRemoteThread( )** to create a new thread in the remote process to execute the shellcode. +* User **CreateRemoteThread( )** to create a new thread in the remote + process to execute the shellcode. -There are multiple Process Injection techniques, Sysmon monitors for the most common one used. The infographic from +There are multiple Process Injection techniques, Sysmon monitors for the +most common one used. The infographic from + Illustrates the different techniques. @@ -1545,15 +1963,19 @@ The fields for the event are: * **UtcTime**: Time in UTC when event was created -* **SourceProcessGuid**: Process Guid of the source process that created a thread in another process +* **SourceProcessGuid**: Process Guid of the source process that + created a thread in another process -* **SourceProcessId**: Process ID used by the OS to identify the source process that created a thread in another process +* **SourceProcessId**: Process ID used by the OS to identify the + source process that created a thread in another process -* **SourceImage**: File path of the source process that created a thread in another process +* **SourceImage**: File path of the source process that created a + thread in another process * **TargetProcessGuid**: Process Guid of the target process -* **TargetProcessId**: Process ID used by the OS to identify the target process +* **TargetProcessId**: Process ID used by the OS to identify the + target process * **TargetImage**: File path of the target process @@ -1561,9 +1983,11 @@ The fields for the event are: * **StartAddress**: New thread start address -* **StartModule**: Start module determined from thread start address mapping to PEB loaded module list +* **StartModule**: Start module determined from thread start address + mapping to PEB loaded module list -* **StartFunction**: Start function is reported if exact match to function in image export tables +* **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. @@ -1573,27 +1997,46 @@ Example where known processes that use the API call are excluded ```xml - + - - - - - Google\Chrome\Application\chrome.exe - C:\Windows\System32\wbem\WmiPrvSE.exe - C:\Windows\System32\svchost.exe - C:\Windows\System32\wininit.exe - C:\Windows\System32\csrss.exe - C:\Windows\System32\services.exe - C:\Windows\System32\winlogon.exe - C:\Windows\System32\audiodg.exe - C:\windows\system32\kernel32.dll + + + + + + Google\Chrome\Application\chrome.exe + + + C:\Windows\System32\wbem\WmiPrvSE.exe + + + C:\Windows\System32\svchost.exe + + + C:\Windows\System32\wininit.exe + + + C:\Windows\System32\csrss.exe + + + C:\Windows\System32\services.exe + + + C:\Windows\System32\winlogon.exe + + + C:\Windows\System32\audiodg.exe + + + C:\windows\system32\kernel32.dll + ``` + ## 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. @@ -1641,7 +2084,8 @@ 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 +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. @@ -1653,46 +2097,118 @@ Example that excludes known update and telemetry domains. - - .mozaws.net - .mozilla.com - .mozilla.net - .mozilla.org - clients1.google.com - clients2.google.com - clients3.google.com - clients4.google.com - clients5.google.com - clients6.google.com - - safebrowsing.googleapis.com - -pushp.svc.ms - .b-msedge.net - .bing.com - .hotmail.com - .live.com - .live.net - .s-microsoft.com - .microsoft.com - .microsoftonline.com - .microsoftstore.com - .ms-acdc.office.com - .msedge.net - .msn.com - .msocdn.com - .skype.com - .skype.net - .windows.com - .windows.net.nsatc.net - .windowsupdate.com - .xboxlive.com - login.windows.net + + + + + .mozaws.net + + + .mozilla.com + + + .mozilla.net + + + .mozilla.org + + + + + clients1.google.com + + + clients2.google.com + + + clients3.google.com + + + clients4.google.com + + + clients5.google.com + + + clients6.google.com + + + safebrowsing.googleapis.com + + + + + + -pushp.svc.ms + + + .b-msedge.net + + + + .bing.com + + + .hotmail.com + + + .live.com + + + .live.net + + + .s-microsoft.com + + + .microsoft.com + + + .microsoftonline.com + + + .microsoftstore.com + + + .ms-acdc.office.com + + + .msedge.net + + + .msn.com + + + .msocdn.com + + + .skype.com + + + .skype.net + + + .windows.com + + + .windows.net.nsatc.net + + + .windowsupdate.com + + + .xboxlive.com + + + login.windows.net + - - + + ``` + ## WMI Events WMI events, both temporary and permanent (survive a reboot), have been used for diff --git a/WMI-events.md b/chapters/WMI-events.md similarity index 96% rename from WMI-events.md rename to chapters/WMI-events.md index c330c82..553f16b 100644 --- a/WMI-events.md +++ b/chapters/WMI-events.md @@ -1,111 +1,111 @@ -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. - -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) - -- **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 - -- **Consumer** - An action to take upon triggering the filter - -- **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. - -Fields for the Filter creation, modification, or deletion are: - -- **RuleName**: Rule name for filter - -- **EventType**: Will always be *WmiFilterEvent* - -- **UtcTime**: Time event happened - -- **Operation**: Created, modified or deleted - -- **User**: User that performed the action - -- **EventNamespace**: WMI Namespace where object was created - -- **Name**: Name of the filter - -- **Query**: Query defined for the filter - -The fields for Consumer creation, modification, or deletion are: - -- **RuleName**: Rule name for filter - -- **EventType**: Will always be *WmiConsumerEvent* - -- **UtcTime**: Time event happened - -- **Operation**: Created, modified, or deleted - -- **User**: User that performed the action - -- **Name**: Name of the consumer - -- **Type**: Type of consumer - -- **Destination**: Command or Script being executed - -The fields for filter to consumer binding are: - -- **RuleName**: Rule name for filter - -- **EventType**: Will always be *WmiBindingEvent* - -- **UtcTime**: Time event happened - -- **Operation**: Created, modified, or deleted - -- **User**: User that performed the action - -- **Consumer**: Consumer 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, -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) - -It is recommended to log all instances of this event type. - -```XML - - - * - - - - - - - - -``` +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. + +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) + +- **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 + +- **Consumer** - An action to take upon triggering the filter + +- **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. + +Fields for the Filter creation, modification, or deletion are: + +- **RuleName**: Rule name for filter + +- **EventType**: Will always be *WmiFilterEvent* + +- **UtcTime**: Time event happened + +- **Operation**: Created, modified or deleted + +- **User**: User that performed the action + +- **EventNamespace**: WMI Namespace where object was created + +- **Name**: Name of the filter + +- **Query**: Query defined for the filter + +The fields for Consumer creation, modification, or deletion are: + +- **RuleName**: Rule name for filter + +- **EventType**: Will always be *WmiConsumerEvent* + +- **UtcTime**: Time event happened + +- **Operation**: Created, modified, or deleted + +- **User**: User that performed the action + +- **Name**: Name of the consumer + +- **Type**: Type of consumer + +- **Destination**: Command or Script being executed + +The fields for filter to consumer binding are: + +- **RuleName**: Rule name for filter + +- **EventType**: Will always be *WmiBindingEvent* + +- **UtcTime**: Time event happened + +- **Operation**: Created, modified, or deleted + +- **User**: User that performed the action + +- **Consumer**: Consumer 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, +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) + +It is recommended to log all instances of this event type. + +```XML + + + * + + + + + + + + +``` diff --git a/chapters/clipboard-capture.md b/chapters/clipboard-capture.md new file mode 100644 index 0000000..04a451f --- /dev/null +++ b/chapters/clipboard-capture.md @@ -0,0 +1,82 @@ +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. + +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. + +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. + + +The fields for the event 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 the text in the clipboard. + +* **ProcessId**: Process ID of the process that stored the text in the clipboard. + +* **Image**: The process that recorded to the clipboard. + +* **Session**: Session where the process writing to the clipboard is running. This can be system(0) interactive or remote, etc. + +* **ClientInfo**: this will contain the session username, and in case of a remote session the originating hostname, and the IP address when available. + +* **Hashes**: This determines the file name, same as the FileDelete event. + +* **Archived**: Status whether is was stored in the configured Archive directory. + +A sample configuration to capture all clipboard events: + +```XML + + sha1 + + + + + + + + + + +``` + +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 + + + + - + 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 + + +``` + + diff --git a/install-and-configuration.md b/chapters/configuration.md similarity index 59% rename from install-and-configuration.md rename to chapters/configuration.md index 9241e10..977996c 100644 --- a/install-and-configuration.md +++ b/chapters/configuration.md @@ -1,256 +1,7 @@ -Install 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. - -* **Sysmon64.exe** - 64bit only version. - -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 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: - -* Decompresses and saves driver and copy of itself in to **%systemroot%** - -* Registers event log manifest - -* Creates a service - -* Enables a default configuration (ProcessCreation, ProcessTermination, DriverLoad , FileCreationTimeChanged, SHA1 for Images) if no configuration file is passed using the **-c \** parameter - -The Installation process allows for some obfuscation: - -* Driver name can be changed - -* Service name can be changed - -* Sysmon binary name can be renamed. - -These obfuscation changes will also affect registry paths for the driver and processes service keys. All of the obfuscation methods are part of the installation option set. - -The installation options are: - -* Default -- Driver is installed and named SysmonDrv and service Sysmon - -```shell -sysmon.exe --i --accepteula - -``` - -* Renamed Driver -- The driver file and registry entry are renamed. Name has an 8-character limit. - -```shell -sysmon.exe -i -d -``` - -* Renamed Service -- The executable name defines the service name. - -```shell -.exe -i -d -``` - -The installation process on a x64 system with the binary named sysmon.exe that is intended to work across x64 and x86 architectures is shown below. This is important since some of the actions may cause confusion or trigger alerts on monitoring systems. - -One important thing to keep in mind when obfuscating the driver name and service name is that certain characteristics remain the same. - -* Service description remains the same. (This can be modified post-install.) - -* Driver Altitude number remains the same. - -* 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 Sysmon executable. - -* SysmonDrv - Kernel Driver Service, this service loads the Sysmon driver with an altitude number of 385201 - -The settings for each service are: - -Main Service: - -* Name: **Name of the executable (default Sysmon or Sysmon64)** - -* LogOn: **Local System** - -* Description: **System Monitor service** - -* Startup: **Automatic** - -* ImagePath: **%windir%\\\** - -Driver Service: - -* Name: **SysmonDrv unless --d \ is** - -* LogOn: **Local System** - -* Description: **System Monitor driver** - -* Startup: **Automatic** - -* 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. 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. - -```shell -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 - -``` - -SSome basic filtering can be done also from the command line. Only filtering by process name can be done for NetworkConnect, ImageLoad, and ProcessAccess via the command line. - -* **NetworkConnect** - Track network connections. - -```shell -sysmon.exe -i -c -n [] -``` - -* **ImageLoad** - DLL loading by processes. - -```shell -sysmon.exe -i -c -l [] -``` - -* **ProcessAccess** - Processes whose memory is accessed. - -```shell -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. - -```shell -sysmon.exe -u -``` -When executed the command will run a series of steps to uninstall the service, driver and remove files for the tool. - -![Uninstall Process](./media/image8.png) - -There is an undocumented value that can be passed to the **-u** parameter of **"force"** to force the removal of the services even if a stop was not possible. - -```shell -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: - -* Keep a repository of Sysmon versions archived; Microsoft does not provide older versions for download. - -* Sysmon is very dependent on the version of the binary for its configuration. The install/upgrade script should check the binary version for: - - * Upgrade - - * 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: - -```sql -SELECT * FROM CIM_Datafile WHERE (Name="c:\\Windows\\Sysmon64.exe" OR Name="c:\\Windows\\Sysmon.exe") AND version="10.0.4.1" -``` - -* Check file versions they don't match release versioning. - -* It is better to not push configuration as an XML that gets run from a share or dropped on disk with a scheduled task: - - * Credentials are left that can be recovered via DPAPI for deleted scheduled tasks. - - * The file can be read more easily by an attacker if controls are not properly placed - - * There is a higher chance of human error - - * Better to push values via GPO or other methods with file version checking. 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. @@ -283,6 +34,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 @@ -291,16 +46,14 @@ The main arguments that can be passed are: sysmon.exe -i [configfile path] ``` -* **-c** : apply config - ```shell -sysmon.exe -c [configfile path] +sysmon. -i [configfile path] ``` -* **-a** : Archive Folder +* **-c** : apply config ```shell -sysmon.exe -a [archive folder] +sysmon.exe -c [configfile path] ``` * **-u** : un-install Sysmon @@ -309,13 +62,13 @@ sysmon.exe -a [archive folder] 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] @@ -327,7 +80,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 @@ -336,56 +89,102 @@ 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. +Sysmon for Linux parameters are: + +The main arguments that can be passed are: + +* **-i** : Install Sysmon + +```shell +/usr/bin/sysmon -i [configfile path] +``` + +* **-c** : apply config + +```shell +/usr/bin/sysmon -c [configfile path] +``` + +```bash +/ussr/bin/sysmon -u [force] +``` + +* **-s** : Print schema + +```shell +/ussr/bin/sysmon -s [schema version] +``` + +* **-accepteula** : Accepts the license agreement + +```shell +/ussr/bin/sysmon -accepteula +``` + +* **--** : Resets the configuration to the default + +```shell +/ussr/bin/sysmon -c -- +``` + +The option elements under the comment "Configuration file" allow for the configuration of filters and parameters that relate to filters. + +* **-n** : Track network connections for specified process/processes. + +```bash +/ussr/bin/sysmon -c -n [] +``` + Filter Operators ---------------- @@ -393,19 +192,22 @@ In the filters element under configuration is the list of operators that can be | **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 ";" ) +| 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. +| contains any| Contains any of the values. (values are separate by ";" ) +| contains all| Contains all of the values. (values are separate by ";" ) +| 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. +| begin with | String value starts with the specified string. +| not begin with| String value does not starts with the specified string. +| end with | String value ends with the specified string. +| not end with| String value ends with the specified string. +| less than | Numeric value is less than +| more than | Numeric value is more than Each of these operators execute against the value in a given field for each of the event types. @@ -440,7 +242,7 @@ We can filter on the Field Names defined in the data elements. They are defined ![Fields definition](./media/image12.png) -As of the latest version we have defined as event types: +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 @@ -470,13 +272,20 @@ As of the latest version we have defined as event types: * **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. 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. -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. +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) @@ -555,6 +364,7 @@ Since getting stated can be complex, some great resources that serve as starting Configuration Tampering ----------------------- + One of the actions an attacker takes is the identification of controls and logging on a system. Due to initial footprint and safety, most advanced attackers limit their actions to enumerate controls to the most common actions that elements that will trigger a monitoring solution. The most common methods used are: @@ -563,11 +373,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** ----------------------------| ----------------------- @@ -580,16 +390,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** @@ -601,7 +491,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. @@ -609,9 +505,35 @@ 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. +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 + Configuration Deployment ------------------------ -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. + +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. + +Sylog Message Size +------------------ + +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: + +* Image +* ParentImage +* CommandLine +* ParentCommandLine Deployment Script ----------------- @@ -640,7 +562,7 @@ if ($Present) { } else { # Execute upgrade process. Write-Host -Object "[-] Sysmon needs upgrade." -ForegroundColor Red - -U + -U -I } } else { diff --git a/cover.png b/chapters/cover.png similarity index 100% rename from cover.png rename to chapters/cover.png diff --git a/create-remote-thread.md b/chapters/create-remote-thread.md similarity index 100% rename from create-remote-thread.md rename to chapters/create-remote-thread.md diff --git a/dns-query.md b/chapters/dns-query.md similarity index 100% rename from dns-query.md rename to chapters/dns-query.md diff --git a/driver-loading.md b/chapters/driver-loading.md similarity index 100% rename from driver-loading.md rename to chapters/driver-loading.md diff --git a/chapters/eBPF.md b/chapters/eBPF.md new file mode 100644 index 0000000..2b5e83e --- /dev/null +++ b/chapters/eBPF.md @@ -0,0 +1,18 @@ +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 diff --git a/file-create-time-change.md b/chapters/file-create-time-change.md similarity index 100% rename from file-create-time-change.md rename to chapters/file-create-time-change.md diff --git a/file-create.md b/chapters/file-create.md similarity index 100% rename from file-create.md rename to chapters/file-create.md diff --git a/file-delete.md b/chapters/file-delete.md similarity index 64% rename from file-delete.md rename to chapters/file-delete.md index d51ed59..d238b24 100644 --- a/file-delete.md +++ b/chapters/file-delete.md @@ -1,7 +1,7 @@ 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: +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: * Dropper / stager that removes itself after execution (T1193 or T1064 and loads more) or attackers doing it manually @@ -11,6 +11,9 @@ Via its filter driver, Sysmon can log the creation of files and information on w ![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. + + ### Archive directory 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. @@ -74,3 +77,19 @@ Example monitoring for script file creation by extension: ``` + +### Warning + +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. + +SHA1 hashes for vulnerables version of the drivers are: + +* 35c67ac6cb0ade768ccf11999b9aaf016ab9ae92fb51865d73ec1f7907709dca +* d2ed01cce3e7502b1dd8be35abf95e6e8613c5733ee66e749b972542495743b8 +* a86e063ac5214ebb7e691506a9f877d12b7958e071ecbae0f0723ae24e273a73 +* c0640d0d9260689b1c6c63a60799e0c8e272067dcf86847c882980913694543a +* 2a5e73343a38e7b70a04f1b46e9a2dde7ca85f38a4fb2e51e92f252dad7034d4 +* 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. diff --git a/file-stream-creation-hash.md b/chapters/file-stream-creation-hash.md similarity index 100% rename from file-stream-creation-hash.md rename to chapters/file-stream-creation-hash.md diff --git a/chapters/file_delete_detected.md b/chapters/file_delete_detected.md new file mode 100644 index 0000000..7a8166b --- /dev/null +++ b/chapters/file_delete_detected.md @@ -0,0 +1,30 @@ +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**. + +It leverages the Sysmon minidriver and we should considered it altitude number when other security products are present. + +![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. + +### Event information + +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 (child) + +* **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 saved file in the ArchiveDirectory + +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. diff --git a/image-loading.md b/chapters/image-loading.md similarity index 100% rename from image-loading.md rename to chapters/image-loading.md diff --git a/chapters/install_linux.md b/chapters/install_linux.md new file mode 100644 index 0000000..d7a09fc --- /dev/null +++ b/chapters/install_linux.md @@ -0,0 +1,54 @@ +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. + +Installation +------------ + +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. + +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. + +```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 +``` diff --git a/chapters/install_windows.md b/chapters/install_windows.md new file mode 100644 index 0000000..f682c8a --- /dev/null +++ b/chapters/install_windows.md @@ -0,0 +1,253 @@ +Install 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. + +* **Sysmon64.exe** - 64bit only version. + +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 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: + +* Decompresses and saves driver and copy of itself in to **%systemroot%** + +* Registers event log manifest + +* Creates a service + +* Enables a default configuration (ProcessCreation, ProcessTermination, DriverLoad , FileCreationTimeChanged, SHA1 for Images) if no configuration file is passed using the **-c \** parameter + +The Installation process allows for some obfuscation: + +* Driver name can be changed + +* Service name can be changed + +* Sysmon binary name can be renamed. + +These obfuscation changes will also affect registry paths for the driver and processes service keys. All of the obfuscation methods are part of the installation option set. + +The installation options are: + +* Default -- Driver is installed and named SysmonDrv and service Sysmon + +```shell +sysmon.exe --i --accepteula + +``` + +* Renamed Driver -- The driver file and registry entry are renamed. Name has an 8-character limit. + +```shell +sysmon.exe -i -d +``` + +* Renamed Service -- The executable name defines the service name. + +```shell +.exe -i -d +``` + +The installation process on a x64 system with the binary named sysmon.exe that is intended to work across x64 and x86 architectures is shown below. This is important since some of the actions may cause confusion or trigger alerts on monitoring systems. + +One important thing to keep in mind when obfuscating the driver name and service name is that certain characteristics remain the same. + +* Service description remains the same. (This can be modified post-install.) + +* Driver Altitude number remains the same. + +* 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 Sysmon executable. + +* SysmonDrv - Kernel Driver Service, this service loads the Sysmon driver with an altitude number of 385201 + +The settings for each service are: + +Main Service: + +* Name: **Name of the executable (default Sysmon or Sysmon64)** + +* LogOn: **Local System** + +* Description: **System Monitor service** + +* Startup: **Automatic** + +* ImagePath: **%windir%\\\** + +Driver Service: + +* Name: **SysmonDrv unless --d \ is** + +* LogOn: **Local System** + +* Description: **System Monitor driver** + +* Startup: **Automatic** + +* 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. + +```shell +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 + +``` + +SSome basic filtering can be done also from the command line. Only filtering by process name can be done for NetworkConnect, ImageLoad, and ProcessAccess via the command line. + +* **NetworkConnect** - Track network connections. + +```shell +sysmon.exe -i -c -n [] +``` + +* **ImageLoad** - DLL loading by processes. + +```shell +sysmon.exe -i -c -l [] +``` + +* **ProcessAccess** - Processes whose memory is accessed. + +```shell +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. + +```shell +sysmon.exe -u +``` + +When executed the command will run a series of steps to uninstall the service, driver and remove files for the tool. + +![Uninstall Process](./media/image8.png) + +There is an undocumented value that can be passed to the **-u** parameter of **"force"** to force the removal of the services even if a stop was not possible. + +```shell +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: + +* Keep a repository of Sysmon versions archived; Microsoft does not provide older versions for download. + +* Sysmon is very dependent on the version of the binary for its configuration. The install/upgrade script should check the binary version for: + + * Upgrade + + * 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: + +```sql +SELECT * FROM CIM_Datafile WHERE (Name="c:\\Windows\\Sysmon64.exe" OR Name="c:\\Windows\\Sysmon.exe") AND version="10.0.4.1" +``` + +* Check file versions they don't match release versioning. + +* It is better to not push configuration as an XML that gets run from a share or dropped on disk with a scheduled task: + + * Credentials are left that can be recovered via DPAPI for deleted scheduled tasks. + + * The file can be read more easily by an attacker if controls are not properly placed + + * There is a higher chance of human error + + * Better to push values via GPO or other methods with file version checking. + diff --git a/media/image1.png b/chapters/media/image1.png similarity index 100% rename from media/image1.png rename to chapters/media/image1.png diff --git a/media/image10.png b/chapters/media/image10.png similarity index 100% rename from media/image10.png rename to chapters/media/image10.png diff --git a/media/image11.png b/chapters/media/image11.png similarity index 100% rename from media/image11.png rename to chapters/media/image11.png diff --git a/media/image12.png b/chapters/media/image12.png similarity index 100% rename from media/image12.png rename to chapters/media/image12.png diff --git a/media/image13.png b/chapters/media/image13.png similarity index 100% rename from media/image13.png rename to chapters/media/image13.png diff --git a/media/image14.png b/chapters/media/image14.png similarity index 100% rename from media/image14.png rename to chapters/media/image14.png diff --git a/media/image15.png b/chapters/media/image15.png similarity index 100% rename from media/image15.png rename to chapters/media/image15.png diff --git a/media/image16.png b/chapters/media/image16.png similarity index 100% rename from media/image16.png rename to chapters/media/image16.png diff --git a/media/image17.png b/chapters/media/image17.png similarity index 100% rename from media/image17.png rename to chapters/media/image17.png diff --git a/media/image18.png b/chapters/media/image18.png similarity index 100% rename from media/image18.png rename to chapters/media/image18.png diff --git a/media/image19.png b/chapters/media/image19.png similarity index 100% rename from media/image19.png rename to chapters/media/image19.png diff --git a/media/image2.png b/chapters/media/image2.png similarity index 100% rename from media/image2.png rename to chapters/media/image2.png diff --git a/media/image20.png b/chapters/media/image20.png similarity index 100% rename from media/image20.png rename to chapters/media/image20.png diff --git a/media/image21.png b/chapters/media/image21.png similarity index 100% rename from media/image21.png rename to chapters/media/image21.png diff --git a/media/image22.png b/chapters/media/image22.png similarity index 100% rename from media/image22.png rename to chapters/media/image22.png diff --git a/media/image23.png b/chapters/media/image23.png similarity index 100% rename from media/image23.png rename to chapters/media/image23.png diff --git a/media/image24.png b/chapters/media/image24.png similarity index 100% rename from media/image24.png rename to chapters/media/image24.png diff --git a/media/image25.png b/chapters/media/image25.png similarity index 100% rename from media/image25.png rename to chapters/media/image25.png diff --git a/media/image26.png b/chapters/media/image26.png similarity index 100% rename from media/image26.png rename to chapters/media/image26.png diff --git a/media/image27.png b/chapters/media/image27.png similarity index 100% rename from media/image27.png rename to chapters/media/image27.png diff --git a/media/image28.png b/chapters/media/image28.png similarity index 100% rename from media/image28.png rename to chapters/media/image28.png diff --git a/media/image29.png b/chapters/media/image29.png similarity index 100% rename from media/image29.png rename to chapters/media/image29.png diff --git a/media/image3.png b/chapters/media/image3.png similarity index 100% rename from media/image3.png rename to chapters/media/image3.png diff --git a/media/image30.png b/chapters/media/image30.png similarity index 100% rename from media/image30.png rename to chapters/media/image30.png diff --git a/media/image31.png b/chapters/media/image31.png similarity index 100% rename from media/image31.png rename to chapters/media/image31.png diff --git a/media/image32.png b/chapters/media/image32.png similarity index 100% rename from media/image32.png rename to chapters/media/image32.png diff --git a/media/image33.png b/chapters/media/image33.png similarity index 100% rename from media/image33.png rename to chapters/media/image33.png diff --git a/media/image34.png b/chapters/media/image34.png similarity index 100% rename from media/image34.png rename to chapters/media/image34.png diff --git a/media/image35.png b/chapters/media/image35.png similarity index 100% rename from media/image35.png rename to chapters/media/image35.png diff --git a/media/image36.png b/chapters/media/image36.png similarity index 100% rename from media/image36.png rename to chapters/media/image36.png diff --git a/media/image37.png b/chapters/media/image37.png similarity index 100% rename from media/image37.png rename to chapters/media/image37.png diff --git a/media/image38.png b/chapters/media/image38.png similarity index 100% rename from media/image38.png rename to chapters/media/image38.png diff --git a/media/image39.png b/chapters/media/image39.png similarity index 100% rename from media/image39.png rename to chapters/media/image39.png diff --git a/media/image4.png b/chapters/media/image4.png similarity index 100% rename from media/image4.png rename to chapters/media/image4.png diff --git a/media/image40.png b/chapters/media/image40.png similarity index 100% rename from media/image40.png rename to chapters/media/image40.png diff --git a/media/image41.png b/chapters/media/image41.png similarity index 100% rename from media/image41.png rename to chapters/media/image41.png diff --git a/media/image42.png b/chapters/media/image42.png similarity index 100% rename from media/image42.png rename to chapters/media/image42.png diff --git a/media/image43.png b/chapters/media/image43.png similarity index 100% rename from media/image43.png rename to chapters/media/image43.png diff --git a/media/image44.png b/chapters/media/image44.png similarity index 100% rename from media/image44.png rename to chapters/media/image44.png diff --git a/media/image45.png b/chapters/media/image45.png similarity index 100% rename from media/image45.png rename to chapters/media/image45.png diff --git a/media/image46.png b/chapters/media/image46.png similarity index 100% rename from media/image46.png rename to chapters/media/image46.png diff --git a/media/image47.png b/chapters/media/image47.png similarity index 100% rename from media/image47.png rename to chapters/media/image47.png diff --git a/media/image48.png b/chapters/media/image48.png similarity index 100% rename from media/image48.png rename to chapters/media/image48.png diff --git a/media/image49.png b/chapters/media/image49.png similarity index 100% rename from media/image49.png rename to chapters/media/image49.png diff --git a/media/image5.png b/chapters/media/image5.png similarity index 100% rename from media/image5.png rename to chapters/media/image5.png diff --git a/media/image50.png b/chapters/media/image50.png similarity index 100% rename from media/image50.png rename to chapters/media/image50.png diff --git a/media/image51.png b/chapters/media/image51.png similarity index 100% rename from media/image51.png rename to chapters/media/image51.png diff --git a/media/image52.png b/chapters/media/image52.png similarity index 100% rename from media/image52.png rename to chapters/media/image52.png diff --git a/media/image53.png b/chapters/media/image53.png similarity index 100% rename from media/image53.png rename to chapters/media/image53.png diff --git a/media/image54.png b/chapters/media/image54.png similarity index 100% rename from media/image54.png rename to chapters/media/image54.png diff --git a/media/image55.png b/chapters/media/image55.png similarity index 100% rename from media/image55.png rename to chapters/media/image55.png diff --git a/media/image56.png b/chapters/media/image56.png similarity index 100% rename from media/image56.png rename to chapters/media/image56.png diff --git a/media/image57.png b/chapters/media/image57.png similarity index 100% rename from media/image57.png rename to chapters/media/image57.png diff --git a/media/image58.png b/chapters/media/image58.png similarity index 100% rename from media/image58.png rename to chapters/media/image58.png diff --git a/media/image59.png b/chapters/media/image59.png similarity index 100% rename from media/image59.png rename to chapters/media/image59.png diff --git a/media/image6.png b/chapters/media/image6.png similarity index 100% rename from media/image6.png rename to chapters/media/image6.png diff --git a/media/image60.png b/chapters/media/image60.png similarity index 100% rename from media/image60.png rename to chapters/media/image60.png diff --git a/media/image61.png b/chapters/media/image61.png similarity index 100% rename from media/image61.png rename to chapters/media/image61.png diff --git a/media/image62.png b/chapters/media/image62.png similarity index 100% rename from media/image62.png rename to chapters/media/image62.png diff --git a/chapters/media/image63.png b/chapters/media/image63.png new file mode 100644 index 0000000..52f6e7b Binary files /dev/null and b/chapters/media/image63.png differ diff --git a/chapters/media/image64.png b/chapters/media/image64.png new file mode 100644 index 0000000..6f519f5 Binary files /dev/null and b/chapters/media/image64.png differ diff --git a/chapters/media/image65.png b/chapters/media/image65.png new file mode 100644 index 0000000..a4e8dbd Binary files /dev/null and b/chapters/media/image65.png differ diff --git a/chapters/media/image66.png b/chapters/media/image66.png new file mode 100644 index 0000000..c6f0238 Binary files /dev/null and b/chapters/media/image66.png differ diff --git a/chapters/media/image67.png b/chapters/media/image67.png new file mode 100644 index 0000000..89738f4 Binary files /dev/null and b/chapters/media/image67.png differ diff --git a/chapters/media/image68.png b/chapters/media/image68.png new file mode 100644 index 0000000..22ee068 Binary files /dev/null and b/chapters/media/image68.png differ diff --git a/media/image7.png b/chapters/media/image7.png similarity index 100% rename from media/image7.png rename to chapters/media/image7.png diff --git a/media/image8.png b/chapters/media/image8.png similarity index 100% rename from media/image8.png rename to chapters/media/image8.png diff --git a/media/image9.png b/chapters/media/image9.png similarity index 100% rename from media/image9.png rename to chapters/media/image9.png diff --git a/media/tslogo.png b/chapters/media/tslogo.png similarity index 100% rename from media/tslogo.png rename to chapters/media/tslogo.png diff --git a/chapters/metadata.yml b/chapters/metadata.yml new file mode 100644 index 0000000..87bf745 --- /dev/null +++ b/chapters/metadata.yml @@ -0,0 +1,13 @@ +--- +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 +date: 28.01.2020 +publisher: TrustedSec Inc. +ibooks: + version: 1.0 +stylesheet: pandoc.css +cover-image: media/cover.png +--- \ No newline at end of file diff --git a/named-pipes.md b/chapters/named-pipes.md similarity index 100% rename from named-pipes.md rename to chapters/named-pipes.md diff --git a/network-connections.md b/chapters/network-connections.md similarity index 100% rename from network-connections.md rename to chapters/network-connections.md diff --git a/operational-events.md b/chapters/operational-events.md similarity index 100% rename from operational-events.md rename to chapters/operational-events.md diff --git a/chapters/pandoc.css b/chapters/pandoc.css new file mode 100644 index 0000000..8b9903f --- /dev/null +++ b/chapters/pandoc.css @@ -0,0 +1,328 @@ +/* + * I add this to html files generated with pandoc. + */ + +html { + font-size: 100%; + overflow-y: scroll; + -webkit-text-size-adjust: 100%; + -ms-text-size-adjust: 100%; +} + +body { + color: #444; + font-family: Georgia, Palatino, 'Palatino Linotype', Times, 'Times New Roman', serif; + font-size: 12px; + line-height: 1.7; + padding: 1em; + margin: auto; + max-width: 42em; + background: #fefefe; +} + +a { + color: #0645ad; + text-decoration: none; +} + +a:visited { + color: #0b0080; +} + +a:hover { + color: #06e; +} + +a:active { + color: #faa700; +} + +a:focus { + outline: thin dotted; +} + +*::-moz-selection { + background: rgba(255, 255, 0, 0.3); + color: #000; +} + +*::selection { + background: rgba(255, 255, 0, 0.3); + color: #000; +} + +a::-moz-selection { + background: rgba(255, 255, 0, 0.3); + color: #0645ad; +} + +a::selection { + background: rgba(255, 255, 0, 0.3); + color: #0645ad; +} + +p { + margin: 1em 0; +} + +img { + max-width: 100%; +} + +h1, h2, h3, h4, h5, h6 { + color: #111; + line-height: 125%; + margin-top: 2em; + font-weight: normal; +} + +h4, h5, h6 { + font-weight: bold; +} + +h1 { + font-size: 2.5em; +} + +h2 { + font-size: 2em; +} + +h3 { + font-size: 1.5em; +} + +h4 { + font-size: 1.2em; +} + +h5 { + font-size: 1em; +} + +h6 { + font-size: 0.9em; +} + +blockquote { + color: #666666; + margin: 0; + padding-left: 3em; + border-left: 0.5em #EEE solid; +} + +hr { + display: block; + height: 2px; + border: 0; + border-top: 1px solid #aaa; + border-bottom: 1px solid #eee; + margin: 1em 0; + padding: 0; +} + +pre, code, kbd, samp { + color: #000; + font-family: monospace, monospace; + _font-family: 'courier new', monospace; + font-size: 0.98em; +} + +pre { + white-space: pre; + white-space: pre-wrap; + word-wrap: break-word; +} + +b, strong { + font-weight: bold; +} + +dfn { + font-style: italic; +} + +ins { + background: #ff9; + color: #000; + text-decoration: none; +} + +mark { + background: #ff0; + color: #000; + font-style: italic; + font-weight: bold; +} + +sub, sup { + font-size: 75%; + line-height: 0; + position: relative; + vertical-align: baseline; +} + +sup { + top: -0.5em; +} + +sub { + bottom: -0.25em; +} + +ul, ol { + margin: 1em 0; + padding: 0 0 0 2em; +} + +li p:last-child { + margin-bottom: 0; +} + +ul ul, ol ol { + margin: .3em 0; +} + +dl { + margin-bottom: 1em; +} + +dt { + font-weight: bold; + margin-bottom: .8em; +} + +dd { + margin: 0 0 .8em 2em; +} + +dd:last-child { + margin-bottom: 0; +} + +img { + border: 0; + -ms-interpolation-mode: bicubic; + vertical-align: middle; +} + +figure { + display: block; + text-align: center; + margin: 1em 0; +} + +figure img { + border: none; + margin: 0 auto; +} + +figcaption { + font-size: 0.8em; + font-style: italic; + margin: 0 0 .8em; +} + +table { + margin-bottom: 2em; + border-bottom: 1px solid #ddd; + border-right: 1px solid #ddd; + border-spacing: 0; + border-collapse: collapse; +} + +table th { + padding: .2em 1em; + background-color: #eee; + border-top: 1px solid #ddd; + border-left: 1px solid #ddd; +} + +table td { + padding: .2em 1em; + border-top: 1px solid #ddd; + border-left: 1px solid #ddd; + vertical-align: top; +} + +.author { + font-size: 1.2em; + text-align: center; +} + +@media only screen and (min-width: 480px) { + body { + font-size: 14px; + } +} +@media only screen and (min-width: 768px) { + body { + font-size: 16px; + } +} +@media print { + * { + background: transparent !important; + color: black !important; + filter: none !important; + -ms-filter: none !important; + } + + body { + font-size: 12pt; + max-width: 100%; + } + + a, a:visited { + text-decoration: underline; + } + + hr { + height: 1px; + border: 0; + border-bottom: 1px solid black; + } + + a[href]:after { + content: " (" attr(href) ")"; + } + + abbr[title]:after { + content: " (" attr(title) ")"; + } + + .ir a:after, a[href^="javascript:"]:after, a[href^="#"]:after { + content: ""; + } + + pre, blockquote { + border: 1px solid #999; + padding-right: 1em; + page-break-inside: avoid; + } + + tr, img { + page-break-inside: avoid; + } + + img { + max-width: 100% !important; + } + + @page :left { + margin: 15mm 20mm 15mm 10mm; +} + + @page :right { + margin: 15mm 10mm 15mm 20mm; +} + + p, h2, h3 { + orphans: 3; + widows: 3; + } + + h2, h3 { + page-break-after: avoid; + } +} diff --git a/process-access.md b/chapters/process-access.md similarity index 100% rename from process-access.md rename to chapters/process-access.md diff --git a/chapters/process-creation.md b/chapters/process-creation.md new file mode 100644 index 0000000..d25ae53 --- /dev/null +++ b/chapters/process-creation.md @@ -0,0 +1,85 @@ + +Process Creation +================ + +Sysmon will log **EventID 1** for the creation of any new process when +it registers with the kernel. + +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. + +The fields on a process creation event are: + +* **ProcessGuid** -- Unique process GUID generated by Sysmon. + +* **ProcessId** -- Process ID represented as a integer number. + +* **Image** -- Full path of the executable image that was executed. + +* **FileVersion** -- File version filed in the image metadata. (Windows Only) + +* **Description** -- Description field in the image metadata.(Windows Only) + +* **Product** -- Product field in the image metadata. (Windows Only) + +* **Company** - Company field in the image metadata. (Windows Only) + +* **OriginalFileName** -- Original image name if renamed. (Windows Only) + +* **CommandLine** -- Command line that executed the image. + +* **CurrentDirectory** -- Directory under which the image was + executed. + +* **User** - Name of the account who created the process (child) . It + usually contains domain name and user name + +* **LogonGuid** - Logon GUID of the user who created the new process. + +* **LogonId** -Login ID of the user who created the new process. + +* **TerminalSessionId** - ID of the session the user belongs to + +* **IntegrityLevel** - Integrity label assigned to a process + +* **Hashes** - Full hash of the file with the algorithms in the + HashType field. (Windows Only) + +* **ParentProcessGuid** - ProcessGUID of the process that + spawned/created the main process (child) + +* **ParentProcessId** - Process ID of the process that spawned/created + the main process (child) + +* **ParentImage -** File path that spawned/created the main process. + +* **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. + +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. + +```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. \ No newline at end of file diff --git a/process-events.md b/chapters/process-events.md similarity index 52% rename from process-events.md rename to chapters/process-events.md index edec623..f2d6cab 100644 --- a/process-events.md +++ b/chapters/process-events.md @@ -2,22 +2,12 @@ Process Events ============== -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. +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. -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. +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) -When a user logs onto on a modern version of Windows (Windows 2016/10) -they will have 2 Logon IDs assigned if: - -* User is a member of local Administrator Group. - -* UAC (User Access Control) is enabled. - -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. @@ -26,6 +16,12 @@ 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. +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. + +![Linux ProcessGUID Source](./media/image66.png) + +The ProcessGUIs is referenced in several events under different names. + ![ProcessGUID Relation](./media/image32.png) The only Event Types that will not reference a ProcessGuid or one of its @@ -35,7 +31,28 @@ derived names are * Kernel Driver Load +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. + +For Windows + +![LogonGuide Source](./media/image68.png) + +For Linux + +![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: + +* User is a member of local Administrator Group. + +* UAC (User Access Control) is enabled. + +These sessions will be linked by a Linked Login ID in Successful Logon +Event ID 4624, making the logging of this event important. + The image of the process is also related in other processes and can be used to track all actions related to a specific one. ![Image Relation](./media/image33.png) + diff --git a/chapters/process-tampering.md b/chapters/process-tampering.md new file mode 100644 index 0000000..114ff3f --- /dev/null +++ b/chapters/process-tampering.md @@ -0,0 +1,51 @@ +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. + +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) + +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. + +Example: + +```xml +Sysmon schemaversion="4.50"> + + + + + + + + +``` + +Collect events and build a exclusion list like: + +```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 + + +``` + +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. diff --git a/process-termination.md b/chapters/process-termination.md similarity index 100% rename from process-termination.md rename to chapters/process-termination.md diff --git a/chapters/raw-access-read.md b/chapters/raw-access-read.md new file mode 100644 index 0000000..25d0c12 --- /dev/null +++ b/chapters/raw-access-read.md @@ -0,0 +1,29 @@ +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. + +On Linux this event is logged when a block device is directly accessed and eBPF is used to detect this type of action. + +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. + +The fields for the event are: + +* **RuleName**: Name of rule that triggered the event + +* **UtcTime**: Time in UTC when event was created + +* **ProcessGuid**: Process GUID of the process that conducted reading operations from the drive + +* **ProcessId**: Process ID used by the OS to identify the process that conducted reading operations from the drive + +* **Image**: File path of the process that conducted reading operations from the drive + +* **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. + + +Example that captures all instances of this event + +![collect all](./media/image60.png) diff --git a/registry-actions.md b/chapters/registry-actions.md similarity index 100% rename from registry-actions.md rename to chapters/registry-actions.md diff --git a/chapters/sysmon-changelog.md b/chapters/sysmon-changelog.md new file mode 100644 index 0000000..a6915bf --- /dev/null +++ b/chapters/sysmon-changelog.md @@ -0,0 +1,14 @@ +# Sysmon Changelog + +| Version | Schema | Features | Release | +|---------|--------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------| +| 13.01 | 4.50 | * Fixed regression bug where several event types where not logged. | January 13, 2021 | +| 13.0 | 4.50 | * Added support for Process Tampering Detection. | January 11, 2021 | +| 12.03 | 4.40 | * fixes reporting and a possible crash condition for PipeEvent and RegistryEvent rules. | November 25, 2020 | +| 12.02 | 4.40 | * This update to Sysmon fixes several configuration parsing bugs. | November 4, 2020 | +| 12.01 | 4.40 | * Security and bug fix release, resolves a PipeEvent processing issue and adds extra checks to kernel writes. | October 16, 2020 | +| 12.0 | 4.40 | * Added support to capture text stored in to the clipboard by a process. | September 17, 2020 | +| 11.11 | 4.4 | * Fixes a bug that prevented USB media from being ejected.
* Fixes an issue that could stop network event logging and a resulting memory leak.
* Fixes logs file delete events for delete-on-close files. | July 15, 2020 | +| 11.1 | 4.31 | * For Event ID 15 “Content field was added to save text streams of less than 1k.
* The –a commandline option has been removed. The custom archive directory must be set via configuration file.
* Fix Issue where EventID 1 was not logged on Windowds 2016 and Windows 10.
* Fix rule parsing issue. | June 24, 2020 | +| 11.0 | 4.30 | * Control Reverse DNS Lookup.
* Log file deletions and story copy of the file.
* Bug Fixes. | April 28, 2020 | +| 10.42 | 4.23 | * Memory leaks in DNS, Networking and Image load events
* Bug fixes including filtering, rule group names, NULL process GUIDS and W3LOGSVC interop issue
* Increased rule name field length from 32 to 128 characters
* Added “excludes any” and “excludes all” filtering conditions.
* Performance improvements for ImageLoad module | December 11, 2019 | \ No newline at end of file diff --git a/sysmon-events.md b/chapters/sysmon-events.md similarity index 99% rename from sysmon-events.md rename to chapters/sysmon-events.md index acd5b02..e4b3486 100644 --- a/sysmon-events.md +++ b/chapters/sysmon-events.md @@ -43,6 +43,10 @@ Sysmon Events * [WMI Events](#wmi-events) + * [Clipboard Capture](#clipboard-capture.md) + + * [Process Tampering](#process-tampering.md) + Sysmon Operational Events ------------------------- diff --git a/the-sysmon-driver.md b/chapters/the-sysmon-driver.md similarity index 91% rename from the-sysmon-driver.md rename to chapters/the-sysmon-driver.md index a4aca12..76001d6 100644 --- a/the-sysmon-driver.md +++ b/chapters/the-sysmon-driver.md @@ -21,7 +21,6 @@ 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. diff --git a/chapters/what-is-sysmon.md b/chapters/what-is-sysmon.md new file mode 100644 index 0000000..78c4f83 --- /dev/null +++ b/chapters/what-is-sysmon.md @@ -0,0 +1,72 @@ +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. + +The original version the tool was for internal use at Microsoft. Under Windows the tool the tool supports 64-bit and 32-bit systems and uses a single command line tool for installation and configuration management. + +For Linux the tool can be compiled from source or installed via the distribution package manager. It supports the following distributions: + +- 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. diff --git a/examples/Exchange_CVE_2021_26855.xml b/examples/Exchange_CVE_2021_26855.xml new file mode 100644 index 0000000..feef5cb --- /dev/null +++ b/examples/Exchange_CVE_2021_26855.xml @@ -0,0 +1,112 @@ + + + sha256 + + + + + + + \wwwroot\aspnet_client\;owa\auth;ecp\auth\;ClientAccess\Owa\;ClientAccess\Ecp\;ClientAccess\Oab\ + w3wp.exe;UMWorkerProcess.exe;UMService.exe + + + w3wp.exe + UMWorkerProcess.exe + UMService.exe + + .bat;.cmd;.exe;.js;.vbs;.vbe;.dll;.ps1 + .rar;.zip;.7z;.js;.vbs;.vbe;.dll;.ps1 + + + + + + w3wp.exe + UMWorkerProcess.exe + + .exe + + + + + + lsass.exe + + + + + + + C:\Windows\system32\svchost.exe + 0x1000 + + + C:\Windows\system32\wbem\wmiprvse.exe + 0x1400 + + + C:\Windows\System32\svchost.exe + 0x3000 + + + C:\Windows\system32\wbem\wmiprvse.exe + 0x1000 + + + C:\Windows\System32\svchost.exe + 0x1000 + + + C:\Windows\system32\services.exe + 0x1000 + + + C:\Windows\system32\wininit.exe + 0x1000000 + + + C:\Windows\system32\csrss.exe + 0x1fffff + + + C:\Windows\system32\wininit.exe + 0x1fffff + + + + + + + + powershell.exe;powershell_ise.exe + System.Management.Automation + + + + + + + C:\Windows\System32\ServerManager.exe + C:\Windows\System32\RemoteFXvGPUDisablement.exe + + + + diff --git a/examples/FileDeleteDetected.xml b/examples/FileDeleteDetected.xml new file mode 100644 index 0000000..224abb2 --- /dev/null +++ b/examples/FileDeleteDetected.xml @@ -0,0 +1,186 @@ + + + sha256 + + + Archive + + + + + + \Appdata\Local\Microsoft\Windows\INetCache\Content.Outlook\ + .com;.bat;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.xla;.cmd;.sh;.lnk;.pptm;.scr;.sct + + + \Downloads\ + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + \Appdata\Local\Temp\ + .com;.bat;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.xla;.cmd;.sh;.lnk;.pptm;.scr;.sct + + + + C:\ProgramData\Intel + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\ProgramData\Mozilla + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\ProgramData\chocolatey\logs + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\ProgramData\Microsoft\DeviceSync + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\ProgramData\Microsoft\PlayReady + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\ProgramData\Microsoft\User Account Pictures + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\ProgramData\Microsoft\Crypto\DSS\MachineKeys + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\ProgramData\Microsoft\NetFramework\BreadcrumbStore + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\ProgramData\Microsoft\Office\Heartbeat + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\ProgramData\Microsoft\Windows\WER\ReportQueue + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\ProgramData\Microsoft\Windows\WER\Temp + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\ProgramData\Microsoft\Windows\WER\Temp + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\ProgramData\Microsoft\Windows\WER\Temp + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\ProgramData\Microsoft\Windows\WER\Temp + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\ProgramData\Microsoft\Windows\WER\Temp + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\Users\All Users\Intel + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\Users\All Users\Mozilla + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\Users\All Users\chocolatey\logs + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\Users\All Users\Microsoft\DeviceSync + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\Users\All Users\Microsoft\PlayReady + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\Users\All Users\Microsoft\User Account Pictures + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\Users\All Users\Microsoft\Crypto\DSS\MachineKeys + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\Users\All Users\Microsoft\Crypto\RSA\MachineKeys + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\Users\All Users\Microsoft\NetFramework\BreadcrumbStore + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\Users\All Users\Microsoft\Office\Heartbeat + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\Users\All Users\Microsoft\Windows\WER\ReportArchive + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\Users\All Users\Microsoft\Windows\WER\ReportQueue + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\Users\All Users\Microsoft\Windows\WER\Temp + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\Windows\Tasks + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\Windows\tracing + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\Windows\Registration\CRMLog + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\Windows\System32\Tasks + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\Windows\System32\spool\drivers\color + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + C:\Windows\SysWOW64\Tasks + .com;.bat;.exe;.reg;.ps1;.vbs;.vba;.lnk;.doc;.xls;.hta;.bin;.7z;.dll;.xla;.cmd;.sh;.lnk;.pptm;.scr;.msi;.sct + + + + + + + + + \Downloads\ + .exe;dll;.msi;.7z;.zip + + + \Appdata\Local\Temp\ + .exe;dll;.msi;.7z;.zip + + + + + diff --git a/examples/NetConnBaseline.xml b/examples/NetConnBaseline.xml new file mode 100644 index 0000000..0c1dd12 --- /dev/null +++ b/examples/NetConnBaseline.xml @@ -0,0 +1,80 @@ + NT AUTHORITY\SYSTEM + + + C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe + 443;80 + + + C:\Windows\SystemApps\Microsoft.Windows.Search_;\SearchApp.exe + 443;80 + + + C:\Windows\System32\smartscreen.exe + 443 + + + C:\Program Files\WindowsApps\;\LocalBridge.exe + 443 + + + C:\Windows\System32\taskhostw.exe + 443;389 + NT AUTHORITY\SYSTEM + + + C:\Windows\System32\lsass.exe + 88;135;389 + NT AUTHORITY\SYSTEM + + + C:\Program Files\WindowsApps\Microsoft.YourPhone;\YourPhone.exe + 443 + + + C:\Windows\System32\taskhostw.exe + 389 + NT AUTHORITY\SYSTEM + + + C:\Program Files\WindowsApps\Microsoft.Windows.Photos;\Microsoft.Photos.exe + 443 + + + C:\Windows\System32\CompatTelRunner.exe + 443 + NT AUTHORITY\SYSTEM + + + C:\Program Files (x86)\Microsoft\EdgeUpdate\MicrosoftEdgeUpdate.exe + 443 + NT AUTHORITY\SYSTEM + + + C:\Program Files\WindowsApps\Microsoft.XboxGamingOverlay;\GameBar.exe + 443 + + + C:\Windows\System32\BackgroundTransferHost.exe + 443 + + + C:\Windows\System32\RuntimeBroker.exe + 443 + + + C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe + 80;443 + + + C:\Windows\System32\backgroundTaskHost.exe + 135;389 + + + C:\Windows\System32\MoUsoCoreWorker.exe + 443 + NT AUTHORITY\SYSTEM + + + + + diff --git a/process-creation.md b/process-creation.md deleted file mode 100644 index b9772b9..0000000 --- a/process-creation.md +++ /dev/null @@ -1,66 +0,0 @@ - -Process Creation -================ - -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 fields on a process creation event are: - -* **ProcessGuid** -- Unique process GUID generated by Sysmon. - -* **ProcessId** -- Process ID represented as a integer number. - -* **Image** -- Full path of the executable image that was executed. - -* **FileVersion** -- File version filed in the image metadata. - -* **Description** -- Description field in the image metadata. - -* **Product** -- Product field in the image metadata. - -* **Company** - Company field in the image metadata. - -* **OriginalFileName** -- Original image name if renamed. - -* **CommandLine** -- Command line that executed the image. - -* **CurrentDirectory** -- Directory under which the image was - executed. - -* **User** - Name of the account who created the process (child) . It - usually contains domain name and user name - -* **LogonGuid** - Logon GUID of the user who created the new process. - -* **LogonId** -Login ID of the user who created the new process. - -* **TerminalSessionId** - ID of the session the user belongs to - -* **IntegrityLevel** - Integrity label assigned to a process - -* **Hashes** - Full hash of the file with the algorithms in the - HashType field. - -* **ParentProcessGuid** - ProcessGUID of the process that - spawned/created the main process (child) - -* **ParentProcessId** - Process ID of the process that spawned/created - the main process (child) - -* **ParentImage -** File path that spawned/created the main process. - -* **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. \ No newline at end of file diff --git a/raw-access-read.md b/raw-access-read.md deleted file mode 100644 index 5a30ef6..0000000 --- a/raw-access-read.md +++ /dev/null @@ -1,26 +0,0 @@ -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. - -The fields for the event are: - -* **RuleName**: Name of rule that triggered the event - -* **UtcTime**: Time in UTC when event was created - -* **ProcessGuid**: Process GUID of the process that conducted reading operations from the drive - -* **ProcessId**: Process ID used by the OS to identify the process that conducted reading operations from the drive - -* **Image**: File path of the process that conducted reading operations from the drive - -* **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 - -![collect all](./media/image60.png) diff --git a/what-is-sysmon.md b/what-is-sysmon.md deleted file mode 100644 index 8b19031..0000000 --- a/what-is-sysmon.md +++ /dev/null @@ -1,38 +0,0 @@ -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