Notes
Objects, not text
One idea makes PowerShell different. In Bash the pipe carries text, and you cut fields out with grep and awk. In PowerShell the pipe carries objects with named properties. So you filter with where object, sort with sort object and choose columns with select object, all by property name. Commands are named verb dash noun, like get process. Three commands teach you everything else: get command to find commands, get help for examples, and get member to see an object's properties.
# verb-noun commands (cmdlets) Get-Process | Where-Object CPU -gt 100 | Sort-Object CPU -Descending | Select-Object -First 5 Name, CPU # no grep or awk: you filter and # pick properties by name Get-Command *event* find commands Get-Help Get-WinEvent -Examples Get-Process | Get-Member properties
Event logs
Here is the Windows version of the Bash log analysis. Get win event reads event logs, and the filter hash table narrows it on the server side: the security log, event four six two five for failed logons, in the last hour. Each event carries its data as a list of properties, and for this event the source address is one of them. Group object then counts by address, and sorting by count gives the same ranked list that sort and uniq produced on Linux.
$f = @{ LogName = "Security"
Id = 4625
StartTime = (Get-Date).AddHours(-1) }
Get-WinEvent -FilterHashtable $f |
ForEach-Object {
$_.Properties[19].Value } |
Group-Object | Sort-Object Count -Desc
# Properties[19] = source address
# (run as administrator) Who has power here
Next question: who has power on this machine? Get local group member lists the local administrators, and there should be very few. Get local user shows enabled accounts and when each last logged on, which finds forgotten accounts. Then check the events from the Windows logging episode: four seven two zero for a new account and four seven three two for someone added to a local group. An unexpected new administrator is one of the clearest signs of compromise.
Get-LocalGroupMember Administrators
Get-LocalUser | Where-Object Enabled
| Select-Object Name, LastLogon
# new account or admin today?
Get-WinEvent -FilterHashtable @{
LogName="Security"; Id=4720,4732 }
# 4720 user created
# 4732 added to a local group Persistence
An attacker who wants to return arranges for something to start automatically. PowerShell lets you list every place that can happen. Scheduled tasks. Services, with the account each runs as and the program it launches; look for odd paths in temporary folders. The registry run keys. And the startup commands. You are looking for the entry that does not belong: a random name, a path in a user's profile, a task created last night. Baseline a clean machine so you know what normal looks like.
Get-ScheduledTask | Where-Object {
$_.State -ne "Disabled" } |
Select-Object TaskName, TaskPath
Get-CimInstance Win32_Service |
Select-Object Name, StartName, PathName
Get-ItemProperty `
HKLM:\...\CurrentVersion\Run
Get-CimInstance `
Win32_StartupCommand Processes and network
Then the live state. Get net TCP connection shows what is listening and which established connections exist, each with the number of the process that owns it. Get process turns that number into a name, a path on disk and a start time. And get file hash gives the SHA two fifty six of that program, which you can look up in a malware database. Listening port, to process, to file, to hash: four commands that take you from something strange on the network to a verdict.
Get-NetTCPConnection -State Listen |
Select-Object LocalPort, OwningProcess
Get-NetTCPConnection -State Established
| Select-Object RemoteAddress,
RemotePort, OwningProcess
Get-Process -Id 4242 |
Select-Object Name, Path, StartTime
Get-FileHash C:\path\file.exe
-Algorithm SHA256 Active Directory
With the Active Directory module the same style answers questions about the whole company. Who is in domain admins? Which accounts have not logged in for ninety days and should be disabled? Which passwords never expire? Which user accounts have a service principal name, making them targets for the Kerberoasting attack you will meet in Part seven? These four queries are a quick directory health check, and running them monthly finds the weak accounts before an attacker does.
Get-ADGroupMember "Domain Admins" # accounts unused for 90 days Search-ADAccount -AccountInactive ` -TimeSpan 90.00:00:00 -UsersOnly # passwords that never expire Get-ADUser -Filter ` "PasswordNeverExpires -eq `$true" # accounts with an SPN Get-ADUser -LDAPFilter ` "(servicePrincipalName=*)"
Why attackers love it
Now the other direction. Attackers love PowerShell for the same reasons administrators do. It is already on every Windows machine, so there is nothing to install. It is signed by Microsoft, so it looks legitimate. It can download code and run it in memory without writing a file. And it reaches everything. The tell-tale signs in a command line are an encoded command, a hidden window, and a one-liner that downloads something and immediately runs it.
- already on every Windows machine: nothing to install
- signed by Microsoft, so it looks legitimate
- can download and run code in memory, leaving no file
- reaches everything: registry, AD, WMI, remote machines
- signs: -EncodedCommand, -WindowStyle Hidden, download-and-run one-liners
Taming it
You cannot remove PowerShell from Windows, but you can make it visible and limited. Script block logging, event four one zero four, records the actual code that ran, after any encoding is undone. Transcription keeps a full record of sessions. AMSI lets antivirus inspect scripts as they execute, even ones that exist only in memory. Constrained language mode, with application control, blocks the dangerous features for ordinary users. And remove the old version two engine, which has none of these protections.
- script block logging (4104): records the code that ran, after decoding
- transcription: a full record
- AMSI: antivirus sees scripts as they run, even in memory
- constrained language mode with application control
- remove PowerShell v2
- JEA: limited admin endpoints
One myth
One myth to clear up. PowerShell has an execution policy, with settings like restricted and remote signed, and many people believe it stops malicious scripts. It does not. It prevents accidents, such as someone double-clicking a script. Anyone can bypass it with a single command-line switch, and Microsoft states plainly that it is not a security boundary. The real controls are the ones on the previous slide: logging, AMSI and application control.
- Restricted / RemoteSigned / AllSigned ...
- it stops accidents: double- clicking a script
- it does not stop attackers: one switch bypasses it (-ExecutionPolicy Bypass)
- Microsoft says so itself
- rely on logging, AMSI and application control instead
Writing your own
When you write your own scripts, the hygiene is the same as for Bash and Python. Turn on strict mode and make errors stop the script, instead of carrying on. Keep secrets out of the file and fetch them from a vault. Support the what if switch, PowerShell's built-in dry run, for anything that changes the system. Sign the scripts you deploy. And run them as the least privileged account that works, not as a domain administrator out of habit.
Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" # no secrets in the script: # use SecretManagement or a vault # support -WhatIf for changes: [CmdletBinding(SupportsShouldProcess)] # sign scripts you deploy # run as the least-privileged # account that works
Common mistakes
Mistakes. No script block logging, so the most used attack tool on Windows leaves no record. Trusting the execution policy as protection. The old version two engine still installed. Administrative scripts with passwords written inside them. Everyone a local administrator, so any PowerShell a user is tricked into running can do anything. Parsing output as text instead of using properties. And never recording what a clean machine looks like, so nothing stands out later.
- no script block logging
- trusting the execution policy
- PowerShell v2 still installed
- admin scripts with passwords inside
- everyone a local admin, so PowerShell can do anything
- parsing output as text instead of using properties
- never baselining a clean machine
Say it like this
In the interview: attackers use PowerShell as a living-off-the-land tool because it is preinstalled, signed by Microsoft and able to download and run code in memory. I defend by enabling script block logging and transcription and forwarding them centrally, relying on AMSI, using constrained language mode with application control, removing the version two engine and local admin rights, and alerting on encoded commands, hidden windows and download-and-run patterns. The execution policy is not a control.
- "It is a living-off-the-land
- tool: preinstalled, signed, able to run code in memory.
- I enable script block logging
- and transcription, rely on AMSI, use constrained language
- mode with application control, remove v2 and local admin, and alert on encoded or download-and-run commands."