Skip to content

Commit

Permalink
Improve code readability by adding braces to functions (#279)
Browse files Browse the repository at this point in the history
This commit updates multiple PowerShell scripts to include braces `{}` around `foreach` loops, conditional statements, and function definitions. These changes enhance code clarity and structure across various functions in the Hawk module, ensuring better maintainability and adherence to coding best practices. Additionally, some scripts have been updated to improve error handling and logging.

Co-authored-by: Antonio Santana <[email protected]>
  • Loading branch information
Sntai20 and Antonio Santana authored Mar 3, 2025
1 parent f2f9030 commit aa23e68
Show file tree
Hide file tree
Showing 90 changed files with 1,890 additions and 944 deletions.
6 changes: 4 additions & 2 deletions Hawk/Hawk.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ function Import-ModuleFile
if ($importIndividualFiles)
{
# Execute Preimport actions
foreach ($path in (& "$ModuleRoot\internal\scripts\preimport.ps1")) {
foreach ($path in (& "$ModuleRoot\internal\scripts\preimport.ps1"))
{
. Import-ModuleFile -Path $path
}

Expand All @@ -71,7 +72,8 @@ if ($importIndividualFiles)
}

# Execute Postimport actions
foreach ($path in (& "$ModuleRoot\internal\scripts\postimport.ps1")) {
foreach ($path in (& "$ModuleRoot\internal\scripts\postimport.ps1"))
{
. Import-ModuleFile -Path $path
}

Expand Down
3 changes: 2 additions & 1 deletion Hawk/functions/General/Show-HawkHelp.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
.NOTES
General notes
#>
Function Show-HawkHelp {
Function Show-HawkHelp
{

Out-LogFile "Creating Hawk Help File"

Expand Down
50 changes: 34 additions & 16 deletions Hawk/functions/General/Update-HawkModule.ps1
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
Function Update-HawkModule {
Function Update-HawkModule
{
<#
.SYNOPSIS
Hawk upgrade check.
Expand Down Expand Up @@ -30,26 +31,31 @@
)

# If ElevatedUpdate is true then we are running from a forced elevation and we just need to run without prompting
if ($ElevatedUpdate) {
if ($ElevatedUpdate)
{
# Set upgrade to true
$Upgrade = $true
}
else {
else
{

# See if we can do an upgrade check
if ($null -eq (Get-Command Find-Module)) { }

# If we can then look for an updated version of the module
else {
else
{
Out-LogFile "Checking for latest version online" -Action
$onlineversion = Find-Module -name Hawk -erroraction silentlycontinue
$Localversion = (Get-Module Hawk | Sort-Object -Property Version -Descending)[0]
Out-LogFile ("Found Version " + $onlineversion.version + " Online") -Information

if ($null -eq $onlineversion) {
if ($null -eq $onlineversion)
{
Out-LogFile "[ERROR] - Unable to check Hawk version in Gallery" -isError
}
elseif (([version]$onlineversion.version) -gt ([version]$localversion.version)) {
elseif (([version]$onlineversion.version) -gt ([version]$localversion.version))
{
Out-LogFile "New version of Hawk module found online" -Information
Out-LogFile ("Local Version: " + $localversion.version + " Online Version: " + $onlineversion.version) -Information

Expand All @@ -62,26 +68,35 @@
$result = $host.ui.PromptForChoice($title, $message, $options, 0)

# Check to see what the user choose
switch ($result) {
0 { $Upgrade = $true; Send-AIEvent -Event Upgrade -Properties @{"Upgrade" = "True" }
switch ($result)
{
0
{
$Upgrade = $true; Send-AIEvent -Event Upgrade -Properties @{"Upgrade" = "True" }
}
1 { $Upgrade = $false; Send-AIEvent -Event Upgrade -Properties @{"Upgrade" = "False" }
1
{
$Upgrade = $false; Send-AIEvent -Event Upgrade -Properties @{"Upgrade" = "False" }
}
}
}
# If the versions match then we don't need to upgrade
else {
else
{
Out-LogFile "Latest Version Installed" -Information
}
}
}

# If we determined that we want to do an upgrade make the needed checks and do it
if ($Upgrade) {
if ($Upgrade)
{
# Determine if we have an elevated powershell prompt
If (([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
If (([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
{
# Update the module
if ($PSCmdlet.ShouldProcess("Hawk Module", "Update module")) {
if ($PSCmdlet.ShouldProcess("Hawk Module", "Update module"))
{
Out-LogFile "Downloading Updated Hawk Module" -Action
Update-Module Hawk -Force
Out-LogFile "Update Finished" -Action
Expand All @@ -91,7 +106,8 @@
if ($ElevatedUpdate) { exit }

# If we didn't elevate then we are running in the admin prompt and we need to import the new hawk module
else {
else
{
Out-LogFile "Starting new PowerShell Window with the updated Hawk Module loaded" -Action

# We can't load a new copy of the same module from inside the module so we have to start a new window
Expand All @@ -102,7 +118,8 @@
}
}
# If we are not running as admin we need to start an admin prompt
else {
else
{
# Relaunch as an elevated process:
Out-LogFile "Starting Elevated Prompt" -Action
Start-Process powershell.exe -ArgumentList "-noexit -Command Import-Module Hawk;Update-HawkModule -ElevatedUpdate" -Verb RunAs -Wait
Expand All @@ -116,7 +133,8 @@
}
}
# Since upgrade is false we log and continue
else {
else
{
Out-LogFile "Skipping Upgrade" -Action
}
}
93 changes: 62 additions & 31 deletions Hawk/functions/Message/Get-HawkMessageHeader.ps1
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
Function Get-HawkMessageHeader {
Function Get-HawkMessageHeader
{
<#
.SYNOPSIS
Gathers the header from the an msg file prepares a report
Expand Down Expand Up @@ -34,10 +35,12 @@
)

# Create the outlook com object
try {
try
{
$ol = New-Object -ComObject Outlook.Application
}
catch [System.Runtime.InteropServices.COMException] {
catch [System.Runtime.InteropServices.COMException]
{
# If we throw a com expection most likely reason is outlook isn't installed
Out-LogFile "Unable to create outlook com object." -error
Out-LogFile "Please make sure outlook is installed." -error
Expand All @@ -53,7 +56,8 @@


# check to see if we have a valid file path
if (Test-Path $MSGFile) {
if (Test-Path $MSGFile)
{

# Convert a possible relative path to a full path
$MSGFile = (Resolve-Path $MSGFile).Path
Expand All @@ -63,19 +67,22 @@

Out-LogFile ("Reading message header from file " + $MSGFile) -action
# Import the message and start processing the header
try {
try
{
$msg = $ol.CreateItemFromTemplate($MSGFile)
$header = $msg.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x007D001E")
}
catch {
catch
{
Out-LogFile ("Unable to load " + $MSGFile)
Out-LogFile $Error[0]
break
}

$headersWithLines = $header.split("`n")
}
else {
else
{
# If we don't have a valid file path log an error and stop
Out-LogFile ("Failed to find file " + $MSGFile) -error
Write-Error -Message "Failed to find file " + $MSGFile -ErrorAction Stop
Expand All @@ -86,9 +93,11 @@
[array]$Output = $null

# Read thru each line to pull together each entry into a single object
foreach ($string in $headersWithLines) {
foreach ($string in $headersWithLines)
{
# If our string is not null and we have a leading whitespace then this needs to be added to the previous string as part of the same object.
if (!([string]::IsNullOrEmpty($string)) -and ([char]::IsWhiteSpace($string[0]))) {
if (!([string]::IsNullOrEmpty($string)) -and ([char]::IsWhiteSpace($string[0])))
{
# Do some string clean up
$string = $string.trimstart()
$string = $string.trimend()
Expand All @@ -100,14 +109,17 @@

# If we are here we do a null check just in case but we know the first char is not a whitespace
# So we have a new "object" that we need to process in
elseif (!([string]::IsNullOrEmpty($string))) {
elseif (!([string]::IsNullOrEmpty($string)))
{

# For the inital pass the string will be null or empty so we need to check for that
if ([string]::IsNullOrEmpty($CombinedString)) {
if ([string]::IsNullOrEmpty($CombinedString))
{
# Create our new string and continue processing
$CombinedString = ($string.trimend())
}
else {
else
{
# We should have everything now so create the object
$Object = $null
$Object = New-Object -TypeName PSObject
Expand Down Expand Up @@ -137,21 +149,25 @@
# Determine the initial submitting client/ip

[array]$receivedHeadersString = $Output | Where-Object { $_.header -eq "Received" }
foreach ($stringHeader in $receivedHeadersString.value) {
foreach ($stringHeader in $receivedHeadersString.value)
{
[array]$receivedHeadersObject += Convert-ReceiveHeader -Header $stringHeader
}

# Sort the receive header so oldest is at the top
$receivedHeadersObject = $receivedHeadersObject | Sort-Object -Property ReceivedFromTime

if ($null -eq $receivedHeadersObject) { }
else {
else
{

# Determine how it was submitted to the service
if ($receivedHeadersObject[0].ReceivedBy -like "*outlook.com*") {
if ($receivedHeadersObject[0].ReceivedBy -like "*outlook.com*")
{
$Findings += (Add-Finding -Name "Submitting Host" -Value $receivedHeadersObject[0].ReceivedBy -Conclusion "Submitted from Office 365" -MoreInformation "Warning - This might have originated from one of your clients")
}
else {
else
{
$Findings += (Add-Finding -Name "Submitting Host" -Value $receivedHeadersObject[0].ReceivedBy -Conclusion "Submitted from Internet" -MoreInformation "")
}

Expand All @@ -163,12 +179,15 @@
$AuthAs = $output | Where-Object { $_.header -like 'X-MS-Exchange-Organization-AuthAs' }
# Make sure we got something back
if ($null -eq $AuthAs) { }
else {
else
{
# If auth is anonymous then it came from the internet
if ($AuthAs.value -eq "Anonymous") {
if ($AuthAs.value -eq "Anonymous")
{
$Findings += (Add-Finding -Name "Authentication Method" -Value $AuthAs.value -Conclusion "Method used to authenticate" -MoreInformation "https://docs.microsoft.com/en-us/exchange/header-firewall-exchange-2013-help")
}
else {
else
{
$Findings += (Add-Finding -Name "Authentication Method" -Value $AuthAs.value -Conclusion "Method used to authenticate" -MoreInformation "https://docs.microsoft.com/en-us/exchange/header-firewall-exchange-2013-help")
}
}
Expand All @@ -177,12 +196,15 @@
$AuthMech = $output | Where-Object { $_.header -like 'X-MS-Exchange-Organization-AuthMechanism' }
# Make sure we got something back
if ($null -eq $AuthMech) { }
else {
else
{
# If auth is anonymous then it came from the internet
if ($AuthMech.value -eq "04" -or $AuthMech.value -eq "06") {
if ($AuthMech.value -eq "04" -or $AuthMech.value -eq "06")
{
$Findings += (Add-Finding -Name "Authentication Mechanism" -Value $AuthMech.value -Conclusion "04 = Credentials Used; 06 = SMTP Authentication" -MoreInformation "https://docs.microsoft.com/en-us/exchange/header-firewall-exchange-2013-help")
}
else {
else
{
$Findings += (Add-Finding -Name "Authentication Mechanism" -Value $AuthMech.value -Conclusion "Mechanism used to authenticate" -MoreInformation "https://docs.microsoft.com/en-us/exchange/header-firewall-exchange-2013-help")
}
}
Expand All @@ -195,19 +217,23 @@
$frommatches = $null
$frommatches = $From.Value | Select-String -Pattern '(?<=<)([\s\S]*?)(?=>)' -AllMatches

if ($null -ne $frommatches) {
if ($null -ne $frommatches)
{
# Pull the string from the matches
[string]$fromString = $frommatches.Matches.Groups[1].Value
}
else {
else
{
[string]$fromString = $From.value
}

# Check to see if they match
if ($fromString.trim() -eq $ReturnPath.value.trim()) {
if ($fromString.trim() -eq $ReturnPath.value.trim())
{
$Findings += (Add-Finding -Name "P1 P2 Match" -Value ("From: " + $From.value + "; Return-Path: " + $ReturnPath.value) -Conclusion "P1 and P2 Header match" -MoreInformation "")
}
else {
else
{
$Findings += (Add-Finding -Name "P1 P2 Match" -Value ("From: " + $From.value + "; Return-Path: " + $ReturnPath.value) -Conclusion "P1 and P2 Header don't Match" -MoreInformation "WARNING - P1 and P2 Header don't Match")
}

Expand All @@ -223,7 +249,8 @@


# Function to create a finding object for adding to the output array
Function Add-Finding {
Function Add-Finding
{
param (
[string]$Name,
[string]$Value,
Expand All @@ -246,7 +273,8 @@ Function Add-Finding {
}

# Processing a received header and returns it as a object
Function Convert-ReceiveHeader {
Function Convert-ReceiveHeader
{
#Core code from https://blogs.technet.microsoft.com/heyscriptingguy/2011/08/18/use-powershell-to-parse-email-message-headerspart-1/
Param
(
Expand All @@ -265,9 +293,11 @@ Function Convert-ReceiveHeader {
$headerMatches = $Header | Select-String -Pattern $HeaderRegex -AllMatches

# Check if we got back results
if ($null -ne $headerMatches) {
if ($null -ne $headerMatches)
{
# Formatch our with
Switch -wildcard ($headerMatches.Matches.groups[3].value.trim()) {
Switch -wildcard ($headerMatches.Matches.groups[3].value.trim())
{
"SMTP*" { $with = "SMTP" }
"ESMTP*" { $with = "ESMTP" }
default { $with = $headerMatches.Matches.groups[3].value.trim() }
Expand All @@ -286,7 +316,8 @@ Function Convert-ReceiveHeader {
return $Output
}
# If we failed to match then return null
else {
else
{
return $null
}
}
Loading

0 comments on commit aa23e68

Please sign in to comment.