Tree's Notes
  • Overview
  • Tools & Cheatsheets
  • Hacking Methodology
  • Hands-on Practice
  • Linux
    • Linux Basics
  • Windows
    • Windows Basics
  • MacOS
    • MacOS Basics
  • Web
    • Web Basics
  • Mobile
    • iOS
    • Android
  • OS Agnostic
    • Template
  • Courses
    • Hack The Box
      • Bug Bounty Hunter
        • Module 1: Web Requests
        • Module 2: Introduction to Web Applications
        • Module 3: Using Web Proxies
        • Module 4: Information Gathering - Web Edition
        • Module 5: Attacking Web Applications with Ffuf
        • Module 6: JavaScript Deobfuscation
        • Module 7: Cross-Site Scripting (XSS)
        • Module 8: SQL Injection Fundamentals
        • Module 9: SQLMap Essentials
        • Module 10: Command Injections
        • Module 11: File Upload Attacks
        • Module 12: Server-Side Attacks
        • Module 13: Login Brute Forcing
        • Module 14: Broken Authentication
        • Module 15: Web Attacks
        • Module 16: File Inclusion
        • Module 17: Session Security
        • Module 18: Web Service & API Attacks
        • Module 19: Hacking Wordpress
        • Module 20: Bug Bounty Hunting Process
    • OffSec
      • 🦊EXP-301
        • Module 1: Windows User Mode Exploit Development: General Course Information
        • Module 2: WinDbg and x86 Architecture
        • Module 3: Exploiting Stack Overflows
        • Module 4: Exploiting SEH Overflows
        • Module 5: Introduction to IDA Pro
        • Module 6: Overcoming Space Restrictions: Egghunters
        • Module 7: Creating Custom Shellcode
        • Module 8: Reverse Engineering for Bugs
        • Module 9: Stack Overflows and DEP Bypass
        • Module 10: Stack Overflows and ASLR Bypass
        • Module 11: Format String Specifier Attack Part I
        • Module 12: Format String Specifier Attack Part II
        • Module 13: Trying Harder: The Labs
      • 🐙EXP-312
        • Module 1: macOS Control Bypasses: General Course Information
        • Module 2: Virtual Machine Setup Guide
        • Module 3: Introduction to macOS
        • Module 4: macOS Binary Analysis Tools
        • Module 5: The Art of Crafting Shellcodes
        • Module 6: The Art of Crafting Shellcodes (Apple Silicon Edition)
        • Module 7: Dylib Injection
        • Module 8: The Mach Microkernel
        • Module 9: XPC Attacks
        • Module 10: Function Hooking on macOS
        • Module 11: The macOS Sandbox
        • Module 12: Bypassing Transparency, Consent, and Control (Privacy)
        • Module 13: GateKeeper Internals
        • Module 14: Bypassing GateKeeper
        • Module 15: Symlink and Hardlink Attacks
        • Module 16: Injecting Code into Electron Applications
        • Module 17: Getting Kernel Code Execution
        • Module 18: Mach IPC Exploitation
        • Module 19: macOS Penetration Testing
        • Module 20: Chaining Exploits on macOS Ventura
        • Module 21: Mount(ain) of Bugs (archived)
      • ⚓IR-200
        • Module 1: Incident Response Overview
        • Module 2: Fundamentals of Incident Response
        • Module 3: Phases of Incident Response
        • Module 4: Incident Response Communication Plans
        • Module 5: Common Attack Techniques
        • Module 6: Incident Detection and Identification
        • Module 7: Initial Impact Assessment
        • Module 8: Digital Forensics for Incident Responders
        • Module 9: Incident Response Case Management
        • Module 10: Active Incident Containment
        • Module 11: Incident Eradication and Recovery
        • Module 12: Post-Mortem Reporting
        • Module 13: Incident Response Challenge Labs
      • 🐉PEN-103
      • 🐲PEN-200
        • Module 1: Copyright
        • Module 2: Penetration Testing with Kali Linux: General Course Information
        • Module 3: Introduction to Cybersecurity
        • Module 4: Effective Learning Strategies
        • Module 5: Report Writing for Penetration Testers
        • Module 6: Information Gathering
        • Module 7: Vulnerability Scanning
        • Module 8: Introduction to Web Application Attacks
        • Module 9: Common Web Application Attacks
        • Module 10: SQL Injection Attacks
        • Module 11: Client-side Attacks
        • Module 12: Locating Public Exploits
        • Module 13: Fixing Exploits
        • Module 14: Antivirus Evasion
        • Module 15: Password Attacks
        • Module 16: Windows Privilege Escalation
        • Module 17: Linux Privilege Escalation
        • Module 18: Port Redirection and SSH Tunneling
        • Module 19: Tunneling Through Deep Packet Inspection
        • Module 20: The Metasploit Framework
        • Module 21: Active Directory Introduction and Enumeration
        • Module 22: Attacking Active Directory Authentication
        • Module 23: Lateral Movement in Active Directory
        • Module 24: Enumerating AWS Cloud Infrastructure
        • Module 25: Attacking AWS Cloud Infrastructure
        • Module 26: Assembling the Pieces
        • Module 27: Trying Harder: The Challenge Labs
      • 🛜PEN-210
        • Module 1: IEEE 802.11
        • Module 2: Wireless Networks
        • Module 3: Wi-Fi Encryption
        • Module 4: Linux Wireless Tools, Drivers, and Stacks
        • Module 5: Wireshark Essentials
        • Module 6: Frames and Network Interaction
        • Module 7: Aircrack-ng Essentials
        • Module 8: Cracking Authentication Hashes
        • Module 9: Attacking WPS Networks
        • Module 10: Rogue Access Points
        • Module 11: Attacking Captive Portals
        • Module 12: Attacking WPA Enterprise
        • Module 13: bettercap Essentials
        • Module 14: Determining Chipsets and Drivers
        • Module 15: Kismet Essentials
        • Module 16: Manual Network Connections
      • 🔗PEN-300
        • Module 1: Evasion Techniques and Breaching Defenses: General Course Information
        • Module 2: Operating System and Programming Theory
        • Module 3: Client Side Code Execution With Office
        • Module 4: Phishing with Microsoft Office
        • Module 5: Client Side Code Execution With Windows Script Host
        • Module 6: Reflective PowerShell
        • Module 7: Process Injection and Migration
        • Module 8: Introduction to Antivirus Evasion
        • Module 9: Advanced Antivirus Evasion
        • Module 10: Application Whitelisting
        • Module 11: Bypassing Network Filters
        • Module 12: Linux Post-Exploitation
        • Module 13: Kiosk Breakouts
        • Module 14: Windows Credentials
        • Module 15: Windows Lateral Movement
        • Module 16: Linux Lateral Movement
        • Module 17: Microsoft SQL Attacks
        • Module 18: Active Directory Exploitation
        • Module 19: Attacking Active Directory
        • Module 20: Combining the Pieces
        • Module 21: Trying Harder: The Labs
      • ⚛️SEC-100
      • 🛡️SOC-200
        • Module 1: Introduction to SOC-200
        • Module 2: Attacker Methodology Introduction
        • Module 3: Windows Endpoint Introduction
        • Module 4: Windows Server Side Attacks
        • Module 5: Windows Client-Side Attacks
        • Module 6: Windows Privilege Escalation
        • Module 7: Windows Persistence
        • Module 8: Linux Endpoint Introduction
        • Module 9: Linux Server Side Attacks
        • Module 10: Linux Privilege Escalation
        • Module 11: Network Detections
        • Module 12: Antivirus Alerts and Evasion
        • Module 13: Active Directory Enumeration
        • Module 14: Network Evasion and Tunneling
        • Module 15: Windows Lateral Movement
        • Module 16: Active Directory Persistence
        • Module 17: SIEM Part One: Intro to ELK
        • Module 18: SIEM Part Two: Combining the Logs
        • Module 19: Trying Harder: The Labs
      • TH-200
        • Module 1: Threat Hunting Concepts and Practices
        • Module 2: Threat Actor Landscape Overview
        • Module 3: Communication and Reporting for Threat Hunters
        • Module 4: Hunting With Network Data
        • Module 5: Hunting on Endpoints
        • Module 6: Theat Hunting Without IoCs
        • Module 7: Threat Hunting Challenge Labs
      • 🦉WEB-200
        • Module 1: Introduction to WEB-200
        • Module 2: Tools (archived)
        • Module 3: Web Application Enumeration Methodology
        • Module 4: Introduction to Burp Suite
        • Module 5: Cross-Site Scripting Introduction and Discovery
        • Module 6: Cross-Site Scripting Exploitation and Case Study
        • Module 7: Cross-Origin Attacks
        • Module 8: Introduction to SQL
        • Module 9: SQL Injection
        • Module 10: Directory Traversal Attacks
        • Module 11: XML External Entities
        • Module 12: Server-side Template Injection - Discovery and Exploitation
        • Module 13: Command Injection
        • Module 14: Server-side Request Forgery
        • Module 15: Insecure Direct Object Referencing
        • Module 16: Assembling the Pieces: Web Application Assessment Breakdown
      • 🕷️WEB-300
        • Module 1: Introduction
        • Module 2: Tools & Methodologies
        • Module 3: ManageEngine Applications Manager AMUserResourcesSyncServlet SSQL Injection RCE
        • Module 4: DotNetNuke Cookie Deserialization RCE
        • Module 5: ERPNext Authentication Bypass and Remote Code Execution
        • Module 6: openCRX Authentication Bypass and Remote Code Execution
        • Module 7: openITCOCKPIT XSS and OS Command Injection - Blackbox
        • Module 8: Concord Authentication Bypass to RCE
        • Module 9: Server-Side Request Forgery
        • Module 10: Guacamole Lite Prototype Pollution
        • Module 11: Dolibarr Eval Filter Bypass RCE
        • Module 12: RudderStack SQLi and Coraza WAF Bypass
        • Module 13: Conclusion
        • Module 14: ATutor Authentication Bypass and RCE (archived)
        • Module 15: ATutor LMS Type Juggling Vulnerability (archived)
        • Module 16: Atmail Mail Server Appliance: from XSS to RCE (archived)
        • Module 17: Bassmaster NodeJS Arbitrary JavaScript Injection Vulnerability (archived)
    • SANS
      • FOR572
Powered by GitBook
On this page
  • Windows Processes
  • Windows Registry
  • Command Prompt, VBScript, and Powershell
  • Command Prompt
  • Visual Basic Script (VBScript)
  • PowerShell
  • Programming on Windows
  • Component Object Model
  • .NET and .NET Core
  • Windows Event Log
  • Introduction to Windows Events
  • PowerShell and Event Logs
  • Empowering the Logs
  • System Monitor (Sysmon)
  • Sysmon and Event Viewer
  • Sysmon and PowerShell
  • Remote Access with PowerShell Core
Edit on GitHub
  1. Courses
  2. OffSec
  3. SOC-200

Module 3: Windows Endpoint Introduction

Windows Processes

A process is an instance of a program running in system memory, used by both the OS and applications. Some applications use one process, others may use more.

Windows Registry

Windows maintains service and applications configurations in the Windows Registry. It is a hierarchical database that store critical information for the OS and for applications that use it. It stores settings, options, and various other information in hives, keys, and values.

Keys can contain a single value, or even more keys with their own values/keys. Values are made up of three fields: name, type, and data.

Command Prompt, VBScript, and Powershell

Command Prompt

The predecessor to cmd.exe was COMMAND.COM, which used the same command syntax.

Also known as cmd.exe, the command prompt is the most commonly-used command-line interface for the Windows operating system. Automated command-line tasks can be created via batch files.

Example Batch File

@ECHO OFF
TITLE Example Batch File
ECHO This batchfile will show Windows 10 Operating System information
systeminfo | findstr /C:"Host Name"
systeminfo | findstr /C:"OS Name"
systeminfo | findstr /C:"OS Version"
systeminfo | findstr /C:"System Type"
systeminfo | findstr /C:"Registered Owner"
PAUSE

Visual Basic Script (VBScript)

These scripts require the file extension .vbs and must be run through the cscript.exe interpreter.

Getting WMIService reference in our VBScript

' List Operating System and Service Pack Information

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

With the reference set, we can now use it.

Querying WMIService for all entries in Win32_OperatingSystem

Set colOSes = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")

CIM is an open standard for defining and organizing information technology details in a structured model. It is similar to WMI, except that WMI is Microsoft's implementation of CIM and was developed later. Their resources are present in modern versions of Windows.

For each loop to print system information

For Each objOS in colOSes
  Wscript.Echo "Computer Name: " & objOS.CSName
  Wscript.Echo "Caption: " & objOS.Caption 'Name
  Wscript.Echo "Version: " & objOS.Version 'Version & build
  Wscript.Echo "Build Number: " & objOS.BuildNumber 'Build
  Wscript.Echo "Build Type: " & objOS.BuildType
  Wscript.Echo "OS Type: " & objOS.OSType
  Wscript.Echo "Other Type Description: " & objOS.OtherTypeDescription
  WScript.Echo "Service Pack: " & objOS.ServicePackMajorVersion & "." & _
   objOS.ServicePackMinorVersion
Next

Operating System Information VBScript stored in osinfo.vbs

' List Operating System and Service Pack Information

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
 
Set colOSes = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")
For Each objOS in colOSes
  Wscript.Echo "Computer Name: " & objOS.CSName
  Wscript.Echo "Caption: " & objOS.Caption 'Name
  Wscript.Echo "Version: " & objOS.Version 'Version & build
  Wscript.Echo "Build Number: " & objOS.BuildNumber 'Build
  Wscript.Echo "Build Type: " & objOS.BuildType
  Wscript.Echo "OS Type: " & objOS.OSType
  Wscript.Echo "Other Type Description: " & objOS.OtherTypeDescription
  WScript.Echo "Service Pack: " & objOS.ServicePackMajorVersion & "." & _
   objOS.ServicePackMinorVersion
Next

Running osinfo.vbs to get OS information

C:\tools\windows_endpoint_introduction>cscript osinfo.vbs
Microsoft (R) Windows Script Host Version 5.812
Copyright (C) Microsoft Corporation. All rights reserved.

Computer Name: CLIENT01
Caption: Microsoft Windows 10 Pro for Workstations
Version: 10.0.19042
Build Number: 19042
Build Type: Multiprocessor Free
OS Type: 18
Other Type Description:
Service Pack: 0.0

PowerShell

PowerShell is a scripting language that leverages the .NET Framework. The scripts are plaintext files, typically with an extension of .ps1. Powershell commands are called cmdlets.

PowerShell uses something called an execution policy which is a protective measure designed to block potentially malicious scripts from executing. Your current execution policy can be queried with Get-ExecutionPolicy inside a PowerShell prompt.

Getting Operating System information with Get-CimInstance

PS C:\Users\offsec> Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object -Property CSName, Caption, Version,BuildNumber, BuildType, OSType, RegisteredUser, OSArchitecture, ServicePackMajorVersion, ServicePackMinorVersion


CSName                  : CLIENT01
Caption                 : Microsoft Windows 10 Pro for Workstations
Version                 : 10.0.19043
BuildNumber             : 19043
BuildType               : Multiprocessor Free
OSType                  : 18
RegisteredUser          : offsec
OSArchitecture          : 64-bit
ServicePackMajorVersion : 0
ServicePackMinorVersion : 0

Getting a list of all services with Get-Service

PS C:\Users\offsec> Get-Service

Status   Name               DisplayName
------   ----               -----------
Stopped  AarSvc_e9593       Agent Activation Runtime_e9593
Running  AdvancedSystemC... Advanced SystemCare Service 9
Stopped  AJRouter           AllJoyn Router Service
Stopped  ALG                Application Layer Gateway Service
Stopped  AppIDSvc           Application Identity
Running  Appinfo            Application Information
Stopped  AppMgmt            Application Management
...

Using Where-Object to get all running services retrieved from Get-Service

PS C:\Users\offsec> Get-Service | Where-Object { $_.Status -eq "Running" }

Status   Name               DisplayName
------   ----               -----------
Running  AdvancedSystemC... Advanced SystemCare Service 9
Running  Appinfo            Application Information
Running  AppXSvc            AppX Deployment Service (AppXSVC)
Running  AudioEndpointBu... Windows Audio Endpoint Builder
Running  Audiosrv           Windows Audio
Running  BFE                Base Filtering Engine
...

Source code for our hostinfo.ps1 script

Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object -Property CSName, Caption, Version,BuildNumber, BuildType, OSType, RegisteredUser, OSArchitecture, ServicePackMajorVersion, ServicePackMinorVersion
Get-Service | Where-Object { $_.Status -eq "Running" }

Executing our hostinfo.ps1 script

PS C:\tools\windows_endpoint_introduction> .\hostinfo.ps1

CSName                  : CLIENT01
Caption                 : Microsoft Windows 10 Pro for Workstations
Version                 : 10.0.19043
BuildNumber             : 19043
BuildType               : Multiprocessor Free
OSType                  : 18
RegisteredUser          : offsec
OSArchitecture          : 64-bit
ServicePackMajorVersion : 0
ServicePackMinorVersion : 0

Status      : Running
Name        : AdvancedSystemCareService9
DisplayName : Advanced SystemCare Service 9

Status      : Running
Name        : Appinfo
DisplayName : Application Information
...

Getting help for the Get-CimInstance cmdlet

PS C:\Users\offsec> Get-Help Get-CimInstance

NAME
    Get-CimInstance

SYNOPSIS
    Gets the CIM instances of a class from a CIM server.
...

DESCRIPTION
    The Get-CimInstance cmdlet gets the CIM instances of a class
    from a CIM server. You can specify either the class name or
    a query for this cmdlet. This cmdlet returns one or more CIM
    instance objects representing a snapshot of the CIM instances
    present on the CIM server.

...
    Get-CimInstance [-ClassName] <System.String> [-ComputerName
    <System.String[]>] [-Filter <System.String>]
    [-KeyOnly] [-Namespace <System.String>] [-OperationTimeoutSec
    <System.UInt32>] [-Property <System.String[]>]
    [-QueryDialect <System.String>] [-Shallow] [<CommonParameters>]
...

Aliases can be queried with the Get-Alias cmdlet.

Using Get-Alias with gcim to show the original cmdlet

PS C:\Users\offsec> Get-Alias gcim

CommandType     Name                                        Version    Source
-----------     ----                                        -------    ------
Alias           gcim -> Get-CimInstance

If built-in PowerShell functions and scripts don't fit our needs, we can build our own.

Custom Function Example Get-AVInfo

function Get-AVInfo {
    gcim -Namespace root/SecurityCenter2 -ClassName AntivirusProduct
}

Importing and Executing the Get-AVInfo function

PS C:\Users\offsec> Import-Module C:\tools\windows_endpoint_introduction\get_avinfo.ps1

PS C:\Users\offsec> Get-AVInfo

displayName              : Windows Defender
instanceGuid             : {D68DDC3A-831F-4fae-9E44-DA132C1ACF46}
pathToSignedProductExe   : windowsdefender://
pathToSignedReportingExe : %ProgramFiles%\Windows Defender\MsMpeng.exe
productState             : 397568
timestamp                : Fri, 21 May 2021 13:08:38 GMT
PSComputerName           :

While some commands from cmd.exe still work in PowerShell, there may be analogous commands that are better for scripting purposes. For example, we can use [Security.Principal.WindowsIdentity]::GetCurrent().Name in place of whoami, or Get-NetIPConfiguration in lieu of ipconfig. In addition, we can store output subsets into variables and perform complicated function calls.

Programming on Windows

Component Object Model

COM is a code wrapper. Code wrappers reduce complexity of code without sacrificing utility. COM was later upgraded to the Distributed Component Object Model (DCOM). It addressed new issues between COM objects including memory and formatting issues when passing data between objects running on two different networked machines.

ActiveX later came into play, allowing execution of code that would run in the browser. ActiveX later evolved into .NET as well as .NET Core, aiming to address shortcomings of ActiveX whiel also enhancing reliability and suitability for applications.

.NET and .NET Core

The .NET Framework introducted C# and Visual Basic.NET, which provides wrappers for the Windows API as well as COM objects within the OS. .NET Core makes .NET available to other OS' in the marketplace. i.e. applications written in C# and other supportedl anguages can be compiled and executed on Linux as well as macOS without using a compatability layer.

Windows Event Log

Introduction to Windows Events

Event logs are stored in C:\Windows\System32\winevt\Logs where they're saved as .evtx files. These are restricted to privileged users and is encoded into hexadecimal values. Event Viewer can be used to parse the logs.

Windows Logs categories:

  • Application: events generated by Windows applications.

  • Security: authentication and other security-related activities.

  • Setup: details about upgrade installations or replacements by Windows Update

  • System: Native operating system behaviors that don't fit any of the other categories. ex. system restarts, mounting drives, etc.

PowerShell and Event Logs

Using Get-WinEvent to list all the different Windows Event Logs

PS C:\Windows\system32> Get-WinEvent -ListLog Application, Security, Setup, System

LogMode   MaximumSizeInBytes RecordCount LogName
-------   ------------------ ----------- -------
Circular            20971520        4388 Application
Circular            20971520         981 Security
Circular             1052672          60 Setup
Circular            20971520        1019 System

Getting all Security events with Get-WinEvent

PS C:\Windows\system32> Get-WinEvent -LogName Security | Select-Object -first 10

   ProviderName: Microsoft-Windows-Security-Auditing

TimeCreated             Id LevelDisplayName Message
-----------             -- ---------------- -------
4/23/2021 11:44:01 AM 4702 Informational    A scheduled task was updated....
4/23/2021 11:34:00 AM 4702 Informational    A scheduled task was updated....
4/23/2021 11:34:00 AM 4702 Informational    A scheduled task was updated....
4/23/2021 11:34:00 AM 4702 Informational    A scheduled task was updated....
4/23/2021 11:33:59 AM 4702 Informational    A scheduled task was updated....
4/23/2021 11:33:59 AM 4702 Informational    A scheduled task was updated....
4/23/2021 11:33:59 AM 4624 Information      An account was successfully logged on....
4/23/2021 11:23:59 AM 4702 Informational    A scheduled task was updated....
4/23/2021 11:23:59 AM 4702 Informational    A scheduled task was updated....
4/23/2021 11:23:59 AM 4702 Informational    A scheduled task was updated....

Getting all Logon Events with Get-WinEvent

PS C:\Windows\system32> Get-WinEvent -LogName 'Security' | Where-Object { $_.Id -eq "4624" } | Select-Object -Property TimeCreated,Message -first 10

TimeCreated          Message
-----------          -------                               
4/23/2021 2:18:25 PM An account was successfully logged on....
4/23/2021 2:18:24 PM An account was successfully logged on....
4/23/2021 2:12:23 PM An account was successfully logged on....
4/23/2021 10:16:55 AM An account was successfully logged on....
4/23/2021 10:05:57 AM An account was successfully logged on....
4/23/2021 10:05:57 AM An account was successfully logged on....
4/23/2021 10:00:11 AM An account was successfully logged on....
4/23/2021 9:54:07 AM  An account was successfully logged on....
4/23/2021 9:52:18 AM  An account was successfully logged on....
4/23/2021 9:48:55 AM  An account was successfully logged on....

Hash tables, in Powershell, are data structures that store pairings of keys and associated values. Using -FilterHashtableis more efficient because we're not piping all the results into another command.

Using FilterHashtable with Get-WinEvent to filter events

PS C:\Windows\system32> Get-WinEvent -FilterHashtable @{LogName='Security'; StartTime="4/23/2021 14:00:00"; EndTime="4/23/2021 14:30:00"; ID=4624} | Select-Object -Property TimeCreated,Message

TimeCreated           Message
-----------           -------
4/23/2021 2:18:25 PM An account was successfully logged on....
4/23/2021 2:18:24 PM An account was successfully logged on....
4/23/2021 2:12:23 PM An account was successfully logged on....  

Filter Logon events over the course of a weekend

PS C:\Windows\system32> Get-WinEvent -FilterHashtable @{LogName='Security'; StartTime="4/23/2021 19:00:00"; EndTime="4/26/2021 07:00:00"; ID=4624} | Select-Object -Property TimeCreated,Message

TimeCreated           Message
-----------           -------
4/24/2021 03:17:22 AM An account was successfully logged on....

Mapping elements in EventData for Logon events

Index 0 is "SubjectUserSid"
Index 1 is "SubjectUserName"
Index 2 is "SubjectDomainName"
Index 3 is "SubjectLogonId"
Index 4 is "TargetUserSid"
Index 5 is "TargetUserName"
Index 6 is "TargetDomainName"
Index 7 is "TargetLogonId"
Index 8 is "LogonType"
...

Filtering out a Logon Event and a specific Logon Type

PS C:\Windows\system32> Get-WinEvent -FilterHashtable @{LogName='Security'; StartTime="4/23/2021 00:00:00"; EndTime="4/26/2021 07:00:00"; ID=4624 } | Where-Object { $_.properties[8].value -eq 10 } | Format-List

TimeCreated  : 4/24/2021 03:17:22 AM
ProviderName : Microsoft-Windows-Security-Auditing
Id           : 4624
Message      : An account was successfully logged on.

               Subject:
                Security ID:            S-1-5-18
                Account Name:           CLIENT01$
                Account Domain:         WORKGROUP
                Logon ID:               0x3E7

               Logon Information:
                Logon Type:             10
                Restricted Admin Mode:  No
                Virtual Account:                No
                Elevated Token:         No

               Impersonation Level:             Impersonation
...
               Network Information:
                Workstation Name:       CLIENT01
                Source Network Address: 192.168.51.50
                Source Port:            0

Empowering the Logs

System Monitor (Sysmon)

SysMon is an enhanced auditing tool from the Sysinternals suite. It can be deployed to a Windows endpoint and create its own events as a separate provider under Applications and Services Logs.

Configuration Entires in a Sysmon XML File

<HashAlgorithms>MD5,SHA256,IMPHASH</HashAlgorithms>
<CopyOnDeletePE>True</CopyOnDeletePE>
<ArchiveDirectory>BackupDeleted</ArchiveDirectory>

Process Rule Group for Event Filtering in Sysmon Configuration

<RuleGroup name="Process Rules" groupRelation="or">
  <ProcessCreate onmatch="exclude">
    <Image condition="is">C:\Program Files\Windows Media Player\wmplayer.exe</Image>
    <Image condition="is">C:\Windows\system32\powercfg.exe</Image>
  </ProcessCreate>  
</RuleGroup>

Driver Rule Group for Event Filtering in Sysmon Configuration

<RuleGroup name="Driver Rules" groupRelation="or">
  <Driverload onmatch="exclude">
    <Signature condition="begin with">AMD</Signature>
    <Signature condition="contains">microsoft</Signature>
    <Signature condition="contains">windows</Signature>
  </Driverload>  
</RuleGroup>

Network Rule Groups for Event Filtering in Sysmon Configuration

<RuleGroup name="Network Process Rules" groupRelation="or">
  <NetworkConnect onmatch="exclude">
    <Image condition="end with">Chrome.exe</Image>
    <Image condition="end with">msedge.exe</Image>
  </NetworkConnect>
</RuleGroup>
<RuleGroup name="Network Port Rules" groupRelation="or">
  <NetworkConnect onmatch="include">
    <DestinationPort condition="is">8080</DestinationPort>
    <DestinationPort condition="is">443</DestinationPort>
  </NetworkConnect>
</RuleGroup>

Example Sysmon Config file

<Sysmon schemaversion="3.2">
  <HashAlgorithms>MD5,SHA256,IMPHASH</HashAlgorithms>
  <CopyOnDeletePE>True</CopyOnDeletePE>
  <ArchiveDirectory>BackupDeleted</ArchiveDirectory>
 <EventFiltering>
  <RuleGroup name="Process Rules" groupRelation="or">
    <ProcessCreate onmatch="exclude">
      <Image condition="is">C:\Program Files\Windows Media Player\wmplayer.exe</Image>
      <Image condition="is">C:\Windows\system32\powercfg.exe</Image>
  </RuleGroup>
  <RuleGroup name="Driver Rules" groupRelation="or">
    <Driverload onmatch="exclude">
      <Signature condition="begin with">AMD</Signature>
      <Signature condition="contains">microsoft</Signature>
      <Signature condition="contains">windows</Signature>
  </RuleGroup>
  <RuleGroup name="Network Process Rules" groupRelation="or">
    <NetworkConnect onmatch="exclude">
      <Image condition="end with">Chrome.exe</Image>
      <Image condition="end with">msedge.exe</Image>
    </NetworkConnect>
  </RuleGroup>
  <RuleGroup name="Network Port Rules" groupRelation="or">
    <NetworkConnect onmatch="include">
      <DestinationPort condition="is">8080</DestinationPort>
      <DestinationPort condition="is">443</DestinationPort>
    </NetworkConnect>
  </RuleGroup>
  </EventFiltering>
</Sysmon>

The above-linked Sysmon Configuration not only works as-is but includes many event filtering rules suitable for most enterprise environments.

Running Sysmon for the first time, confirming the config file in use

PS C:\Sysmon> .\Sysmon64.exe -c | Select-Object -first 10

System Monitor v13.10 - System activity monitor
Copyright (C) 2014-2021 Mark Russinovich and Thomas Garnier
Using libxml2. libxml2 is Copyright (C) 1998-2012 Daniel Veillard. All Rights Reserved.
Sysinternals - www.sysinternals.com

Current configuration:
 - Service name:                  Sysmon64
 - Driver name:                   SysmonDrv
 - Config file:                   C:\Sysmon\sysmonconfig-export.xml

Sysmon and Event Viewer

Sysmon events are stored in Applications and Services Logs/Microsoft/Windows/Sysmon/Operational.

The most important detail in the event is the Channel tag. This is the Log Name to be used when querying events via Get-WinEvent.

After deploying an XML configuration file for Sysmon, you may notice some additional false positives. These may be in the form of hundreds of events being created that are unhelpful and require tuning out. If this happens, we can update the configuration file to remove the rules associated with the events or add a rule to exclude them. You can use the "-c" argument of Sysmon to update the configuration that Sysmon uses.

Sysmon and PowerShell

Getting Sysmon events with Get-WinEvent

PS C:\Windows\system32> Get-WinEvent -LogName "Microsoft-Windows-Sysmon/Operational"

   ProviderName: Microsoft-Windows-Sysmon

TimeCreated                      Id LevelDisplayName Message
-----------                      -- ---------------- -------
4/29/2021 11:10:02 AM             1 Information      Process Create:...
4/29/2021 11:10:02 AM             1 Information      Process Create:...
4/29/2021 11:02:16 AM             5 Information      Process terminated:...
4/29/2021 10:52:38 AM            13 Information      Registry value set:...
4/29/2021 10:52:38 AM            13 Information      Registry value set:...
4/29/2021 10:52:38 AM            13 Information      Registry value set:...
4/29/2021 10:52:38 AM            13 Information      Registry value set:...
...

Custom function Get-SysmonEvent

function Get-SysmonEvent {
    Get-WinEvent -LogName "Microsoft-Windows-Sysmon/Operational"
}

Filtering out ProcessCreate Sysmon events

PS C:\Windows\system32> Get-SysmonEvent | Where-Object { $_.id -eq "1" }

   ProviderName: Microsoft-Windows-Sysmon

TimeCreated                      Id LevelDisplayName Message
-----------                      -- ---------------- -------
4/29/2021 1:43:31 PM              1 Information      Process Create:...
4/29/2021 1:43:30 PM              1 Information      Process Create:...
4/29/2021 1:43:30 PM              1 Information      Process Create:...

Updated Get-SysmonEvent with parameter support

function Get-SysmonEvent{
    param (
        $eventid,
        $start,
        $end
    )
    $filters = @{LogName = "Microsoft-Windows-Sysmon/Operational"}
    
    if ($eventid -ne $null) {
        $filters.ID = $eventid
    }
    
    if ($start -ne $null) {
        $filters.StartTime = $start
    }

    if ($end -ne $null) {
        $filters.EndTime = $end
    }
    Get-WinEvent -FilterHashtable $filters
}

Full Event Data for FileCreate Event

PS C:\Sysmon> Get-SysmonEvent 11 "4/28/2021 13:48:00" "4/28/2021 13:49:00" | Format-List

TimeCreated  : 4/28/2021 1:48:42 PM
ProviderName : Microsoft-Windows-Sysmon
Id           : 11
Message      : File created:
               RuleName: -
               UtcTime: 2021-04-28 18:48:42.900
               ProcessGuid: {71c0553d-bf88-60fa-d200-000000003300}
               ProcessId: 2032
               Image: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
               TargetFilename: C:\Sysmon\FileCreate.bat
               CreationUtcTime: 2021-04-28 18:48:42.900

Event Data in XML format for ProcessCreate

<EventData>
     <Data Name="RuleName">-</Data>
     <Data Name="UtcTime">2017-04-28 22:08:22.025</Data>
     <Data Name="ProcessGuid">{A23EAE89-BD56-5903-0000-0010E9D95E00}</Data>
     <Data Name="ProcessId">6228</Data>
...
</EventData>

ProcessCreate Event found with ProcessId Discovered from Another Event

PS C:\Sysmon> Get-SysmonEvent 1 $null "7/28/2021 13:48:42" | Where-Object { $_.properties[3].value -eq 2032 } | Format-List

TimeCreated  : 4/28/2021 13:48:02 AM
ProviderName : Microsoft-Windows-Sysmon
Id           : 1
Message      : Process Create:
               RuleName: -
               UtcTime: 2021-04-28 18:48:02.646
               ProcessGuid: {71c0553d-bf88-60fa-d200-000000003300}
               ProcessId: 2032
               Image: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

Remote Access with PowerShell Core

Connecting to a Windows 10 Machine using pwsh

PS /home/kali> Enter-PSSession 192.168.51.10 -Credential offsec -Authentication Negotiate

PowerShell credential request
Enter your credentials.

Password for user offsec: ***

[192.168.51.10]: PS C:\Users\offsec\Documents> 

Importing a local module while remotely connected via pwsh

[192.168.51.10]: PS C:\Users\offsec\Documents> Import-Module C:\Sysmon\Get-Sysmon.psm1

[192.168.51.10]: PS C:\Users\offsec\Documents> Get-Module

ModuleType Version    Name                                ExportedCommands                         
---------- -------    ----                                ----------------
Script     0.0    Get-Sysmon                          {Get-SysmonEvent}
Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Content...}
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object...}

From an auditing perspective, it's important to note that accessing Windows machines with pwsh generates a large volume of Logon/Logoff events with every command. When using Enter-PSSession interactively, it would be best to remember that the convenience comes with a price in terms of audit volume.

PreviousModule 2: Attacker Methodology IntroductionNextModule 4: Windows Server Side Attacks

Last updated 5 months ago

Rather than memorize every possible XML format for Windows events, Microsoft provides a reference for each one. The documentation contains an example of XML data mapping.

🛡️
Logon Events
GitHub - Neo23x0/sysmon-config: Sysmon configuration file template with default high-quality event tracingGitHub
Logo
Windows Event Viewer