Windows application event log event id

Introduction to Windows Event Logs and the tools to query them.

Event Logs are recorded events occurring in the execution of a system. This provided audit trail can be utilized to understand activity and diagnosis of a system. This includes complex systems with little user interaction.

A defender can use event logs to combine entries from multiple sources with statistical analysis to view possible correlations. SIEM’s can be used to accomplish this in a large enterprise environment where one can view the logs from all the endpoints, appliances, etc. to query the logs from multiple devices instead of manually connecting to a single device to view its logs.

The Windows Event Logs are not text files that can be viewed using a text editor. The raw data can be translated into XML using the Windows API. The events in these log files are stored in a proprietary binary format with a .evt or .evtx extension. The log files with the .evtx file extension typically reside in C:\Windows\System32\winevt\Logs.

Elements of a Windows Event Log

Event logs are used to troubleshoot incidents and understanding the situation and to remediate.

Elements in event logs in Windows systems are:

  • System Logs: Records events associated with the Operating System segments. They may include information about hardware changes, device drivers, system changes, and other activities related to the device.

  • Security Logs: Records events connected to logon and logoff activities on a device. The system’s audit policy specifies the events. The logs are an excellent source for analysts to investigate attempted or successful unauthorized activity.

  • Application Logs: Records events related to applications installed on a system. The main pieces of information include application errors, events, and warnings.

  • Directory Service Events: Active Directory changes and activities are recorded in these logs, mainly on domain controllers.

  • File Replication Service Events: Records events associated with Windows Servers during the sharing of Group Policies and logon scripts to domain controllers, from where they may be accessed by the users through the client servers.

  • DNS Event Logs: DNS servers use these logs to record domain events and to map out.

  • Custom Logs: Events are logged by applications that require custom data storage. This allows applications to control the log size or attach other parameters, such as ACLs, for security purposes.

Event logs can be classified into types to describe the activity resulting a logged event.

Event type

Description

Error

Indicates a significant problem such as loss of data or functionality.

Warning

May indicate a possible future problem.

Information

Describes successful operation of an application, driver, or service.

Success Audit

Recorded audited security access attempt that is successful.

Failure Audit

Recorded audited security access attempt that fails.

Recorded audited security access attempt that is successful.

Three main ways of accessing these event logs within a Windows system:

  1. 1.

    Event Viewer (GUI-based application)

  2. 2.

    Wevtutil.exe (command-line tool)

  3. 3.

    Get-WinEvent (PowerShell cmdlet)

In any Windows system, the Event Viewer, a Microsoft Management Console (MMC) snap-in, can be launched by simply right-clicking the Windows icon in the taskbar and selecting Event Viewer. For the savvy sysadmins that use the CLI much of their day, Event Viewer can be launched by typing eventvwr.msc. It is a GUI-based application that allows you to interact quickly with and analyze logs.

Event Viewer has three panes.

  1. 1.

    The pane on the left provides a hierarchical tree listing of the event log providers.

  2. 2.

    The pane in the middle will display a general overview and summary of the events specific to a selected provider.

  3. 3.

    The pane on the right is the actions pane.

The following section is the Applications and Services Logs. Expand this section and drill down on Microsoft > Windows > PowerShell > Operational. PowerShell will log operations from the engine, providers, and cmdlets to the Windows event log.
Right-click on
Operational then Properties.

Within Properties, we see the log location, log size, and when it was created, modified, and last accessed. Within the Properties window, we can also see the maximum set log size and what action to take once the criteria are met. This concept is known as log rotation. These are discussions held with corporations of various sizes. How long does it take to keep logs, and when it’s permissible to overwrite them with new data.

Lastly, noticing the Clear Log button at the bottom right. Know there are legitimate reasons to use this button, such as during security maintenance, but adversaries will likely attempt to clear the logs to go undetected. Note: This is not the only method to remove the event logs for any given event provider.

Focusing on the middle pane, we can display the events specific to a selected provider. In this case, PowerShell/Operational.

The event provider’s name and the number of events logged and displayed here.

Each column of the pane presents a particular type of information as described below:

  • Level: Highlights the log recorded type based on the identified event types specified earlier. In this case, the log is labeled as Information.

  • Date and Time: Highlights the time at which the event was logged.

  • Source: The name of the software that logs the event is identified. From the above image, the source is PowerShell.

  • Event ID: This is a predefined numerical value that maps to a specific operation or event based on the log source. This makes Event IDs not unique, so Event ID 4103 in the above image is related to Executing Pipeline but will have an entirely different meaning in another event log.

  • Task Category: Highlights the Event Category. This entry will help you organize events so the Event Viewer can filter them. The event source defines this column.

The middle pane has a split view. More information is displayed in the bottom half of the middle pane for any event you click on.
This section has two tabs:
General and Details.

  • General is the default view, and the rendered data is displayed.

  • The Details view has two options: Friendly view and XML view.

Lastly, we can open a saved log within the Actions pane. This is useful if the remote machine can’t be accessed. The logs can be provided to the analyst.

The Create Custom View and Filter Current Log are nearly identical. The only difference between the 2 is that the By log and By source radio buttons are greyed out in Filter Current Log. What is the reason for that? The filter we can make with this specific action only relates to the current log. Hence no reason for by log or by source to be enabled.

Why are these actions beneficial? If we don’t want all the events associated with PowerShell/Operational cluttering all the real estate in the pane and are only interested in 4104 events. That is possible with these two actions.

To view event logs from another computer, right-click Event Viewer (Local) > Connect to Another Computer...

Connect to Another Computer

What is the Event ID for the first recorded event?

Filter on Event ID 4104. What was the 2nd command executed in the PowerShell session?

What is the Task Category for Event ID 4104?

Analyze the Windows PowerShell log. What is the Task Category for Event ID 800?

Pipeline Execution Details

Wevtutil.exe is a tool that can be utilized for allowing querying of event logs via command line and Powershell. An addition to the tool is the ability to install/uninstall event manifests, run queries, and to export/archive/clear logs.

Under Usage is a brief example of how to use the tool. ep (enum-publishers) is used as a command for wevtutil.exe.

Next are Common options that can be used with WIndows Events Utility.

The bottom of the command prompt shows wevtutil COMMAND /?. This provides additional information specific to a command. Ex, to get more information on the command qe (query-events):

How many log names are in the machine?

What event files would be read when using the query-events command?

event log, log file, structured query

What option would you use to provide a path to a log file?

What is the VALUE for /q?

The questions below are based on this command: wevtutil qe Application /c:3 /rd:true /f:text

What is the /rd option for?

What is the /c option for?

Maximum number of events to read

The Powershell cmdlet Get-WinEvent gets events from event logs and event tracing log files as well as remote computers. This cmdlet provides information on event logs and providers and allows for combining numerous events from multiple sources. This is put into a single command and filter using XPath, structured XML, and hash table queries.

The Get-WinEvent cmdlet replaces the Get-EventLog cmdlet.

Example 1: Get all logs from a computer

Below describes how to obtainall event logs locally. The list starts with class logs before listing new Window Event logs. The RecordCount be zero or null.

Example 2: Get event log providers and log names

Theis command results in the event log providers and their associated logs. The Name is the provider, and LogLinks is the log that is written to.

Log filtering allows for selecting events from an event log. Filter event logs using the Where-Object cmdlet as follows:

-LogName Application | Where-Object

It’s inefficient to send objects down the pipeline to a Where-Object command when working with large event logs. The use of the Get-WinEvent cmdlet’s FilterHashtable parameter is recommended to filter event logs. Achieve the same results as above by running the following command:

Get-WinEvent FilterHashtable @{

The syntax of a hash table is as follows:

@{ <name> = <value>; [<name> = <value> ] }

Guidelines for defining a hash table are:

  • Begin the hash table with an @ sign.

  • Enclose the hash table in braces {}

  • Enter one or more key-value pairs for the content of the hash table.

  • Use an equal sign (=) to separate each key from its value.

A semicolon is not needed if each key/value is seperated with a new line, as shown above for the -FilterHashtable for ProviderName='WLMS'.

The accepted key/value pairs for the Get-WinEvent FilterHashtable parameter:

Key name

Value data type

Accepts wildcard characters?

LogName

<String[]>

Yes

ProviderName

<String[]>

Yes

Path

<String[]>

No

Keywords

<Long[]>

No

ID

<Int32>

No

Level

<Int32>

No

StartTime

<DateTime>

No

EndTime

<DateTime>

No

UserID

<SID>

No

Data

<String[]>

No

<named-data>

<String[]>

No

Microsoft recommends making the hash table one key-value pair at a time when building a query. Event viewer can provide information on what is needed to build the hash table.

Using the information above, create a hash table:

Get-WinEvent FilterHashtable @{

An example of a Git-WinEvent and FilterHashtable command/syntax:

Get-WinEvent FilterHashtable @{LogName=‘Microsoft-Windows-PowerShell/Operational’; ID=4104} | Select-Object Property Message | Select-String Pattern ‘SecureString’

More about creating hash tables can be found

here

.

Answer the following questions using the

online

help documentation for Get-WinEvent

Execute the command from Example 1 (as is). What are the names of the logs related to OpenSSH?

OpenSSH/Admin,OpenSSH/Operational

Execute the command from Example 8. Instead of the string Policy search for PowerShell. What is the name of the 3rd log provider?

Microsoft-Windows-Powershell-DesiredStateConfiguration-FileDownloadManager

Execute the command from Example 9. Use Microsoft-Windows-PowerShell as the log provider. How many event ids are displayed for this event provider?

192 — Omit the first Line

How do you specify the number of events to display?

When using the FilterHashtable parameter and filtering by level, what is the value for Informational?

XPath (XML Path Language) provides standard syntax and semantics for addressing parts of an XML document and manipulating strings, numbers, and booleans. The Windows Event Log supports a subset of

XPath 1.0

.

Below is an example XPath query along with its explanation:

// The following query selects all events from the channel or log file where the severity level is less than or equal to 3 and the event occurred in the last 24 hour period.

XPath Query: *[System[(Level <= 3) and TimeCreated[timediff(@SystemTime) <= 86400000]]]

XPath event query starts with ‘*‘ or ‘Event‘.

Both wevtutil and Get-WinEvent support XPath queries as event filters.

Click on the Details tab and select the XML View radio button to understand how to use the XML View to construct a valid XPath query.

The first tag is the starting point. This can either be an * or the word Event.

The command so far looks like this: Get-WinEvent -LogName Application -FilterXPath '*'

Add that to the command: Get-WinEvent -LogName Application -FilterXPath '*/System/'

Note: Its best practice to explicitly use the keyword System but can use an * instead as with the Event keyword. The query -FilterXPath '*/*' is still valid.

The Event ID is 100. Plug that into the command.

The command now is: Get-WinEvent -LogName Application -FilterXPath '*/System/EventID=100'

When using wevtutil.exe and XPath to query for the same event log and ID, this is the result:

Two additional parameters were used in the above command to retrieve one event and for it not to contain any XML tags.

to query a different element, such as Provider Name, the syntax will be different. To filter on the provider, use the Name attribute of Provider

In the syntax above, the Provider Name is WLMS, and there are two Event IDs. Below will only query for events with Event ID 101:

Create XPath queries for elements within EventData.

The EventData element doesn’t always contain information.

Below is the XML View of the event for which we will build our XPath query.

Build the query for TargetUserName. In this case, that will be System. The XPath query would be:

The -MaxEvents parameter was used, and it was set to 1 to return one event.

Using Get-WinEvent and XPath, what is the query to find WLMS events with a System Time of 2020-12-15T01:09:08.940277500Z?

Get-Event -LogName Application -FilterXPath '*/System/Provider[@Name="WLMS"] and */System/TimeCreated[@SystemTime="2020-12-15T01:09:08.940277500Z"]'

Using Get-WinEvent and XPath, what is the query to find a user named Sam with an Logon Event ID of 4720?

Get-WinEvent -LogName Security -FilterXPath '*/EventData/Data[@Name="TargetUserName"]="Sam" and */System/EventID=4720'

Based on the previous query, how many results are returned?

Based on the output from the question #2, what is Message?

A user account was created

Still working with Sam as the user, what time was Event ID 4724 recorded? (MM/DD/YYYY H:MM:SS [AM/PM])

What is the Provider Name?

Microsoft-Windows-Security-Auditing

Some events will not be generated by default, and certain features will need to be enabled/configured on the endpoint, such as PowerShell logging. This feature can be enabled via Group Policy or the Registry.

Local Computer Policy > Computer Configuration > Administrative Templates > Windows Components > Windows PowerShell

Local Group Policy Editor

Some resources to provide more information about enabling this feature, along with its associated event IDs:

Another feature to enable/configure is Audit Process Creation, which will generate event ID 4688. This will allow command-line process auditing.

Local Computer Policy > Computer Configuration > Administrative Templates > System > Audit Process Creation

Putting Theory Into Practice

The next scenarios/questions are based on the external event log file titled merged.evtx found on the Desktop.

Scenario 1 (Questions 1 & 2): The server admins have made numerous complaints to Management regarding PowerShell being blocked in the environment. Management finally approved the usage of PowerShell within the environment. Visibility is now needed to ensure there are no gaps in coverage. You researched this topic: what logs to look at, what event IDs to monitor, etc. You enabled PowerShell logging on a test machine and had a colleague execute various commands.

What event ID is to detect a PowerShell downgrade attack?

What is the Date and Time this attack took place? (MM/DD/YYYY H:MM:SS [AM/PM])

Scenario 2 (Questions 3 & 4): The Security Team is using Event Logs more. They want to ensure they can monitor if event logs are cleared. You assigned a colleague to execute this action.

A Log clear event was recorded. What is the ‘Event Record ID’?

What is the name of the computer?

Scenario 3 (Questions 5, 6 & 7): The threat intel team shared its research on Emotet. They advised searching for event ID 4104 and the text «ScriptBlockText» within the EventData element. Find the encoded PowerShell payload.

What is the name of the first variable within the PowerShell command?

What is the Date and Time this attack took place? (MM/DD/YYYY H:MM:SS [AM/PM])

What is the Execution Process ID?

Scenario 4 (Questions 8 & 9): A report came in that an intern was suspected of running unusual commands on her machine, such as enumerating members of the Administrators group. A senior analyst suggested searching for «C:\Windows\System32\net1.exe«. Confirm the suspicion.

What is the Group Security ID of the group she enumerated?

This is my write-up on THM’s Windows Event Logs Room.


Task 1: What are event logs?

Event logs essentially contain the records of events or activities that have transpired in a machine or host, that would help system administrators, IT technicians, etc, audit and trouble shoot issues in the system.

But for blue teams, windows event logs serve a different purpose. These logs are analyzed for malicious activities or indicators of compromise. Windows Event Logs can also be forwarded to SIEMs where analyst can aggregate, analyze, and correlate log data from various sources to provide security insights of a network.

For a Linux system, the logging system is knows as Syslog.


Task 2: Event Viewer

The Windows Event Logs are stored with an .evt or .evtx extension and are located in C:\\Windows\\System32\\winevt\\Logs.

Before moving on to Event Viewer, we first need to understand the different elements of a Windows Event Logs system. This would help us understand where to look at if we are trying to solve an issue or analyzing a specific kind of event.

  • System Logs: Records events associated with the Operating System segments. They may include information about hardware changes, device drivers, system changes, and other activities related to the device.
  • Security Logs: Records events connected to logon and logoff activities on a device. The system’s audit policy specifies the events.
  • Application Logs: Records events related to applications installed on a system. The main pieces of information include application errors, events, and warnings.
  • Directory Service Events: Active Directory changes and activities are recorded in these logs, mainly on domain controllers.
  • File Replication Service Events: Records events associated with Windows Servers during the sharing of Group Policies and logon scripts to domain controllers, from where they may be accessed by the users through the client servers.
  • DNS Event Logs: DNS servers use these logs to record domain events and to map out
  • Custom Logs: Events are logged by applications that require custom data storage. This allows applications to control the log size or attach other parameters, such as ACLs, for security purposes.

The following table describes the five event types used in event logging.

Event type Description
Error An event that indicates a significant problem such as loss of data or loss of functionality. For example, if a service fails to load during startup, an Error event is logged.
Warning An event that is not necessarily significant, but may indicate a possible future problem. For example, when disk space is low, a Warning event is logged. If an application can recover from an event without loss of functionality or data, it can generally classify the event as a Warning event.
Information An event that describes the successful operation of an application, driver, or service. For example, when a network driver loads successfully, it may be appropriate to log an Information event. Note that it is generally inappropriate for a desktop application to log an event each time it starts.
Success Audit An event that records an audited security access attempt that is successful. For example, a user’s successful attempt to log on to the system is logged as a Success Audit event.
Failure Audit An event that records an audited security access attempt that fails. For example, if a user tries to access a network drive and fails, the attempt is logged as a Failure Audit event.

Event Viewer

The Windows Event Logs can be accessed with three methods; Event Viewer, Wevtutil.exe (command-line), and Get-WinEvent (PowerShell). The latter two methods will be discussed in the succeeding tasks.

Event Viewer allows interaction with and analyzing the logs in a GUI application.

Event Viewer can be started by right-clicking the Windows icon and selecting Event Viewer.

Or by typing “eventvwr.msc” in the command line.

Answer the questions below

For the questions below, use Event Viewer to analyze Microsoft-Windows-PowerShell/Operational log.

What is the Event ID for the first recorded event?

Answer: 40961

Open Event Viewer and go to Applications and Services Logs then to Microsoft > Powershell > Operational log.

The first event is found at the bottom of the window pane. We can also click on “Date and Time” column to sort the events based on the date and time of the occurrence of events.

Filter on Event ID 4104. What was the 2nd command executed in the PowerShell session?

Answer: whoami

To create a filter, go to the right pane. Under “Operational” click on “Filter current Log”

We will filter the events with the Event ID 4104.

Once the results are in, sort the events based on date and time. Select the second event. Select the “Details” tab and the PowerShell command is displayed with the tag “ScriptBlockText”.

What is the Task Category for Event ID 4104?

Answer: Execute a Remote Command

We can find the answer by looking at the middle pane, similar to the image above. The “Task Category” column shows the category for Event ID 4104.

Analyze the Windows PowerShell log. What is the Task Category for Event ID 800?

Answer: Pipeline Execution Details

Clear the filter first. We would be returned to the same PowerShell event logs.

The middle pane, under the “Task Category” column would show the task category for Event ID 800.


Task 3: wevtutil.exe

Wevtutil.exe (Windows Event Utility) is a command line tool that would help us query event logs. By writing scripts with this tool, we would be more efficient in sifting through thousands of event logs.

To access its help files, we will run wevtutil.exe /?.

The tool would follow this syntax.

  • wevtutil COMMAND [ARGUMENT [ARGUMENT] …] [/OPTION:VALUE [/OPTION:VALUE] …]

The commands are the following:

el  | enum-logs        List log names.
gl  | get-log          Get log configuration information.
sl  | set-log          Modify configuration of a log.
ep  | enum-publishers  List event publishers.
gp  | get-publisher    Get publisher configuration information.
im  | install-manifest Install event publishers and logs from manifest.
um  | uninstall-manifest Uninstall event publishers and logs from manifest.
qe  | query-events     Query events from a log or log file.
gli | get-log-info     Get log status information.
epl | export-log       Export a log.
al  | archive-log      Archive an exported log.
cl  | clear-log        Clear a log.

Note: We can use the short or long versions of the command, example el or enum-logs

Common options are;

Common Options:

/{r | remote}:VALUE
If specified, run the command on a remote computer. VALUE is the remote computer name. Options /im and /um do not support remote operations.

/{u |username}:VALUE
Specify a different user to log on to the remote computer. VALUE is a user name in the form of domain\\user or user. Only applicable when option /r is specified.

/{p | password}:VALUE
Password for the specified user. If not specified, or if VALUE is "*", the user will be prompted to enter a password. Only applicable when the /u option is specified.

/{a | authentication}:[Default|Negotiate|Kerberos|NTLM]
Authentication type for connecting to remote computer. The default is Negotiate.

/uni | unicode}:[true|false]
Display output in Unicode. If true, then output is in Unicode.

To learn more about a specific command, type the following:

wevtutil COMMAND /?

If we want to know how to use a specific command, as provided in the help files, we will use wevtutil COMMAND /?. For example, if we want to get more information on the command qe (query-events), we would use wevtutil qe /?.

More info can be found on docs.microsoft.com.

Answer the questions below

How many log names are in the machine?

Answer: 1071

The command el would list the log names and the results would then be piped to the next command to count the list of log names by line.

wevtutil el | Measure-Object -Line

What event files would be read when using the query-events command?

Answer: event log, log file, structured query

For us to find more info about the command, we would use wevtutil qe /?.

What option would you use to provide a path to a log file?

Answer: /lf:true

After running the command, we see the options we can use with qe. The option we would use to include a log file path is /lf:true.

What is the VALUE for /q?

Answer: query XPATH

Scrolling through the options, we can see the value for /q? is XPATH query.

The questions below are based on this command: wevtutil qe Application /c:3 /rd:true /f:text

What is the log name?

Answer: Application

From the command given to us, wevtutil is querying events from Application logs.

What is the /rd option for?

Answer: event read redirection

When we run wevtutil qe /?, we would see the options for this command. /rd would refer to event read redirection.

What is the /c option for?

Answer: Maximum number of events to read

/c option refers to the number of events that we wold want to query from the logs.


Task 4: Get-WinEvent

Get-WinEventis a Powershell cmdlet. Per Microsoft, the Get-WinEvent cmdlet “gets events from event logs and event tracing log files on local and remote computers.” The tool can provide information on event logs and event log providers. We can also combine events from different sources by using a single command and filtering these events with XPath queries, structured XML queries, and hash table queries.

Note: The Get-WinEvent cmdlet replaced the Get-EventLog cmdlet.

Refer to the Get-Help information online at docs.microsoft.com.

Examples of how to use Get-WinEvent

Example 1: Get all logs from a computer

The first list will be classic logs, then by new Windows Event logs. RecordCount can have zero or null logs.

Example 2: Get event log providers and log names

This will get us the event log providers and their associated logs. The Name is the provider, and LogLinks is the log that is written to.

Get-WinEvent -ListProvider *

Example 3: Log filtering

Log filtering allows us to select events from an event log. We can then filter event logs from a specific Provider using the Where-Object cmdlet:

Get-WinEvent -LogName Application | Where-Object { $_.ProviderName -Match 'WLMS' }

Where-Object is inefficient to use when working with large event logs. Therefore, the suggested Get-WinEvent cmdlet’s FilterHashtable parameter is recommended to filter event logs.

Get-WinEvent -FilterHashtable @{
LogName='Application'
ProviderName='WLMS'
}
Get-WinEvent -FilterHashtable @{ LogName='Application'; ProviderName= 'WLMS'} 

The syntax of a hash table is as follows:

@{ <name> = <value>; [<name> = <value> ] ...}

Guidelines for defining a hash table are:

  • Begin the hash table with an @ sign.
  • Enclose the hash table in braces {}
  • Enter one or more key-value pairs for the content of the hash table.
  • Use an equal sign (=) to separate each key from its value.

Note: Using semicolon is not needed if each key/value are separated with a new line, as in the first set of commands above for the -FilterHashtable for ProviderName='WLMS'.

Below is a table that displays the accepted key/value pairs for the Get-WinEvent FilterHashtable parameter.

Key name Value data type Accepts wildcard characters?
LogName <String[]> Yes
ProviderName <String[]> Yes
Path <String[]> No
Keywords <Long[]> No
ID <Int32[]> No
Level <Int32[]> No
StartTime <DateTime> No
EndTime <DateTime> No
UserID <SID> No
Data <String[]> No
<named-data> <String[]> No

Check the official Microsoft documentation docs.micro-soft.com for more info on querying using Filterhashtable.

Here is a command by @mubix on using Get-WinEvent -FilterHashtable

Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational'; ID=4104} | Select-Object -Property Message | Select-String -Pattern 'SecureString'

Answer the questions below

Answer the following questions using the online help documentation for Get-WinEvent

Execute the command from Example 1 (as is). What are the names of the logs related to OpenSSH?

Answer: OpenSSH/Admin,OpenSSH/Operational

We will use the command from example 1, then pipe the result to find the strings that matches ssh. We see two logs being displayed.

Get-WinEvent -ListLog * | findstr /i ssh

Execute the command from Example 8. Instead of the string Policy search for PowerShell. What is the name of the 3rd log provider?

Answer: Microsoft-Windows-PowerShell-DesiredStateConfiguration-FileDownloadManager

We will simply copy the command and change the string policy to Powershell. This will display all events relatd to the filter.

Get-WinEvent -ListProvider *Powershell*

Alternatively, we can modify the command to display only the third log provider.

Get-WinEvent -ListProvider *Powershell* | Select-Object -Property Name -Skip 2 -First 1

Execute the command from Example 9. Use Microsoft-Windows-PowerShell as the log provider. How many event ids are displayed for this event provider?

Answer: 192

We will be using the provided command and changing the log provider to Microsoft-Windows-PowerShell. We will also be modifying it by adding Measure-Object -Line to count the results by line.

(Get-WinEvent -ListProvider Microsoft-Windows-PowerShell).Events | Format-Table Id, Description | Measure-Object -Line

How do you specify the number of events to display?

Answer: -MaxEvents

Example 13 provided us the options we can use to display only a certain number of events.

If we want to know more about -MaxEvents, we could use the Get-Help cmdlet.

When using the FilterHashtable parameter and filtering by level, what is the value for Informational?

Answer: 4

This resource for FilterHashtable contains the numerical value of each Level.


Task 5: XPath Queries

The third method of filtering events is by using XPath or XML Path Language, which was created by W3C. The Windows Event Log supports a subset of XPath 1.0.

Here is an example of an XPath query along with its explanation:

// The following query selects all events from the channel or log file where the severity level is less than or equal to 3 and the event occurred in the last 24 hour period.
XPath Query: *[System[(Level <= 3) and TimeCreated[timediff(@SystemTime) <= 86400000]]]

See docs.microsoft.com for more examples of XPath queries. 

Note: An XPath event query starts with ‘*’ or ‘Event‘. wevtutil and Get-WinEvent support XPath queries.

To create an XPath query, Event Viewer would be the reference point.

We look at the bottom of the middle pane, click on the “Details” tab and select the “XML View”. The sructure presented would help use construct a valid XPath query.

The first tag is the starting point. This can either be an ‘*' or Event.

The command would look like this:

Get-WinEvent -LogName Application -FilterXPath '*'

Working our way down, the next tag is System.

Let’s add that to our command:

Get-WinEvetnt -LogName Application -FilterXPath '*/System/'

Next is the EventID tag. We would use the tag name and include the Event ID we want to filter. In this example, the Event ID is 100.

The command would look like something like this:

Get-WinEvetnt -LogName Application -FilterXPath '*/System/EventID=100'

The following would be the result if using wevtutil.exe and XPath to query for the same event log and ID.:

wevtutil.exe qe Application /q:*/System[EventID=100] /f:text /c:1

Two additional options were added to filter only one event with no XML tags.

If we want to query a different element, such as the Provider Name, we need to use the Name attribute of Provider.

Therefore, to query for the Provider name with XPath:

Get-WinEvent -LogName Application -FilterXPath '*/System/Provider[@Name="WLMS"]'

We can also combine two queries in one command.

For example, if we want to query Event IDs of 100 with the Provider Name “WLMS”, we would arrive at this command:

Get-WinEvent -LogName Application -FilterXPath '*/System/Provider[@Name="WLMS"]'

Creating XPath queries with EventData

Querying for elements within EventData with XPath will be a little bit different

Note: The EventData element doesn’t always contain information.

We will use the below XML view of an event to build the XPath query

For this example, we will be creating a query for the TargetUserName of System. The XPath query would be:

Get-WinEvent -LogName Security -FilterXPath '*/EventData/Data[@Name="TargetUserName"]="System"' -MaxEvents 1

The parameter -MaxEvents will return just 1 event.

Read the official Microsoft XPath Reference for more information.

Answer the questions below

Using the knowledge gained on Get-WinEvent and XPath, what is the query to find WLMS events with a System Time of 2020-12-15T01:09:08.940277500Z?

Answer: Get-WinEvent -LogName Application -FilterXPath ‘*/System/Provider[@Name=”WLMS”] and */System/TimeCreated[@SystemTime=”2020-12-15T01:09:08.940277500Z”]’

The steps provided above in building an XPath query would help us create the command.

Using Get-WinEvent and XPath, what is the query to find a user named Sam with an Logon Event ID of 4720?

Answer: Get-WinEvent -LogName Security -FilterXPath ‘*/EventData/Data[@Name=”TargetUserName”]=”Sam” and */System/EventID=4720’

We will be be creating two queries in one command. The first query is to query within the EventData the tag TargetUsername, and specifying the username to be “Sam”. The second query is within Event, looking through System, and specifying the EventID of 4720.

Based on the previous query, how many results are returned?

Answer: 2

We got two results.

Based on the output from the question #2, what is Message?

Answer: A user account was created

The query filters user account creation.

Still working with Sam as the user, what time was Event ID 4724 recorded? (MM/DD/YYYY H:MM:SS [AM/PM])

Answer: 12/17/2020 1:57:14 PM

Working with the same command from above, we just need to change the EventID to 4724.

Get-WinEvent -LogName Security -FilterXPath '*/EventData/Data[@Name="TargetUserName"]="Sam" and */System/EventID=4724'

What is the Provider Name?

Answer: Microsoft-Windows-Security-Auditing

We found the answer when we run the command from above.


Task 6: Event IDs

With the large number of Event IDs in use, we will definitely need resources to help us monitor and hunt events. This section will be covering us in that aspect.

First on the list is The Windows Logging Cheat Sheet (Windows 7 – Windows 2012). The last version update is October 2016, but it’s still a good resource. The document covers a few things that need to be enabled and configured and what event IDs to look for based on different categories, such as Accounts, Processes, Log Clear, etc.

From the resource, if we want to detect if a new service was installed, look for Event ID 7045 within the System Log. The command would be as follows

wevtutil qe System /q:"*/System[EventID=7045]" /c:5 /rd:true /f:text

Spotting the Adversary with Windows Event Log Monitoring is another resource.

I was unable though to connect and download the resource.

But from the room, a snippet is provided from the document where we see Event IDs related to Firewall Rules.

MITRE ATT&CK is also on the list for monitoring or hunting Event IDs.

We can look at a Technique and identify the related Event IDs that we should monitor and hunt. For example, if we look at ATT&CK ID T1098 (Account Manipulation), the “Detection” section contains the Event IDs that are triggered.

The MITRE ATT&CK framework also contains information on how to mitigate each techniques.

The last two resources are from Microsoft:

  • Events to Monitor (Best Practices for Securing Active Directory)
  • The Windows 10 and Windows Server 2016 Security Auditing and Monitoring Reference (a comprehensive list [over 700 pages])
  • Here is a snippet of the 700-page Windows 10 and Windows Server 2016 Security Auditing and Monitoring Reference

Note: There are certain events that are not generated by default, one of them is PowerShell logging. This feature can be enabled via Group Policy or the Registry.

Local Computer Policy > Computer Configuration > Administrative Templates > Windows Components > Windows PowerShell

Press the Windows icon on the keyboard + R to open the Run dialog and type gedit.msc to open the Group Policy Management Console.

Some resources to provide more information about enabling this feature, along with its associated event IDs:

  • About Logging Windows
  • Greater Visibility Through PowerShell Logging
  • Configure PowerShell logging to see PowerShell anomalies in Splunk UBA

Another feature to enable/configure is Audit Process Creation, which will generate event ID 4688 and will allow command-line process auditing.

Local Computer Policy > Computer Configuration > Administrative Templates > System > Audit Process Creation

We have already enabled Audit Process Creation

We will now perform step 2.

I run a simple command of whoami

Go to Event Viewer to see if the command was logged. We should look under Windows Logs > Security. It can be observed that it was not logged at all.

Now for step 3, Enable the command line process auditing.

  • In the Group Policy Editor, go to “Computer Configuration” > “Windows Settings” > “Security Settings” > “Advanced Audit Policy Configuration” > “Audit Policies” > “Detailed Tracking.”
  • In the right pane, locate the “Audit Process Creation” policy, and double-click on it to open the properties.
  • In the properties window, select the “Define these policy settings” option.
  • Check the “Success” and “Failure” boxes to enable auditing for successful and failed process creations. Click Apply and Ok.

We’ll run the same command and notice if there’s a difference.

The command was logged this time.

The steps to test the configuration are at the bottom of the document.

The resources are not exhaustive list, hence we need to read more about this topic.

To effectively monitor and hunt, we need to know what to look for.

Answer the questions below

I’m ready to look at some event logs…


Task 7: Putting theory into practice

Let’s now test our newly acquired pool of knowledge on Windows Event Logs with the different scenarious presented below.

The next scenarios/questions are based on the external event log file titled merged.evtx found on the Desktop. 

Scenario 1 (Questions 1 & 2): The server admins have made numerous complaints to Management regarding PowerShell being blocked in the environment. Management finally approved the usage of PowerShell within the environment. Visibility is now needed to ensure there are no gaps in coverage. You researched this topic: what logs to look at, what event IDs to monitor, etc. You enabled PowerShell logging on a test machine and had a colleague execute various commands.

Scenario 2 (Questions 3 & 4): The Security Team is using Event Logs more. They want to ensure they can monitor if event logs are cleared. You assigned a colleague to execute this action.

Scenario 3 (Questions 5, 6 & 7): The threat intel team shared its research on Emotet. They advised searching for event ID 4104 and the text “ScriptBlockText” within the EventData element. Find the encoded PowerShell payload.

Scenario 4 (Questions 8 & 9): A report came in that an intern was suspected of running unusual commands on her machine, such as enumerating members of the Administrators group. A senior analyst suggested searching for “C:\\Windows\\System32\\net1.exe“. Confirm the suspicion.

Answer the questions below

Open the merged.evtx file with event viewer

What event ID is to detect a PowerShell downgrade attack?

Answer: 400

A search on google would yield us about detecting PowerShell downgrade attacks. Here is an interesting article why attackers would downgrade to older versions of PowerShell.

What is the Date and Time this attack took place? (MM/DD/YYYY H:MM:SS [AM/PM])

Answer: 12/18/2020 7:50:33 AM

I used PowerShell for this task, added –Path parameter to indicate the source of the log file.

Get-WinEvent -Path .\\Desktop\\merged.evtx -FilterXPath '*/System/EventID=400' -MaxEvents 10

We can add the following to sort the results.

Sort-Object -Property TimeCreated -Descending

A Log clear event was recorded. What is the ‘Event Record ID’?

Answer: 27736

In one of the resources provided, an EventID of 104 is generated when the Application or System log were cleared.

Now that we know the Event ID, let’s filter the logs with eEentID 104.

Select the windows event. In the lower pane, click on the “Details” tab and select “XML View”. We now see the ID for the recorded event.

What is the name of the computer?

Answer: PC01.example.corp

The computer name is seen in the tag “Computer” or in the “General” tab.

What is the name of the first variable within the PowerShell command?

Answer: $Va5w3n8=

It is important to know, that only when Script Block Logging is enabled, that these blocks of code, when executed by PowerShell are logged. Such events are recorded with EventID 4104.

The following command would query, using XPath, all events with a 4104 ID, within “EventData” focusing on the tag “Data” that has the strings “ScriptBlockText”. Note: Variables always start with ‘$’.

Get-WinEvent -Path .\\Desktop\\merged.evtx -FilterXPath '*/System/EventID=4104 and */EventData/Data[@Name="ScriptBlockText"]' -Oldest -MaxEvents 1 | Format-List

It took me a while to realize that the details displayed are incomplete, and I try not to rely on Event Viewer too much, because imagine if we have thousands of events to crumb through.

These commands would display all the info about the events and would also provide the answer for the next two questions.

Get-WinEvent -Path .\Desktop\merged.evtx -FilterXPath '*/System/EventID=4104 and */EventData/Data[@Name="ScriptBlockText"]' -Oldest -MaxEvents 1 | Select-Object -Property *

What is the Date and Time this attack took place? (MM/DD/YYYY H:MM:SS [AM/PM])

Answer: 8/25/2020 10:09:28 PM

What is the Execution Process ID?

Answer: 6620

What is the Group Security ID of the group she enumerated?

Answer:S-1-5-32-544

To confirm if she enumerated the “Administrators” group in her local machine, we would run the following commands. We will filter events with XPath within the elements of “EventData” and include the location of the suspected executed file. The piped results would display all the information about the queried events.

Get-WinEvent -Path .\merged.evtx -FilterXPath '*/EventData/Data[@Name="CallerProcessName"]="C:\Windows\System32\net1.exe"' | Select-Object -Property *

There were three events logged, but we are interested in the event where the local group “Administrators” was enumerated.

What is the event ID?

Answer: 4799

For reference, check this out.


Task 8: Conclusion

We have covered a lot about Windows Event Logs, the important Event IDs we should monitor and hunt, and how to query them with the different tools and techniques.

We also touched on the features that need to be enabled or configured so that they can be logged for further visibility.

Windows event logs from various endpoints are also forwarded to SIEMs for easy filtering of evnts, correlating rules, generating reports, and detecting suspicous activities.

TryHackme provided us parting gifts for additional reading:

  • EVTX Attack Samples (a few were used in this room)
  • PowerShell ❤ the Blue Team
  • Tampering with Windows Event Tracing: Background, Offense, and Defense

That concludes this room.


Thank you for reading 🙂

Happy learning!.

Concept Detail
Event Logs Default Path : %systemroot%\system32\config
If modified, new paths available @ HKLM\SYSTEM\CurrentControlSet\Services\Eventlog
Types :
Security – login/logout activity, other security-related evts specified by system’s audit policy. Updated by LSASS only. 3rd party tools cannot insert evts. Admin prev users can review, export, clear events.
System – Evts logged by OS and its components – Failure of a service;
Application – Evts logged by applications – Failure of an application, AV alerts etc
New Log Categories-
Setup – Win security updates, patches etc.
Forwarded Events – Repo of Logs consolidated from multiple machines on a collector system
Applications and Services – 60+ custom logs- TaskScheduler, RDP, Win Firewall, Win Defender etc
Security Evt Logs AccountLogons; AccountMgmt; DirectoryServices; LogonEvents; ObjectAccess – Unauthorized access, accidental access, files/folders deletion, changes in files/folders, or permissions; PolicyChange; PrivlegeUse; ProcessTracking; SystemEvent – SystemStart,Shutdown etc.
Tracking Account Usage 4624 – Successful Logon;
4625 – Failed Logon;
4634/4647 – Successful Logoff; 4647 – User initiated.
4648 – Logon using explicit credentials – RunAs
4672 – Account logon with Admin rights – Special Logon
4720 – Account created.
Logon Type Codes 2 – Interactive – Console Logons.
3 – Network Logon – File share access using SMB
4 – Batch Logon- Scheduled tasks – Non interactive
5 – Windows Service Logon- Services and service account logon to start a service.
7 – Credentials used for Lock/Unlock screen.
8 – Network logon creds in Cleartext
9 – Different Credentials – to authenticate than current user creds – RunAs command.
10 – Remote Interactive – RDP applications like Terminal Services or Remote Assistance.
11 – Cached Interactive – Login using cached credentials – No communcation with DC.
12 – Cached Remote Interactive – Cached credentials for RDP
13 – Cached unlock – Cached credentials used for unlock operations.
Built-in service accounts LocalSystem account .\LocalSystem
Extensive privileges on the local computer; SID: S-1-5-18;
LocalService account NT AUTHORITY\NetworkService
A limited service account that is very similar to Network Service and meant to run standard least-privileged services. Accesses the network as an Anonymous user. SID: S-1-5-19
NetworkService account NT AUTHORITY\NetworkService
Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine. SID: S-1-5-20
Anonymous Logon – Windows system to communicate without explicit creds – for file, print sharing; maintaining NW browse list.
4720 Account created Complimentaries 4722 – User account enabled.
4724 – Attempt to reset account’s password
4728 – Member added to security-enabled global group
4732 – Member added to security-enabled local group
4735 – Security enabled local group changed.
4738 – User account was changed
4756 – Member added to security-enabled universal group
Remote Desktop Protocol 4778 – Session Connected/Reconnected
4779 – Session Disconnected
Account Logon Events NTLM – 4776 – Successful/Failed account authentication
Kerberos – 4768 – Ticket Granting Ticket was granted – Successful Logon
4769 – Service Ticket Requested – Access to server resources
4771 – Pre-authentication Failed – Failed Logon
Kerberos – 4771 – Error Codes 0x6 Invalid Username
0x7 Requested server not found
0xC Policy restriction prohibitied logon – Day/Time restrictions
0x12 Account locked, disabled or expired
0x17 Password expired
0x18 Password invalid
0x25 Clock skew between server & client is too great
Kerberos – 4776 – Error Codes 0xC0000064 – Non-existent account username
0xC000006A – Incorrect password – Username correct
0xC000006F – Account not allowed to log on at this time.
0xC0000070 – Account not allowed to log on from this computer.
0xC0000071 – Expired password.
0xC0000072 – Disabled account.
0xC0000193 – Expired account.
0xC0000234 – Account Locked
Network Shares 5140 – Network Share was accessed – Sharename; Logon account; Remote IP address;
5145 – Shared object accessed
Scheduled Tasks – Microsoft-Windows-Task Scheduler/Operational log 106 – Scheduled task Created
140 – Scheduled task Updated
141 – Scheduled task Deleted
200 – Scheduled task Executed
201 – Scheduled task Completed
Scheduled Tasks – Security Log 4698 – Scheduled task Created
4699 – Scheduled task Deleted
4700 – Scheduled task Enabled
4701 – Scheduled task Disabled
4702 – Scheduled task Updated
Suspicious Services 7034 – Service crashed unexpectedly
7035 – Service sent a Start/Stop control
7036 – Service started or stopped
7040 – Start type changed [Boot|On Request|Disabled]
7045 – Service was installed on the system – Win2008R2+
4697 – Service was installed on the system – Security Log
Application Installation 1033 – Installation Completed – With Success/Failure status
1034 – Application removal completed – With Success/Failure status
11707 – Installation compeleted successfully
11708 – Installation operation failed
11724 – Applicatoin removal completed successfully
Application Execution 4688 – Security Log – New process created – includes execution path – Command line- cmd,PS etc
4689 – Security Log – Process Terminated
1001 – System/Application Log – Windows Error Reporting events.
1000-1002 – Application errors and hangs
PowerShell/Operational Log 4104 – Script contents
4105/4106 – Script Start/Stop
Event Log Clearing 1102 – Audit Log Cleared – Security Logs
104 – Audit Log Cleared – System Log
No built-in mechanism for selective deletion of events
When maximum log size reached –
1. Overwrite events as needed
2. Archive the logs – Do not overwrite
3. Do not overwrite logs – Error msg generated – Admin manually clears the log
Export Event Logs 1. Live Export from EventViewer – Save as .Evt or .Evtx
2. Live System – FTK Imager – Export Event logs – Can result in log corruption.
3. Live system – PsLogList tool from SysInternals – Export log files.
Wireless Access Points Microsoft-Windows-WLAN-AutoConfig Operational.evtx
• 11000 – Wireless network association started
• 8001 – Successful connection to wireless network
• 8002 – Failed connection to wireless network
• 8003 – Disconnect from wireless network
Hardware device Connected  System.evtx
20001 – Device Driver installed or updated.

Published

The Event Viewer is an Administrative tool that records events that occur on your computer. When the system or application runs into any bugs, errors, or security issues, the event logs will have the information that caused the problem. Although it does not solve the issue at hand, the Event logs give you the necessary information to begin the troubleshooting process.

Understanding Event Viewer Layout

In the Event Viewer window, you will see three panels. The left side is the navigation panel, the middle one displays the event details and the right side is for performing actions like saving or loading event logs.

panels-on-Event-viewer

Navigation Panel

The Navigation panel is the left side panel where event logs are categorized into three specific folders. These folders are common in all versions and editions of Windows. These are Custom Views, Windows Logs, and Application and Services Logs.

navigation panel check event logs

Windows logs keep track of every event from the Windows OS and contain a list of the following event log categories:

  • Application: Logs from applications
  • System: Logs created by OS
  • Security: Login events
  • Setup: Logs Windows Setup performance events
  • Forwarded Events: Events forwarded by remote PCs

Application and Service Logs contain events from hardware connections/alerts, third-party applications, and PowerShell events.

Finally, any custom filter you create through the action panel will be stored in the Custom Views event log. By default, this section will have a sub-category named Administrative Events. You can use this to view all Critical, Warning, and Error events from the log history.

Custom event logs named Administrative Events are created automatically on all versions of Windows.

On the Navigation panel, if you click on Event Viewer (Local), you will get an Overview and Summary in the Details panel. Here, you can get a quick review of all the administrative events, recently viewed logs, and Log Summary.

event log and summary

Events Panel

The Events panel displays the list of recorded event logs and the level of the recorded event whether it is information, warning, error, or critical. Among these, event logs indicating Error should be given high priority and should be looked into right away.

event detail panel event logs

If you double-click on the events, a new dialog box opens up showing all the event properties. It contains a log description along with numerous entries. Among these entries, Log Name, Source, Event ID, Logged, Level, and OpCode are a few of the crucial ones.

event properties detail check event logs

  • Logged records the date and time of the event log and it is the most crucial one. You can note the date and time of the system crash or when the system runs into issues and compare it with Logged to determine the recorded event log.
  • Once you have the event log, check its Log Name. Using Log Name, you can determine whether the log is from the application, security, setup, system, or forwarded events.
  • The Level column says whether the event log is a warning, error, or just information. We recommend checking the log description, Event ID, and Source.
  • Event ID and Source are what you will need to determine the exact details of the recorded event log.

Actions Panel

Event Actions allows you to perform actions like save logs, open saved logs, create a custom view, clear event logs, filter current logs, and view properties of the selected log. 

actions-panel

Save and Open Event Logs

Saving Event logs allows you to get the event details and view them on another PC. To save logs in the event viewer,

  1. In the left panel, select the event log category that you want to save.
  2. Now, on the right panel, click on Save All Event As.
    save event as check event logs
  3. Select a file location where you want your event file saved and name the file.

To open saved logs, 

  1. Click on the Open Saved log on the right side of the Event Viewer Window.
    open saved event logs event viewer
  2. Now browse for an event file with .evtx, .evt, or .etl extension.

Once you open saved logs, a log category named Saved Logs will appear on the Event Viewer panel located on the left side.

Filter Event Log and Create Custom View

By filtering logs, the event viewer will extract the events that do not match the event properties set on the custom filter. To set a filter in Event Viewer,

  1. Select the event log category that you want to filter.
  2. Click on Filter Current Logs on the Actions panel.
    filter current logs view event log
  3. Here, fill in Logged, Event Level, Event Sources, EventIDs, and other categories depending on what you want to filter out.
    filter current logs
  4. Click on OK.
  5. Now, you will only get the filtered event logs.

Note: You cannot filter event log inside Custom Views as these logs are already filtered.

Creating a Custom view works similar to filtering event logs. However, when creating custom logs, it will create a new log category in Custom Views. Creating Custom View can especially come in handy when you only want to view the filtered events logs.

Administrative Events under the Custom Views filter all Critical, Warning, and Error events from the entire log history. Therefore, it is the first thing you need to check when the system runs into error or crashes.

Custom event logs named Administrative Events are created automatically on all versions of Windows.

Note: You need the exact date and time of the system crash/error to check event logs.

  1. Press the Windows + R key to open Run.
  2. Type eventvwr and press OK.
    eventviewer from run
  3. Alternatively, you can also right-click on the Windows icon on the taskbar and select Event Viewer.
  4. In Event Viewer, expand Custom Views and click on Administrative Events.
  5. In the middle panel, compare the date and time of the system error with the Date and Time Column.
  6. Double-click on the event log that matches the date and time of the crash/error.
    check event logs from event viewer
  7. Note Log Name, Event ID and Source. Event ID is different for each category of Event Logs.
    check log name event id sources
  8. If the Log Name displays Application, Security, Setup, System, or Forwarded Events, expand Windows Logs and click on the log category (Log Name) that you noted in Step 7.
    check log name corresponding to windows log category
  9. If the Log Name displays some other names, expand Application and Services Logs in the navigation panel. Here you need to find the logs category (Log name) from Step 7.
    check application and service log
  10. Now, in the event details panel search the event using the date and time of the system error.
  11. Once you find the event log that matches the event from Step 6, check other events leading up to the system-crash event log.
  12. You can also search the internet or Microsoft’s official documentation page for Event ID and Source to determine the exact cause of the error log.
    tpm error event id 14

Event Viewer Retention Period

The default retention period for events in a single event log category is around 20MB. And since these event logs are entered on a FIFO (First-In First-out) policy, the entries recorded first are removed first when it hits the 20MB limit.

However, you can increase the event viewer retention size if you want to record more event logs.

  1. Select the event log category whose retention size you want to change.
  2. Right-click and select Properties.
    open event properties check event log
  3. Change the Maximum log size to record a higher number of events.
    change maximum log size

Here, you can also check the current log size, created, modified, and accessed data, log path, and what the system does when the maximum event log size is reached.

  • Windows admin center установка на сервер
  • Windows android скачать последняя версия
  • Windows admin pack windows 7 x64
  • Windows appcompat programs amcache hve
  • Windows and office iso downloader