PowerShell Objects and Get-FileHash
On Windows, the defender's shell is PowerShell, and its big difference from Bash is that commands pass objects, not text. Get-ChildItem emits file objects with a Length, a LastWriteTime and a FullName; Get-FileHash emits objects with an Algorithm, a Hash and a Path. You filter and compare them by property, so there is no awk '{print $11}' to get wrong. PowerShell is also an attacker's favourite tool on Windows, which is why its logging features matter. This lesson uses PowerShell 7.6 (which runs on Linux, macOS and Windows) for file inventories and hash baselines, and shows the one habit that turns a PowerShell script into a command-injection hole. The language itself is taught in PowerShell.
Definitions
- Object pipeline:
A | Bpasses .NET objects from A to B.Select-Object,Where-Object,Sort-Object,Group-ObjectandMeasure-Objectwork on properties. Get-FileHash -Algorithm SHA256: hashes files (SHA1, SHA256, SHA384, SHA512, MD5); the default is SHA256.Compare-Object: compares two collections, optionally by property;<=means "only in the reference",=>"only in the difference".ConvertTo-Json/ConvertFrom-Json,Export-Csv/Import-Csv: turn objects into text and back, for baselines and reports.Invoke-Expression(iex): runs a string as PowerShell code, the equivalent ofeval.
An inventory with hashes
The session creates a small application folder, records a baseline (name, size and SHA-256 per file) as JSON, then changes one file and adds another, and compares. It runs in a temporary folder; on a real server the baseline would be stored elsewhere.
$root = Join-Path ([IO.Path]::GetTempPath()) 'labapp'
Remove-Item $root -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Path "$root/bin", "$root/conf" | Out-Null
Set-Content "$root/bin/service.ps1" 'Write-Output "lab service"'
Set-Content "$root/conf/app.json" '{"debug": false}'
Set-Content "$root/README.txt" 'Lab application'
function Get-Inventory($path) {
Get-ChildItem $path -Recurse -File | Sort-Object FullName | ForEach-Object {
[pscustomobject]@{
Path = [IO.Path]::GetRelativePath($path, $_.FullName)
Length = $_.Length
SHA256 = (Get-FileHash $_.FullName -Algorithm SHA256).Hash
}
}
}
$baseline = Get-Inventory $root
$baseline | Select-Object Path, Length, @{n='SHA256'; e={$_.SHA256.Substring(0, 16) + '...'}} | Format-Table -AutoSize | Out-String -Stream | Where-Object { $_ }
$baseline | ConvertTo-Json | Set-Content "$root/../labapp-baseline.json"
# --- simulated change ---
Set-Content "$root/conf/app.json" '{"debug": true}'
Set-Content "$root/bin/helper.ps1" 'Write-Output "new file"'
$saved = Get-Content "$root/../labapp-baseline.json" -Raw | ConvertFrom-Json
$current = Get-Inventory $root
"== changes"
Compare-Object $saved $current -Property Path, SHA256 | Sort-Object Path, SideIndicator |
ForEach-Object { '{0} {1}' -f $_.SideIndicator, $_.Path }
"== summary"
$changed = Compare-Object $saved $current -Property Path, SHA256 | Group-Object Path
foreach ($g in $changed) {
$kind = if ($g.Count -eq 2) { 'MODIFIED' } elseif ($g.Group[0].SideIndicator -eq '=>') { 'ADDED' } else { 'REMOVED' }
'{0,-9} {1}' -f $kind, $g.Name
}Path Length SHA256
---- ------ ------
bin/service.ps1 27 5A0A6EF431C98038...
conf/app.json 17 589EA70EB20D88D5...
README.txt 16 767E62545A77CBAA...
== changes
=> bin/helper.ps1
<= conf/app.json
=> conf/app.json
== summary
ADDED bin/helper.ps1
MODIFIED conf/app.json
Compare-Object by Path and SHA256 reports a changed file as two rows (old hash <=, new hash =>) and a new file as one => row; grouping by path turns that into MODIFIED and ADDED. No column positions, no text parsing: the properties carry the meaning.
The eval trap: Invoke-Expression
Scripts sometimes build a command as a string and run it with Invoke-Expression. If any part of the string comes from outside, the caller can add commands, exactly like shell=True in Python. The "attack" below only prints a marker.
function Get-SizeUnsafe([string]$name) {
Invoke-Expression "(Get-Item -LiteralPath '/tmp/$name' -ErrorAction SilentlyContinue).Length"
}
function Get-SizeSafe([string]$name) {
$p = Join-Path '/tmp' $name
if ((Split-Path $p -Parent) -ne '/tmp') { return 'refused: path leaves /tmp' }
$item = Get-Item -LiteralPath $p -ErrorAction SilentlyContinue
if ($item) { $item.Length } else { 'no such file' }
}
Set-Content /tmp/report.txt 'lab report'
$evil = "report.txt').Length; Write-Output 'INJECTED: this ran as code' #"
"unsafe normal -> " + (Get-SizeUnsafe 'report.txt')
"unsafe evil -> " + ((Get-SizeUnsafe $evil) -join ' | ')
"safe normal -> " + (Get-SizeSafe 'report.txt')
"safe evil -> " + (Get-SizeSafe $evil)
"safe ../ -> " + (Get-SizeSafe '../etc/passwd')unsafe normal -> 11
unsafe evil -> 11 | INJECTED: this ran as code
safe normal -> 11
safe evil -> no such file
safe ../ -> refused: path leaves /tmp
The single quote and the parenthesis in the "file name" close the expression inside the generated code, the Write-Output runs as a second statement, and the # comments out the rest of the original line so the result still parses. The safe version never turns data into code: it passes the name as a parameter value, uses -LiteralPath (so wildcard characters such as [ and * are not interpreted) and checks that the path stays in the intended folder.
How it is detected
- Script Block Logging (event ID 4104 in
Microsoft-Windows-PowerShell/Operationalfor Windows PowerShell 5.1; PowerShell 7 writes toPowerShellCore/Operational) records the code PowerShell actually compiled, including whatInvoke-Expressionran and decoded-EncodedCommandpayloads. Module logging (4103) records pipeline execution; transcription writes everything to text files. Turn them on by Group Policy. - Hunting queries look for
Invoke-Expression/iex,FromBase64String,-EncodedCommand,DownloadString,-WindowStyle Hiddenand-ExecutionPolicy Bypassin 4104 and process-creation (4688, Sysmon 1) command lines. - In code review: PSScriptAnalyzer's rule
PSAvoidUsingInvokeExpressionflags everyInvoke-Expression. - File changes: an inventory like the first example, run on a schedule, catches changed scripts and configuration.
How it is prevented
- Never build code from strings. Call commands directly with parameters; for external programs use the call operator with an argument array:
& 'C:\Tools\tool.exe' @argsArray. -LiteralPathfor any path from outside, andJoin-Pathplus a parent check for traversal.- Validate parameters with
[ValidatePattern()],[ValidateSet()]and[ValidateRange()]attributes inparam()blocks. - Sign production scripts and use an
AllSignedexecution policy, AppLocker or WDAC. The execution policy alone is not a security boundary (-ExecutionPolicy Bypassskips it); application control is. - Constrained Language Mode (enforced by WDAC/AppLocker) blocks .NET calls and
Add-Typefor untrusted scripts. The Windows and Active Directory course covers these features.
Pitfalls
Format-Tableoutput is for eyes only. Never pipe it into files or other commands; pipe the objects (Export-Csv,ConvertTo-Json) instead.-Pathtreats[]*?as wildcards. A file calledreport[1].txtis not found by-Path; use-LiteralPath.ConvertTo-Jsondepth: the default-Depthis 2, and deeper objects become strings. Pass-Depth 5for nested data.- Hash case:
Get-FileHashreturns upper-case hex,sha256sumlower-case. Compare with-eq(case-insensitive in PowerShell) or normalise.
Practice
1. Change the inventory to also flag files whose size changed but whose hash did not. Can that happen?
No: if the content is the same, the hash and the size are the same. Size is only a cheap pre-filter. A file with the same hash and a different LastWriteTime is the interesting case: someone touched it without changing it, or restored it.
2. Rewrite Invoke-Expression "ping -n 1 $hostName" safely on Windows.
Validate first ([ValidatePattern('^[A-Za-z0-9.-]{1,253}#39;)] on the parameter, or [ipaddress]::TryParse), then call it directly: & ping.exe -n 1 $hostName, or use Test-Connection -TargetName $hostName -Count 1. Inside the lab only.
3. Which event would show you that a script ran Invoke-Expression on a decoded Base64 string?
Event 4104 (Script Block Logging): PowerShell logs the script block it compiled, so the decoded code appears in clear text, and since PowerShell 5 blocks containing suspicious keywords are logged with level Warning even when Script Block Logging is not turned on (unless it is explicitly disabled; Microsoft's PowerShell team announced this on its blog rather than in the reference documentation).
Test yourself
Why is Compare-Object $saved $current -Property Path, SHA256 more reliable than comparing text output?
- It is faster
- It compares objects by named properties, so column positions and formatting can't break it
- It ignores changes
- It needs no baseline
In the injection example, what turned the file name into code?
- Get-Item
- -LiteralPath
- Building a string of code and passing it to Invoke-Expression
- Join-Path
Which event ID records the PowerShell code that was actually executed, including decoded payloads?
- 4624
- 4104
- 7045
- 1102
Is the PowerShell execution policy a security boundary?
- Yes, it blocks all unsigned code
- No; it can be bypassed with -ExecutionPolicy Bypass. Application control (AppLocker, WDAC) is the boundary
- Only on Linux
- Only for administrators