🆕 Introducing HTB CDEP: Certified Detection Engineering Principal Learn More

PowerShell for Analysis

mini-module tag Mini-Module

The "PowerShell for Analysis" module is designed to equip cybersecurity professionals with the skills to leverage PowerShell's scripting capabilities for thorough and effective analysis of data, enabling robust threat investigations within cybersecurity.

Created by letsdefendio

Hard Defensive

Summary

The PowerShell for Analysis module is designed for cybersecurity analysts and professionals in threat intelligence, Incident responders seeking to enhance their analysis capabilities, and IT professionals looking to utilize PowerShell for cybersecurity analysis. Throughout this module, students will develop proficiency in leveraging PowerShell scripts for data analysis in cybersecurity contexts, enhanced abilities in conducting thorough threat investigations and security analysis, and improved automation in data analysis processes for quicker insights.

Recommended prior knowledge:

  • Basic understanding of cybersecurity concepts and practices

  • Familiarity with PowerShell scripting (recommended but not mandatory)

Analysis of Log Files with PowerShell


Powershell provides us with very useful tools for performing security tasks. In this module, we will discuss these and examine how we can benefit from Powershell at various stages of security.

First, let's see how we can perform research/examination on log files of different products/services using PowerShell:

PowerShell is a very useful tool for analyzing log files. You can read, search and manipulate log files using cmdlets such as Get-Content , Select-String , ConvertFrom-Json and ConvertTo-Json .

In the next part of our training, we will work on the log file of our IIS Web server. Let's first read the content of this file:

PS C:\> Get-Content -Path "C:\inetpub\logs\LogFiles\W3SVC1\u_ex230629.log"

When we run this cmdlet, it will read the log file in the path we give as a parameter and print its contents to the screen.

What if our goal was to list the lines containing the phrase “letsdefend” instead of the entire file? Yes, there is a simple way to do this:

PS C:\> Get-Content -Path "C:\inetpub\logs\LogFiles\W3SVC1\u_ex230629.log" | Select-String -Pattern "letsdefend"

When we run this command, it will print only the lines containing the phrase “letsdefend” in the entire log file:

When we want to monitor the changes on this file in real time, we can use the -Wait parameter. When we execute the command below, the Get-Content cmdlet first dumps the contents of the current file to the screen and then starts waiting instead of falling back to the command line. If new content is added to the file (in our example, since we are examining the access logs of a web server, if a new request comes to the server whose logs we are examining), it adds this content to the dump on the screen.

PS C:\> Get-Content -Path "C:\inetpub\logs\LogFiles\W3SVC1\u_ex230629.log" -Wait | Select-String -Pattern "letsdefend"

When we combine this feature with the Select-String example we used in the previous example, we will be able to see when a log that hits the pattern we are looking for is written to the log file we are monitoring.

We can see this in the screenshot below. When we first run the command, it dumps the lines containing "letsdefend" in the relevant log file and then starts monitoring the log file. When we send the waitExample=letsdefend parameters to the web server's index file with get, the last line is added.

Let's write a script on the same log file that counts how many requests came from the same IP address:

# log file location
$filePath = "C:\inetpub\logs\LogFiles\W3SVC1\u_ex230629.log"

# Get 'c-ip' (client IP) field index from log file header
$ipFieldIndex = (Get-Content -Path $filePath | Where-Object { $_ -match "^#Fields:" }).Split(' ').IndexOf('c-ip') -1

# Skip informational lines
$logContent = Get-Content -Path $filePath | Where-Object { $_ -notmatch "^#" }

$ipCount = @{}

foreach($line in $logContent) {
	$ip = $line.Split(' ')[$ipFieldIndex]
	if ($ipCount.ContainsKey($ip)) {
		$ipCount[$ip]++
	} else {
		$ipCount[$ip] = 1
	}
}

$ipCount

In our script, we first find the order of the c-ip column by reading the Fields line, which is included as standard in IIS Log files. This way, we know which columns in the log rows we need to read.

You can see these details in the screenshot of the log file below:

We then create a hashtable ($ipCount) and add each IP address we see for the first time to this hashtable. If an IP address already exists in the hashtable, we increase its number by one. If it does not exist in the hashtable, we create a new key-value pair and set its number to 1. When the script is finished, we print the $ipCount hashtable and show how many requests each IP address made.

Finally, let's look at our output:

By changing the fields in the #Fields line, we can extract their counts in the requesting URLs instead of the source IP address, for example:

Now, let's work on the DHCP log file this time and use the PowerShell Object structure in this example:

Let's have a log file like below. This log file is usually found on DC Servers with the DHCP Server role installed and keeps a record of DHCP operations.

The purpose of the script below is to examine this log file and record the activities of the MAC address we have given:

PS C:\> $macAddress = "00-10-22-01-23-45"
$logPath = "dhcp.log"

$events = Get-Content -Path $logPath |
Where-Object { $_ -match $macAddress } |
ForEach-Object {
	$fields = $_.Split(',')
	$eventDate = [DateTime]::ParseExact($fields[1], "MM/dd/yy HH:mm:ss", $null)
	$eventType = $fields[2]
	$ipAddress = $fields[3]
	$deviceName = $fields[4]
	$mac = $fields[5]

	if ($mac -eq $macAddress) {
		New-Object -TypeName PSObject -Property @{
			EventDate = $eventDate
			EventType = $eventType
			IPAddress = $ipAddress
			DeviceName = $deviceName
			MACAddress = $mac
			}
		}
}

$events | Sort-Object -Property EventDate

Let's detail what we did in which line of this script:

$macAddress = "00-14-22-01-23-45"

In this line, we give the mac address that we will be searching in the log file as a value to the $macAddress variable.

$logPath = "dhcp.log"

In this line, we assign the path of the log file we will examine as a value to the $logPath variable (in this example, since the script and the log file are in the same directory, we only need to write the name of the log file).

$events = Get-Content -Path $logPath |
Where-Object { $_ -match $macAddress } |
ForEach-Object { …

In this part, we add the $logPath variable we have just defined to the Get-Content cmdlet with the -Path parameter.

We then assign the content that reads with | to the Where-Object cmdlet with the - match $macAddress parameter.

Our goal here is to search for the value we previously defined in the $macAddress variable in the data coming from the log file.

In the next step, we assign the output that we obtained by using a second | to the ForEach-Object cmdlet. Now we have the row(s) containing the MAC addresses we specified. Now we can process this data:

ForEach-Object {
$fields = $_.Split(',')
$eventDate = [DateTime]::ParseExact($fields[1], "MM/dd/yy HH:mm:ss", $null)
$eventType = $fields[2]
$ipAddress = $fields[3]
$deviceName = $fields[4]
$mac = $fields[5]

In this part, we divide each incoming row into columns using the ,” character and

add each piece to the $fields variable as an array item.

Next, we assign the fields to variables for later use. Notice that here we have converted the data that is in the $fields[2] field as a string into DateTime type data.

We do this so that we can sort the output correctly in chronological order when printing it to the screen.

We continue by checking whether the data we are processing contains the MAC address we are looking for or not:

PS C:\> if ($mac -eq $macAddress) {
	New-Object -TypeName PSObject -Property @{
		EventDate = $eventDate
		EventType = $eventType
		IPAddress = $ipAddress
		DeviceName = $deviceName
		MACAddress = $mac
		}
}

If the MAC address found in the line (the value of the $mac variable)

is equal to the MAC address ( $macAddress ) we defined at the beginning of the script ( -eq ), we write the content of this line to a new powershell object.

$events | Sort-Object -Property EventDate

In our last line, we assign the events we have (content of the $events variable) to the Sort-Object -Property cmdlet

to sort them according to the EventDate column.

And when we run our script, the result we get is as follows:

While converting the data we were looking for into the powershell object data type, we said that we did this to sort the data by date. Once we convert the data to object type, it is now very easy to use it in different ways. For example, let's say we want to convert this data to JSON format. To do this, we just need to deliver the data we have to the ConvertTo-Json cmdlet:

$events | Sort-Object -Property EventDate | ConvertTo-Json

When we do this our output will look like this:

If we need different types of output, you can also use cmdlets such as ConvertTo-Csv, ConvertTo-Xml, ConvertTo-Html instead of ConvertTo-Json .

If we want to write the output we obtain in any format to a file rather than to the screen, all we have to do is assign the output to the Set-Content cmdlet and specify which file we want to write to with the -Path parameter:

$events | Sort-Object -Property EventDate | ConvertTo-Json | Set-Content -Path "result.json"

In this part of the training, we have covered how to analyze log files with Powershell through powershell codes. In the next part of the training, we will learn about the Windows EventLog Analysis with Powershell topic.

Sign Up / Log In to Unlock the Module

Please Sign Up or Log In to unlock the module and access the rest of the sections.

Relevant Paths

This module progresses you towards the following Paths

Programming for Cybersecurity

Gain essential coding skills for cybersecurity, across PowerShell, Bash, Python, and Go, to protect against digital threats and enhance your abilities in the ever-evolving field of cyber defense.

Hard Path Sections 63 Sections
Required: 400
Reward: +80
Path Modules
Medium
Path Sections 10 Sections
Reward: +10 NEW
The "Introduction to Python" module is designed to familiarize detection engineers in cybersecurity with the Python programming language, enabling them to effectively apply it in the context of threat detection and analysis.
Python for Blue Team
mini module tag Mini-Module
Hard
Path Sections 8 Sections
Reward: +10 NEW
The "Python for Blue Team" module focuses on equipping cybersecurity professionals within the Blue Team with practical Python skills tailored for effective threat detection and strategic defense methodologies.
Medium
Path Sections 7 Sections
Reward: +0 NEW
This module is designed to provide detection engineers in the cybersecurity field with a foundational understanding of Bash scripting, enabling them to bolster their capabilities in threat detection and incident response.
Hard
Path Sections 6 Sections
Reward: +10 NEW
The "Advanced Bash Scripting" module is designed to improve participants' knowledge and skills in using complex scripting techniques for cybersecurity. It aims to enable individuals to effectively tackle intricate security challenges by employing advanced scripting methodologies.
Hard
Path Sections 7 Sections
Reward: +10 NEW
The "Bash Scripting for Blue Team" module focuses on providing the essential scripting skills required for cybersecurity defense, specifically tailored for the Blue Team. It aims to equip individuals with the practical knowledge needed to proactively manage and defend against security threats.
Easy
Path Sections 7 Sections
Reward: +10 NEW
The "Introduction to PowerShell" module is designed to provide participants with a fundamental understanding of PowerShell, covering installation, basic command usage, file and directory operations, optimization techniques, and effective error handling for a well-rounded learning experience.
Hard
Path Sections 6 Sections
Reward: +10 NEW
The "PowerShell for Analysis" module is designed to equip cybersecurity professionals with the skills to leverage PowerShell's scripting capabilities for thorough and effective analysis of data, enabling robust threat investigations within cybersecurity.
Hard
Path Sections 7 Sections
Reward: +10 NEW
The "Advanced PowerShell for Blue Team" module is designed to improve participants' knowledge of using advanced PowerShell techniques. This module is specifically customized to enhance cybersecurity defense strategies for the Blue Team.
Go for Cybersecurity
mini module tag Mini-Module
Medium
Path Sections 5 Sections
Reward: +10 NEW
Discover how to detect and thwart malicious activity across various domains with our specialized Golang for Cybersecurity module. Gain the expertise to analyze, identify, and counter potential threats lurking within emails, networks, systems, and files. Through practical exercises and real-world examples, learners will master the application of Golang to fortify their cybersecurity defenses and safeguard critical digital assets.