endpoint security

Implementing Memory Protection with DEP and ASLR

Implements memory protection mechanisms including DEP (Data Execution Prevention), ASLR (Address Space Layout Randomization), CFG (Control Flow Guard), and other exploit mitigations to prevent memory corruption attacks. Use when hardening endpoints against buffer overflow exploits, ROP chains, and code injection. Activates for requests involving memory protection, exploit mitigation, DEP, ASLR, or CFG configuration.

aslrcfgdependpointexploit-mitigationmemory-protection
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

When to Use

Use this skill when hardening endpoints against memory-based exploits by configuring DEP, ASLR, CFG, and Windows Exploit Protection system-wide and per-application mitigations.

Prerequisites

  • Windows 10/11 or Windows Server 2016+ with administrative privileges
  • Group Policy management access for enterprise-wide deployment
  • Understanding of memory corruption attack techniques (buffer overflow, ROP chains)
  • Test environment for validating application compatibility with exploit mitigations

Workflow

Step 1: Configure System-Level Mitigations

# Enable system-wide DEP (Data Execution Prevention)
# Boot configuration: OptIn (default), OptOut (recommended), AlwaysOn
bcdedit /set nx AlwaysOn
 
# Verify ASLR status (enabled by default on modern Windows)
Get-ProcessMitigation -System
# MandatoryASLR, BottomUpASLR, HighEntropyASLR should be ON
 
# Enable all system-level mitigations
Set-ProcessMitigation -System -Enable DEP,SEHOP,ForceRelocateImages,BottomUp,HighEntropy

Step 2: Configure Per-Application Mitigations

# Harden high-risk applications (browsers, Office, PDF readers)
Set-ProcessMitigation -Name "WINWORD.EXE" -Enable DEP,SEHOP,ForceRelocateImages,CFG,StrictHandle
Set-ProcessMitigation -Name "EXCEL.EXE" -Enable DEP,SEHOP,ForceRelocateImages,CFG,StrictHandle
Set-ProcessMitigation -Name "AcroRd32.exe" -Enable DEP,SEHOP,ForceRelocateImages,CFG
Set-ProcessMitigation -Name "chrome.exe" -Enable DEP,CFG,ForceRelocateImages
Set-ProcessMitigation -Name "msedge.exe" -Enable DEP,CFG,ForceRelocateImages
 
# Export configuration for deployment
Get-ProcessMitigation -RegistryConfigFilePath "C:\exploit_protection.xml"
# Deploy via Intune or GPO

Step 3: Deploy via Intune/GPO

Intune: Endpoint Security → Attack Surface Reduction → Exploit Protection
  Import exploit_protection.xml template
 
GPO: Computer Configuration → Admin Templates → Windows Components
  → Windows Defender Exploit Guard → Exploit Protection
  → "Use a common set of exploit protection settings" → Enabled
  → Point to XML file on network share

Key Concepts

Term Definition
DEP Marks memory pages as non-executable to prevent shellcode execution in data regions
ASLR Randomizes memory addresses of loaded modules to defeat hardcoded ROP gadgets
CFG Validates indirect call targets at runtime to prevent control flow hijacking
SEHOP Validates SEH chain integrity to prevent SEH-based exploitation

Tools & Systems

  • Windows Exploit Protection: Built-in per-process mitigation management
  • EMET (legacy): Enhanced Mitigation Experience Toolkit (predecessor, now deprecated)
  • ProcessMitigations PowerShell: Get/Set-ProcessMitigation cmdlets

Common Pitfalls

  • DEP compatibility: Legacy 32-bit applications may crash with DEP AlwaysOn. Use OptOut with exceptions.
  • Mandatory ASLR breaking apps: Some applications are not ASLR-compatible. Test before enforcing ForceRelocateImages.
  • CFG limited to compiled-in support: CFG only works for applications compiled with /guard:cf. Cannot be retroactively applied.
Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 3

api-reference.md1.8 KB

API Reference: Implementing Memory Protection with DEP and ASLR

Windows PowerShell Commands

# Check system-wide mitigations
Get-ProcessMitigation -System
# Check specific process
Get-ProcessMitigation -Name chrome.exe
# Set system-wide DEP
Set-ProcessMitigation -System -Enable DEP
# Import XML policy
Set-ProcessMitigation -PolicyFilePath policy.xml
# Export current policy
Get-ProcessMitigation -RegistryConfigFilePath export.xml

Memory Protection Mechanisms

Mechanism OS Description
DEP/NX Windows/Linux Prevent code execution from data pages
ASLR Windows/Linux Randomize memory layout
CFG Windows Control Flow Guard
SEHOP Windows SEH Overwrite Protection
Stack Canary Linux Detect stack buffer overflow
PIE Linux Position-Independent Executable
RELRO Linux Read-Only Relocations
FORTIFY_SOURCE Linux Buffer overflow checks

Linux ASLR Check

# Check ASLR level (0=off, 1=conservative, 2=full)
cat /proc/sys/kernel/randomize_va_space
# Enable full ASLR
echo 2 > /proc/sys/kernel/randomize_va_space

ELF Binary Check (checksec)

checksec --file=/usr/bin/target
# Or with readelf
readelf -l binary | grep GNU_STACK
readelf -d binary | grep BIND_NOW

GCC Compilation Flags

Flag Protection
-fstack-protector-strong Stack canary
-D_FORTIFY_SOURCE=2 Buffer overflow checks
-pie -fPIE Position-independent
-Wl,-z,relro,-z,now Full RELRO
-Wl,-z,noexecstack NX stack

References

standards.md0.3 KB

Standards & References

workflows.md0.4 KB

Workflows

Memory Protection Deployment

[Audit current mitigations: Get-ProcessMitigation -System]
  → [Enable system-level DEP, SEHOP, ASLR]
  → [Configure per-app mitigations for high-risk applications]
  → [Export XML, deploy via Intune/GPO]
  → [Test application compatibility] → [Monitor for crashes]
  → [Tune exceptions for incompatible apps]

Scripts 2

agent.py6.4 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""DEP/ASLR Memory Protection Agent - audits processes and binaries for memory protection mitigations."""

import json
import argparse
import logging
import subprocess
import os
from datetime import datetime

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)


def check_windows_dep_policy():
    """Check Windows DEP/NX policy via bcdedit."""
    cmd = ["bcdedit", "/enum", "{current}"]
    result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
    dep_policy = "unknown"
    for line in result.stdout.split("\n"):
        if "nx" in line.lower():
            dep_policy = line.split()[-1] if line.split() else "unknown"
    return {"dep_policy": dep_policy, "recommended": "AlwaysOn"}


def check_windows_process_mitigations():
    """Check process mitigation policies using PowerShell Get-ProcessMitigation."""
    cmd = ["powershell", "-Command",
           "Get-Process | ForEach-Object { try { $m = Get-ProcessMitigation -Id $_.Id -ErrorAction Stop; "
           "[PSCustomObject]@{Name=$_.Name;PID=$_.Id;DEP=$m.DEP.Enable;ASLR=$m.ASLR.ForceRelocateImages;"
           "CFG=$m.CFG.Enable;StrictHandle=$m.StrictHandle.Enable} } catch {} } | ConvertTo-Json"]
    result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
    try:
        processes = json.loads(result.stdout) if result.stdout else []
        if isinstance(processes, dict):
            processes = [processes]
        return processes
    except json.JSONDecodeError:
        return []


def check_linux_aslr():
    """Check Linux ASLR configuration."""
    try:
        with open("/proc/sys/kernel/randomize_va_space") as f:
            value = int(f.read().strip())
        levels = {0: "disabled", 1: "partial", 2: "full"}
        return {"aslr_level": value, "status": levels.get(value, "unknown"), "recommended": 2}
    except (FileNotFoundError, ValueError):
        return {"aslr_level": -1, "status": "unknown"}


def check_linux_nx_support():
    """Check NX bit support on Linux."""
    result = subprocess.run(["grep", "nx", "/proc/cpuinfo"], capture_output=True, text=True, timeout=120)
    return {"nx_supported": "nx" in result.stdout.lower()}


def check_elf_pie_relro(binary_path):
    """Check ELF binary for PIE, RELRO, stack canary, and NX using readelf/checksec."""
    findings = {"binary": binary_path, "pie": False, "relro": "none", "nx": False, "canary": False}
    readelf_cmd = subprocess.run(["readelf", "-h", binary_path], capture_output=True, text=True, timeout=120)
    if "DYN" in readelf_cmd.stdout:
        findings["pie"] = True
    readelf_d = subprocess.run(["readelf", "-d", binary_path], capture_output=True, text=True, timeout=120)
    if "BIND_NOW" in readelf_d.stdout:
        findings["relro"] = "full"
    elif "GNU_RELRO" in readelf_d.stdout:
        findings["relro"] = "partial"
    readelf_s = subprocess.run(["readelf", "-s", binary_path], capture_output=True, text=True, timeout=120)
    if "__stack_chk_fail" in readelf_s.stdout:
        findings["canary"] = True
    readelf_l = subprocess.run(["readelf", "-l", binary_path], capture_output=True, text=True, timeout=120)
    for line in readelf_l.stdout.split("\n"):
        if "GNU_STACK" in line and "RWE" not in line:
            findings["nx"] = True
    score = sum([findings["pie"], findings["relro"] == "full", findings["nx"], findings["canary"]])
    findings["protection_score"] = f"{score}/4"
    return findings


def scan_directory_binaries(directory, extensions=None):
    """Scan directory for binaries and check protections."""
    if extensions is None:
        extensions = [""]
    results = []
    for root, dirs, files in os.walk(directory):
        for fname in files:
            fpath = os.path.join(root, fname)
            if os.path.isfile(fpath) and os.access(fpath, os.X_OK):
                try:
                    result = check_elf_pie_relro(fpath)
                    results.append(result)
                except Exception:
                    continue
        if len(results) >= 100:
            break
    return results


def generate_report(system_checks, binary_checks):
    weak_binaries = [b for b in binary_checks if not b.get("pie") or b.get("relro") == "none"]
    report = {
        "timestamp": datetime.utcnow().isoformat(),
        "system_protections": system_checks,
        "binaries_scanned": len(binary_checks),
        "weak_binaries": len(weak_binaries),
        "protection_summary": {
            "pie_enabled": sum(1 for b in binary_checks if b.get("pie")),
            "full_relro": sum(1 for b in binary_checks if b.get("relro") == "full"),
            "nx_enabled": sum(1 for b in binary_checks if b.get("nx")),
            "canary_present": sum(1 for b in binary_checks if b.get("canary")),
        },
        "weak_binary_details": weak_binaries[:20],
    }
    return report


def main():
    parser = argparse.ArgumentParser(description="DEP/ASLR Memory Protection Audit Agent")
    parser.add_argument("--scan-dir", default="/usr/bin", help="Directory to scan binaries")
    parser.add_argument("--platform", choices=["linux", "windows", "auto"], default="auto")
    parser.add_argument("--output", default="memory_protection_report.json")
    args = parser.parse_args()

    platform = args.platform
    if platform == "auto":
        platform = "windows" if os.name == "nt" else "linux"

    system_checks = {}
    if platform == "linux":
        system_checks["aslr"] = check_linux_aslr()
        system_checks["nx"] = check_linux_nx_support()
        binary_checks = scan_directory_binaries(args.scan_dir)
    else:
        system_checks["dep"] = check_windows_dep_policy()
        process_mitigations = check_windows_process_mitigations()
        binary_checks = []
        for proc in process_mitigations:
            binary_checks.append({
                "binary": proc.get("Name", ""),
                "pid": proc.get("PID", 0),
                "pie": bool(proc.get("ASLR")),
                "nx": bool(proc.get("DEP")),
                "canary": False,
                "relro": "n/a",
            })

    report = generate_report(system_checks, binary_checks)
    with open(args.output, "w") as f:
        json.dump(report, f, indent=2, default=str)
    logger.info("Scanned %d binaries, %d with weak protections",
                report["binaries_scanned"], report["weak_binaries"])
    print(json.dumps(report, indent=2, default=str))


if __name__ == "__main__":
    main()
process.py1.1 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Memory Protection Auditor - Checks exploit mitigation status on Windows."""

import json, subprocess, sys, os
from datetime import datetime


def check_mitigations() -> dict:
    ps_cmd = """
    $sys = Get-ProcessMitigation -System
    $apps = Get-ProcessMitigation -Name * 2>$null | Select-Object -First 20
    @{System = $sys; Apps = $apps} | ConvertTo-Json -Depth 3
    """
    try:
        r = subprocess.run(["powershell", "-NoProfile", "-Command", ps_cmd],
                          capture_output=True, text=True, timeout=30)
        return json.loads(r.stdout) if r.returncode == 0 else {"error": r.stderr}
    except Exception as e:
        return {"error": str(e)}


if __name__ == "__main__":
    result = check_mitigations()
    if "error" in result:
        print(f"Error: {result['error']}")
        print("This tool requires Windows with Exploit Protection support.")
        sys.exit(1)
    out = sys.argv[1] if len(sys.argv) > 1 else "memory_protection_audit.json"
    with open(out, "w") as f:
        json.dump({"generated": datetime.utcnow().isoformat() + "Z", **result}, f, indent=2)
    print(f"Report: {out}")

Assets 1

template.mdtext/markdown · 0.5 KB
Keep exploring