# Windows Logging Hub

## Event View

Event Viewer is a Windows tool that shows detailed logs of events like errors, warnings, and successful actions on a system. It's an essential component for troubleshooting, system diagnostics, and monitoring the overall health of your computer by providing a centralized location to review system, security, and application logs.&#x20;

```
--- Logon / Logoff Events ---
Event ID 4624: Successful Account Logon - Windows Event Logs
Event ID 4625: Failed Account Logon - Windows Event Logs
Event ID 4634: Account Logoff - Windows Event Logs
Event ID 4647: User-Initiated Logoff - Windows Event Logs
Event ID 4800: The Workstation Was Locked - Windows Event Logs
Event ID 4801: The Workstation Was Unlocked - Windows Event Logs

--- Privilege / Account Management ---
Event ID 4672: Special Privileges Assigned to New Logon - Windows Event Logs
Event ID 4720: A User Account Was Created - Windows Event Logs
Event ID 4722: A User Account Was Enabled - Windows Event Logs
Event ID 4723: An Attempt Was Made to Change an Account's Password - Windows Event Logs
Event ID 4724: An Attempt Was Made to Reset an Account's Password - Windows Event Logs
Event ID 4725: A User Account Was Disabled - Windows Event Logs
Event ID 4726: A User Account Was Deleted - Windows Event Logs
Event ID 4732: A Member Was Added to a Security-Enabled Local Group - Windows Event Logs
Event ID 4733: A Member Was Removed from a Security-Enabled Local Group - Windows Event Logs
Event ID 4756: A Member Was Added to a Security-Enabled Universal Group - Windows Event Logs
Event ID 4757: A Member Was Removed from a Security-Enabled Universal Group - Windows Event Logs

--- Process / Execution ---
Event ID 4688: A New Process Has Been Created - Windows Event Logs
Event ID 4689: A Process Has Ended - Windows Event Logs
Event ID 4697: A Service Was Installed in the System - Windows Event Logs
Event ID 4700: Scheduled Task Created - Windows Event Logs
Event ID 4702: Scheduled Task Updated - Windows Event Logs

--- Authentication / Kerberos ---
Event ID 4768: A Kerberos Authentication Ticket (TGT) Was Requested - Windows Event Logs
Event ID 4769: A Kerberos Service Ticket Was Requested - Windows Event Logs
Event ID 4771: Kerberos Pre-Authentication Failed - Windows Event Logs
Event ID 4776: The Computer Attempted to Validate the Credentials for an Account - Windows Event Logs
Event ID 4798: A User's Local Group Membership Was Enumerated - Windows Event Logs

--- System / Security Changes ---
Event ID 4719: System Audit Policy Changed - Windows Event Logs
Event ID 5031: The Windows Firewall Service Was Stopped - Windows Event Logs
Event ID 5032: The Windows Firewall Settings Were Changed - Windows Event Logs
Event ID 5058: Keyfile Operation - Windows Event Logs

```

#### XML template

```xml
<QueryList>
  <Query Id="0" Path="Security">
    <Select Path="Security">
      *[System[EventID=XXXX]]
    </Select>
  </Query>
</QueryList>
```

#### Important Filters

```xml
<!-- 1. Filter by EventID: los eventos más críticos para threat hunting -->
<System[EventID=4624 or EventID=4625 or EventID=4688 or EventID=4689 or EventID=4672 or EventID=4720 or EventID=4726] />

<!-- 2. Filter by Date / Time Range: para análisis temporal -->
<System[TimeCreated[@SystemTime&gt;='YYYY-MM-DDTHH:MM:SS.000Z' and @SystemTime&lt;='YYYY-MM-DDTHH:MM:SS.999Z']] />

<!-- 3. Filter by User (SubjectUserName / TargetUserName) -->
<EventData[Data[@Name='SubjectUserName']='USERNAME'] />
<EventData[Data[@Name='TargetUserName']='USERNAME'] />

<!-- 4. Filter by LogonType: útil para identificar logins remotos, servicios o unlocks -->
<!-- Values: 2=Interactive, 3=Network, 4=Batch, 5=Service, 7=Unlock, 10=RemoteInteractive -->
<EventData[Data[@Name='LogonType']='10'] />

<!-- 5. Filter by Privileges / Access Mask: para detectar operaciones sensibles -->
<EventData[Data[@Name='AccessMask']='0x2'] />
<EventData[Data[@Name='NewSd']='S:ARAI(AU;SAFA;DCLCRPCRSDWDWO;;;WD)'] />

<!-- 6. Filter by ProcessName: para ver qué ejecutables generan eventos -->
<EventData[Data[@Name='ProcessName']='C:\Windows\System32\services.exe'] />

<!-- 7. Filter by Object / File / Registry: detectar manipulación de objetos críticos -->
<EventData[Data[@Name='ObjectName']='C:\SensitiveFile.txt'] />

<!-- 8. Filter by Audit Subcategory: para filtrar por tipo de auditoría -->
<EventData[Data[@Name='Subcategory']='Logon'] />

<!-- 9. Filter by SubjectLogonId: para seguir sesiones específicas -->
<EventData[Data[@Name='SubjectLogonId']='0x3e7'] />

```

#### Combine Filters

```xml
<!-- Combine Filters (General Template) -->
<QueryList>
  <Query Id="0" Path="Security">
    <Select Path="Security">
      *[
        System[EventID=XXXX and TimeCreated[@SystemTime&gt;='YYYY-MM-DDTHH:MM:SS.000Z' and @SystemTime&lt;='YYYY-MM-DDTHH:MM:SS.999Z']]
        and EventData[Data[@Name='SubjectUserName']='USERNAME']
        and EventData[Data[@Name='ProcessName']='C:\Path\To\Process.exe']
        and EventData[Data[@Name='ObjectName']='C:\Sensitive\File.txt']
      ]
    </Select>
  </Query>
</QueryList>
```

## Sysmon

`System Monitor (Sysmon)` is a Windows system service and device driver that remains resident across system reboots to monitor and log system activity to the Windows event log. Sysmon provides detailed information about process creation, network connections, changes to file creation time, and more.

### Sysmon event IDs

```sh
❯ curl  -s https://learn.microsoft.com/en-us/sysinternals/downloads/sysmon | grep -oP "Event ID \d{0,2}.*" | cut -d '<' -f1
Event ID 1: Process creation
Event ID 2: A process changed a file creation time
Event ID 3: Network connection
Event ID 4: Sysmon service state changed
Event ID 5: Process terminated
Event ID 6: Driver loaded
Event ID 7: Image loaded
Event ID 8: CreateRemoteThread
Event ID 9: RawAccessRead
Event ID 10: ProcessAccess
Event ID 11: FileCreate
Event ID 12: RegistryEvent (Object create and delete)
Event ID 13: RegistryEvent (Value Set)
Event ID 14: RegistryEvent (Key and Value Rename)
Event ID 15: FileCreateStreamHash
Event ID 16: ServiceConfigurationChange
Event ID 17: PipeEvent (Pipe Created)
Event ID 18: PipeEvent (Pipe Connected)
Event ID 19: WmiEvent (WmiEventFilter activity detected)
Event ID 20: WmiEvent (WmiEventConsumer activity detected)
Event ID 21: WmiEvent (WmiEventConsumerToFilter activity detected)
Event ID 22: DNSEvent (DNS query)
Event ID 23: FileDelete (File Delete archived)
Event ID 24: ClipboardChange (New content in the clipboard)
Event ID 25: ProcessTampering (Process image change)
Event ID 26: FileDeleteDetected (File Delete logged)
Event ID 27: FileBlockExecutable
Event ID 28: FileBlockShredding
Event ID 29: FileExecutableDetected
Event ID 255: Error
```

### Installing Sysmon

**Download**: <https://docs.microsoft.com/en-us/sysinternals/downloads/sysmon>

```sh
#Install Sysmon with default configuration and hash logging
C:\Tools\Sysmon> sysmon.exe -i -accepteula -h md5,sha256,imphash -l -n

#Use a custom Sysmon configuration
C:\Tools\Sysmon> sysmon.exe -c sysmonconfig-export.xml
```

* <https://github.com/SwiftOnSecurity/sysmon-config>
* <https://github.com/olafhartong/sysmon-modular>

## Get-WinEvent&#x20;

`Get-WinEvent` is a PowerShell cmdlet used to retrieve events from Windows event logs and Event Tracing for Windows (ETW) logs, enabling administrators to filter, analyze, and automate tasks related to system and application events. It is more powerful and efficient than older cmdlets for querying and filtering events, especially for complex criteria like specific event IDs, log names, and times.&#x20;

### Basic Queries

```powershell
#Identify available logs
Get-WinEvent -ListLog * | Select-Object LogName, RecordCount, IsClassicLog, IsEnabled, LogMode, LogType | Format-Table -AutoSize

#List event log providers
Get-WinEvent -ListProvider * | Format-Table -AutoSize

#Retrieve recent system events
Get-WinEvent -LogName 'System' -MaxEvents 50 | Select-Object TimeCreated, ID, ProviderName, LevelDisplayName, Message | Format-Table -AutoSize

#Retrieve recent Sysmon events
Get-WinEvent -LogName "Microsoft-Windows-Sysmon/Operational" -MaxEvents 30 | Select TimeCreated, Id, Message | Format-Table -AutoSize

#Retrieve recent Windows Remote Management (WinRM) events
Get-WinEvent -LogName 'Microsoft-Windows-WinRM/Operational' -MaxEvents 30 | Select-Object TimeCreated, ID, ProviderName, LevelDisplayName, Message | Format-Table

#Analyze external EVTX files
Get-WinEvent -Path "C:\Evidence\sysmon_sample.evtx" -MaxEvents 5 | Select TimeCreated, Id, ProviderName, Message
Get-WinEvent -Path "C:\Tools\chainsaw\XXXXXX\Lateral Movement\*"  | Select-Object -ExpandProperty ProviderName | Sort-Object -Unique

#Filtering with FilterHashtable
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Sysmon/Operational'; ID=1,3} | Select-Object TimeCreated, ID, ProviderName, LevelDisplayName, Message | Format-Table -AutoSize

#Filter by ParentCommandLine (Executed command)
PS C:\Users\Administrator> Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Sysmon/Operational'; ID=1} | Where-Object {$_.Properties[21].Value -like "*-enc*"} | Format-List
```

### Advanced queries

**Search to identify the Event Structure**: `event id 1 properties sysmon`

#### Filter by date range

```powershell
#$startDate = (Get-Date -Year 2023 -Month 5 -Day 28).Date
#$endDate   = (Get-Date -Year 2023 -Month 6 -Day 3).Date
$start = (Get-Date '2023-05-28')
$end   = (Get-Date '2023-06-03')
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Sysmon/Operational';ID=1,3;StartTime=$start;EndTime=$end}
```

#### Filter by suspicious IP traffic

```powershell
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Sysmon/Operational'; ID=3} |
ForEach-Object {
$xml = [xml]$_.ToXml()
$eventData = $xml.Event.EventData.Data
New-Object PSObject -Property @{
    SourceIP = $eventData | Where-Object {$_.Name -eq "SourceIp"} | Select-Object -ExpandProperty '#text'
    DestinationIP = $eventData | Where-Object {$_.Name -eq "DestinationIp"} | Select-Object -ExpandProperty '#text'
    ProcessGuid = $eventData | Where-Object {$_.Name -eq "ProcessGuid"} | Select-Object -ExpandProperty '#text'
    ProcessId = $eventData | Where-Object {$_.Name -eq "ProcessId"} | Select-Object -ExpandProperty '#text'
}
}  | Where-Object {$_.DestinationIP -eq "52.113.194.132"}
```

#### Identify a DLL hijacking attack

```powershell
Get-WinEvent -Path "C:\Logs\DLLHijack\DLLHijack.evtx" -FilterXPath "*[System[(EventID=7)]]" |
 ForEach-Object {
   $xml=[xml]$_.ToXml(); $d=$xml.Event.EventData.Data
   [PSCustomObject]@{
     TimeCreated = $_.TimeCreated
     Image       = ($d | Where-Object {$_.Name -eq 'Image'}).'#text'
     ImageLoaded = ($d | Where-Object {$_.Name -eq 'ImageLoaded'}).'#text'
     Hashes      = ($d | Where-Object {$_.Name -eq 'Hashes'}).'#text'
     User        = ($d | Where-Object {$_.Name -eq 'User'}).'#text'
   }
 } | Where-Object {$_.ImageLoaded -notmatch "\.exe$" -and $_.ImageLoaded -notlike "C:\Windows\System32\*" -and $_.ImageLoaded -notlike "C:\Program Files*"}
```

#### Identify LSASS dump

```powershell
Get-WinEvent -Path "C:\Logs\Dump\LsassDump.evtx" -FilterXPath "*[System[(EventID=10)]]" |
  ForEach-Object {
    $xml=[xml]$_.ToXml(); $d=$xml.Event.EventData.Data
    [PSCustomObject]@{
      TimeCreated = $_.TimeCreated
      SourceImage       = ($d | Where-Object {$_.Name -eq 'SourceImage'}).'#text'
      TargetImage = ($d | Where-Object {$_.Name -eq 'TargetImage'}).'#text'
      SourceUser      = ($d | Where-Object {$_.Name -eq 'SourceUser'}).'#text'
      TargetUser        = ($d | Where-Object {$_.Name -eq 'TargetUser'}).'#text'
    }
  }  | Where-Object {$_.TargetImage -match "lsass.exe$"}
```

#### Detecting Strange Parent Child Relationship

```powershell
Get-WinEvent -Path "C:\Logs\StrangePPID\*" -FilterXPath "*[System[(EventID=8)]]" |
  ForEach-Object {
    $xml=[xml]$_.ToXml(); $d=$xml.Event.EventData.Data
    [PSCustomObject]@{
      TimeCreated = $_.TimeCreated
      SourceImage = ($d | Where-Object {$_.Name -eq 'SourceImage'}).'#text'
      TargetImage = ($d | Where-Object {$_.Name -eq 'TargetImage'}).'#text'
      FunctionName      = ($d | Where-Object {$_.Name -eq 'StartFunction'}).'#text'
      ModuleInitiated        = ($d | Where-Object {$_.Name -eq 'StartModule'}).'#text'
    }
  }
```

#### Filter by using XPath

<pre class="language-powershell"><code class="lang-powershell">#Filter by suspicious IP address
Get-WinEvent -LogName 'Microsoft-Windows-Sysmon/Operational' -FilterXPath "*[System[EventID=3] and EventData[Data[@Name='DestinationIp']='52.113.194.132']]"
<strong>
</strong><strong>#Filter by using a file and specific field
</strong>Get-WinEvent -Path "C:\Tools\chainsaw\XXXXXX\Lateral Movement\*"  -FilterXPath "*[EventData[Data[@Name='ShareName'] and (Data='\\*\PRINT')]]" | Format-List

#Filter by using a EventID
Get-WinEvent -Path "C:\Tools\chainsaw\XXXXXX\Lateral Movement\*"  -FilterXPath "*[System[(EventID=5142)]]" | Format-List
</code></pre>

#### Detect installation of Sysinternals tools

```powershell
Get-WinEvent -LogName 'Microsoft-Windows-Sysmon/Operational' -FilterXPath "*[EventData[Data[@Name='Image']='C:\Windows\System32\reg.exe']] and *[EventData[Data[@Name='CommandLine']='`"C:\Windows\system32\reg.exe`" ADD HKCU\Software\Sysinternals /v EulaAccepted /t REG_DWORD /d 1 /f']]" | Select-Object TimeCreated, ID, ProviderName, LevelDisplayName, Message | Format-Table -AutoSize
```

#### Filter By XML file as Query

```powershell
$Query = @"
	<QueryList>
		<Query Id="0">
			<Select Path="Microsoft-Windows-Sysmon/Operational">*[System[(EventID=7)]] and *[EventData[Data='mscoree.dll']] or *[EventData[Data='clr.dll']]
			</Select>
		</Query>
	</QueryList>
"@
PS C:\Users\Administrator> Get-WinEvent -FilterXml $Query | ForEach-Object {Write-Host $_.Message `n}
```
