SECURITY ENGINEERING · PART 3 · SCRIPTING AND AUTOMATION · POWERSHELL · 43 OF 229

PowerShell for Security: Logs, AD and Detection

PowerShell is how Windows is administered, investigated and attacked, so defenders must read and write it: objects instead of text, querying event logs with Get-WinEvent, checking local admins, services, scheduled tasks and network connections, hashing files, auditing Active Directory, why attackers love it, and the controls (script block logging, AMSI, constrained language mode) that tame it.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 9
  9. 10
  10. 11
  11. 12
  12. 13
  13. 14
  14. 15
  15. 16
  16. 17
  17. 18
  18. 19
  19. 20
  20. 21
  21. 22
  22. 23
  23. 24
  24. 25
  25. 26
  26. 27
  27. 28
  28. 29
  29. 30
  30. 31
  31. 32
  32. 33
  33. 34
  34. 35
  35. 36
  36. 37
  37. 38
  38. 39
  39. 40
  40. 41
  41. 42
  42. 43
  43. 44
  44. 45
  45. 46
  46. 47
  47. 48
  48. 49
  49. 50
  50. 51
  51. 52
  52. 53
  53. 54
  54. 55
  55. 56
  56. 57
  57. 58
  58. 59
  59. 60
  60. 61
  61. 62
  62. 63
  63. 64
  64. 106
  65. 107
  66. 108
  67. 109
  68. 110
  69. 111
  70. 112
  71. 113
  72. 114
  73. 115
  74. 116
  75. 117
  76. 118
  77. 119
  78. 120
  79. 121
  80. 122
  81. 123
  82. 124
  83. 125
  84. 126
  85. 127
  86. 128
  87. 129
  88. 130
  89. 131
  90. 132
  91. 133
  92. 134
  93. 135
  94. 136
  95. 137
  96. 138
  97. 139
  98. 140
  99. 141
  100. 142
  101. 143
  102. 144
1 / 14

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Objects, not text
  • Get-WinEvent for logs
  • admins, tasks, services, connections
  • AD checks
  • log it with 4104, limit it

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.

The pipeline carries objects
# 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.

failed logons in the last hour
$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.

accounts and privilege
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.

what starts by itself
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.

live state
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.

AD hygiene checks (RSAT module)
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.

Living off the land
  • 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.

Controls that work
  • 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.

Execution policy
  • 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.

Safe PowerShell scripts
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.

Avoid these
  • 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.

In the interview
  • "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."

Interview questions

Q1How is PowerShell different from Bash?

PowerShell pipelines pass structured objects with named properties instead of text, so filtering, sorting and selection are done by property (Where-Object, Sort-Object, Select-Object) rather than by parsing strings. Commands follow a Verb-Noun naming scheme.

Q2How do you query Windows event logs with PowerShell?

With Get-WinEvent and a -FilterHashtable specifying the log name, event IDs and time range, for example the Security log with Id 4625 for failed logons. The events can then be grouped and sorted, for instance by source address.

Q3Which PowerShell commands help find persistence on a Windows host?

Get-ScheduledTask for scheduled tasks, Get-CimInstance Win32_Service for services and their paths and accounts, Get-ItemProperty on the registry Run keys, and Win32_StartupCommand, compared against a known-good baseline.

Q4Why do attackers favour PowerShell?

It is installed on every Windows system, signed by Microsoft, can download and execute code in memory without touching disk, and has access to the registry, WMI, Active Directory and remote systems, which makes it ideal for living-off-the-land attacks.

Q5What is script block logging?

A PowerShell logging feature that records the content of executed script blocks as event ID 4104, after de-obfuscation, so defenders can see the actual code that ran even if it was encoded or downloaded into memory.

Q6Is the PowerShell execution policy a security control?

No. It is a safety feature to prevent accidental script execution and can be bypassed with a command-line switch or by other trivial means. Microsoft documents that it is not a security boundary.

Q7What is AMSI?

The Antimalware Scan Interface lets antivirus products inspect script content at execution time, including code that exists only in memory or has been de-obfuscated, so malicious PowerShell can be blocked even without a file on disk.

Q8What is constrained language mode?

A PowerShell mode that restricts access to sensitive language features such as arbitrary .NET types and COM objects. Enforced through application control policies for standard users, it blocks many attack techniques while allowing ordinary scripts.