<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: detecting-living-off-the-land-binaries
description: >-
  Detect and analyze abuse of legitimate system binaries (LOLBins) for malicious
  purposes including execution, download, persistence, and defense evasion.
domain: cybersecurity
subdomain: malware-analysis
tags:
  - lolbins
  - living-off-the-land
  - defense-evasion
  - execution
  - lolbas
  - gtfobins
  - malware-analysis
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1218"]
---

# Detecting Living-off-the-Land Binaries

## Overview

Living-off-the-Land Binaries (LOLBins) are legitimate, signed system binaries abused by attackers for malicious purposes — executing arbitrary code, downloading payloads, bypassing application whitelisting, and establishing persistence. Because these binaries are trusted by the OS and security tools, their abuse is difficult to detect without behavioral analysis. LOLBAS (Windows) and GTFOBins (Linux/Unix) projects catalogue known abuse vectors.

## Prerequisites

- Sysmon with comprehensive process creation logging
- PowerShell Script Block Logging and Module Logging
- EDR with command-line argument logging
- Sigma rules for LOLBin detection
- LOLBAS and GTFOBins reference databases
- YARA for detecting LOLBin invocation patterns in scripts

## Key Concepts

### LOLBin Abuse Categories

| Category | Purpose | Examples |
|----------|---------|---------|
| Execution | Run arbitrary code | `mshta`, `rundll32`, `regsvr32`, `certutil` |
| Download | Fetch remote payloads | `certutil`, `bitsadmin`, `curl`, `wget` |
| Bypass | Evade AppLocker/WDAC | `msbuild`, `installutil`, `cmstp` |
| Persistence | Maintain access | `schtasks`, `at`, `reg`, `sc` |
| Compilation | Compile on target | `csc.exe`, `msbuild.exe` |

### Windows LOLBins (Top 15)

| Binary | Abuse | MITRE ATT&CK |
|--------|-------|---------------|
| `certutil.exe` | Download + decode | T1140, T1105 |
| `mshta.exe` | Execute HTA/JS/VBS | T1218.005 |
| `rundll32.exe` | Execute DLL exports | T1218.011 |
| `regsvr32.exe` | Execute COM scriptlets | T1218.010 |
| `msbuild.exe` | Compile+execute inline | T1127.001 |
| `bitsadmin.exe` | Download files | T1197 |
| `wmic.exe` | Execute XSL scripts | T1218 |
| `cmstp.exe` | UAC bypass + execute | T1218.003 |
| `installutil.exe` | Execute .NET code | T1218.004 |
| `csc.exe` | Compile C# on target | T1127 |
| `powershell.exe` | Script execution | T1059.001 |
| `cmd.exe` | Command execution | T1059.003 |
| `schtasks.exe` | Scheduled persistence | T1053.005 |
| `wscript.exe` | Script execution | T1059.005 |
| `forfiles.exe` | Indirect execution | T1202 |

## Workflow

### Step 1: Detect LOLBin Execution via Sysmon

```bash
# Sysmon Event ID 1 — Process Creation with command-line logging
# Filter for known LOLBin abuse patterns

# certutil download abuse
grep -i "certutil" sysmon_events.json | \
    grep -iE "urlcache|split|decode|encode"

# mshta executing remote content
grep -i "mshta" sysmon_events.json | \
    grep -iE "http|https|javascript|vbscript"

# regsvr32 scriptlet execution
grep -i "regsvr32" sysmon_events.json | \
    grep -iE "/s /n /u /i:http|scrobj"

# rundll32 with suspicious arguments
grep -i "rundll32" sysmon_events.json | \
    grep -iE "javascript:|shell32|url.dll|advpack"

# bitsadmin file transfer
grep -i "bitsadmin" sysmon_events.json | \
    grep -iE "/transfer|/addfile|/resume"
```

### Step 2: Sigma Rules for LOLBin Detection

```yaml
title: Certutil Download and Decode Activity
id: e011b053-4859-4094-b799-4e2f5e9e6e1a
status: experimental
description: Detects certutil abuse for downloading or decoding files
logsource:
  category: process_creation
  product: windows
detection:
  selection:
    Image|endswith: '\certutil.exe'
    CommandLine|contains:
      - 'urlcache'
      - '-decode'
      - '-encode'
      - '-decodehex'
      - 'split'
  condition: selection
falsepositives:
  - Certificate management by IT administrators
level: high
tags:
  - attack.t1140
  - attack.t1105
  - attack.defense_evasion
```

### Step 3: Linux GTFOBins Detection

```bash
# Detect common GTFOBin abuse patterns

# Find with exec
grep -E "find.*-exec.*(sh|bash|nc|python)" /var/log/audit/audit.log

# Vim/Vi shell escape
grep -E "vim.*-c.*:!|vim.*-c.*system" /var/log/audit/audit.log

# Python reverse shells
grep -E "python.*socket.*connect|python.*subprocess" /var/log/audit/audit.log

# Curl/wget piped to shell
grep -E "(curl|wget).*\|\s*(sh|bash)" /var/log/audit/audit.log

# Tar checkpoint abuse
grep -E "tar.*--checkpoint-action" /var/log/audit/audit.log

# Nmap interactive mode
grep -E "nmap.*--interactive|nmap.*--script" /var/log/audit/audit.log
```

### Step 4: Build Detection Baselines

```python
#!/usr/bin/env python3
"""Build baseline of normal LOLBin usage for anomaly detection."""
import json
import re
from collections import Counter
from pathlib import Path

LOLBINS = [
    "certutil.exe", "mshta.exe", "rundll32.exe", "regsvr32.exe",
    "msbuild.exe", "bitsadmin.exe", "wmic.exe", "cmstp.exe",
    "installutil.exe", "csc.exe", "wscript.exe", "cscript.exe",
    "forfiles.exe", "pcalua.exe", "msiexec.exe",
]

def build_baseline(log_path: str) -> dict:
    """Parse Sysmon logs to build normal LOLBin usage baseline."""
    baseline: dict[str, Counter] = {b: Counter() for b in LOLBINS}
    log = Path(log_path)
    if not log.exists():
        return {"error": f"Log not found: {log_path}"}

    for line in log.read_text(errors="replace").split("\n"):
        for lolbin in LOLBINS:
            if lolbin.lower() in line.lower():
                args = re.findall(r'CommandLine["\s:]+([^\n"]+)', line)
                if args:
                    baseline[lolbin][args[0].strip()] += 1

    return {k: dict(v.most_common(10)) for k, v in baseline.items() if v}

result = build_baseline("/var/log/sysmon.json")
print(json.dumps(result, indent=2))
```

### Step 5: Hunt for Anomalous LOLBin Chains

```bash
# Process tree analysis — LOLBin spawning LOLBin
# Suspicious: Office → cmd → certutil → powershell
# Sysmon correlate ParentProcessId → ProcessId chains

python3 -c "
import json
# Load Sysmon process creation events
events = json.loads(open('sysmon_process.json').read())
lolbins = {'certutil', 'mshta', 'rundll32', 'regsvr32', 'msbuild', 'powershell', 'cmd'}
for e in events:
    parent = e.get('ParentImage', '').lower()
    child = e.get('Image', '').lower()
    parent_name = parent.split('\\\\')[-1].replace('.exe', '')
    child_name = child.split('\\\\')[-1].replace('.exe', '')
    if parent_name in lolbins and child_name in lolbins:
        print(f'⚠ Chain: {parent_name} → {child_name}: {e.get(\"CommandLine\", \"\")}')
"
```

## YARA Rule

```yara
rule LOLBin_Abuse_Script {
    meta:
        description = "Detects scripts invoking LOLBins for malicious purposes"
        author = "NERF"
        date = "2026-03-17"
        mitre_attack = "T1218"
        severity = "high"
    strings:
        $cert1 = "certutil" ascii nocase
        $cert2 = "urlcache" ascii nocase
        $mshta = "mshta" ascii nocase
        $regsvr = "regsvr32" ascii nocase
        $scrobj = "scrobj.dll" ascii nocase
        $bits = "bitsadmin" ascii nocase
        $transfer = "/transfer" ascii nocase
        $msbuild = "msbuild" ascii nocase
        $http = /https?:\/\/[^\s"']+/ ascii
    condition:
        filesize < 100KB and
        $http and
        (($cert1 and $cert2) or ($mshta and $http) or
         ($regsvr and $scrobj) or ($bits and $transfer))
}
```

## Verification

- [ ] LOLBin execution events collected with full command-line arguments
- [ ] Sigma detection rules deployed for top LOLBin abuse patterns
- [ ] Process chain analysis identifies multi-stage LOLBin abuse
- [ ] Baseline of normal LOLBin usage established
- [ ] GTFOBins monitoring configured for Linux environments
- [ ] Anomalous LOLBin usage investigated and triaged
- [ ] Findings mapped to MITRE ATT&CK (T1218, T1105, T1140, T1059)

## References

- [LOLBAS Project — Windows LOLBins](https://lolbas-project.github.io/)
- [GTFOBins — Unix LOLBins](https://gtfobins.github.io/)
- [MITRE ATT&CK T1218 — System Binary Proxy Execution](https://attack.mitre.org/techniques/T1218/)
- [Sigma Rules — LOLBin Detection](https://github.com/SigmaHQ/sigma)
