Communitygithub.com

Cobalt Strike Beacon-Konfiguration analysieren

Extrahiere und analysiere die Konfiguration von Cobalt Strike Beacons aus PE-Dateien, Shellcode oder Speicherauszügen.

Was ist Cobalt Strike Beacon-Konfiguration analysieren?

Dieses Skill ermöglicht die Extraktion und Analyse der eingebetteten Konfiguration von Cobalt Strike Beacons, die in PE-Dateien, Shellcode oder Speicherauszügen gefunden werden. Es ist für Incident Responder und SOC-Analysten unerlässlich, um die Infrastruktur von Angreifern zu kartieren und Kampagnen zuzuordnen. Das Skill unterstützt die Arbeit mit Python-Bibliotheken wie `pefile`, `yara-python` und `dissect.cobaltstrike` sowie den SentinelOne CobaltStrikeParser. Es führt Schritt für Schritt durch die Extraktion von C2-Servern, Kommunikationsprotokollen, Malleable C2-Profilen, Wasserzeichen und anderen Indikatoren, und bietet zusätzlich YARA-Regeln zur Erkennung und Netzwerksignaturen zur Korrelation des Verkehrs.

Funktioniert mit~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/mukul975/Anthropic-Cybersecurity-Skills/tree/main/skills/analyzing-cobalt-strike-beacon-configuration

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Analyse der Cobalt Strike Beacon-Konfiguration

Überblick

Cobalt Strike ist ein kommerzielles Adversary-Simulationstool, das von Bedrohungsakteuren häufig für Post-Exploitation-Aktivitäten missbraucht wird. Beacon-Payloads enthalten eingebettete Konfigurationsdaten, die C2-Server-Adressen, Kommunikationsprotokolle, Schlafintervalle, Jitter-Werte, Malleable C2-Profil-Einstellungen, Wasserzeichen-Identifikatoren und Verschlüsselungsschlüssel preisgeben. Die Extraktion dieser Konfiguration aus PE-Dateien, Shellcode oder Speicherauszügen ist für Incident Responder von entscheidender Bedeutung, um die Angreiferinfrastruktur zu kartieren und Kampagnen zuzuordnen. Die Beacon-Konfiguration ist XOR-kodiert mit einem einzigen Byte (0x69 für Version 3, 0x2e für Version 4) und im TLV-Format (Type-Length-Value) im .data-Abschnitt gespeichert.

Verwendungszweck

  • Bei der Untersuchung von Sicherheitsvorfällen, die die Analyse der Cobalt Strike Beacon-Konfiguration erfordern.
  • Beim Erstellen von Erkennungsregeln oder Bedrohungsjagd-Abfragen für diesen Bereich.
  • Wenn SOC-Analysten strukturierte Verfahren für diese Art der Analyse benötigen.
  • Bei der Validierung der Sicherheitsüberwachungsabdeckung für verwandte Angriffstechniken.

Voraussetzungen

  • Python 3.9+ mit dissect.cobaltstrike, pefile, yara-python.
  • SentinelOne CobaltStrikeParser (parse_beacon_config.py).
  • Hex-Editor (010 Editor, HxD) für manuelle Inspektion.
  • Verständnis des PE-Dateiformats und der XOR-Kodierung.
  • Werkzeuge zur Erfassung von Speicherauszügen (Volatility3, WinDbg).
  • Netzwerkanalysetools (Wireshark) zur Korrelation von C2-Verkehr.

Schlüsselkonzepte

Beacon-Konfigurationsstruktur

Cobalt Strike Beacons speichern ihre Konfiguration als eine Ansammlung von TLV-Einträgen (Type-Length-Value) im .data-Abschnitt der PE-Datei. Stageless Beacons XOR-kodieren den gesamten Beacon-Code mit einem 4-Byte-Schlüssel. Der Konfigurationsblob selbst verwendet einen Einzelbyte-XOR-Schlüssel. Jeder TLV-Eintrag enthält eine 2-Byte-Typkennung (z. B. 0x0001 für BeaconType, 0x0008 für C2Server), eine 2-Byte-Länge und Daten variabler Länge.

Malleable C2-Profile

Die Beacon-Konfiguration kodiert das Malleable C2-Profil, das die HTTP-Anfrage-/Antworttransformationen vorgibt, einschließlich URI-Pfaden, Headern, Metadatenkodierung (Base64, NetBIOS) und Datentransformationen. Die Analyse dieser Einstellungen zeigt, wie der Beacon seinen Verkehr tarnt, um sich in legitimen Webverkehr einzufügen.

Wasserzeichen- und Lizenzidentifikation

Jede Cobalt Strike-Lizenz bettet ein eindeutiges Wasserzeichen (4-Byte-Ganzzahl) in generierte Beacons ein. Die Extraktion des Wasserzeichens kann mehrere Beacons mit demselben Betreiber oder einer geknackten Lizenz verknüpfen. Bekannte Wasserzeichendatenbanken, die von Threat-Intelligence-Anbietern gepflegt werden, ordnen Wasserzeichen bestimmten Bedrohungsakteuren oder geleakten Lizenzschlüsseln zu.

Arbeitsablauf

Schritt 1: Konfiguration mit CobaltStrikeParser extrahieren

#!/usr/bin/env python3
"""Extract Cobalt Strike beacon config from PE or memory dump."""
import sys
import json

# Using SentinelOne's CobaltStrikeParser
# pip install dissect.cobaltstrike
from dissect.cobaltstrike.beacon import BeaconConfig

def extract_beacon_config(filepath):
    """Parse beacon configuration from file."""
    configs = list(BeaconConfig.from_path(filepath))

    if not configs:
        print(f"[-] No beacon configuration found in {filepath}")
        return None

    for i, config in enumerate(configs):
        print(f"\n[+] Beacon Configuration #{i+1}")
        print(f"{'='*60}")

        settings = config.as_dict()

        # Critical fields for incident response
        critical_fields = [
            "SETTING_C2_REQUEST",
            "SETTING_C2_RECOVER",
            "SETTING_PUBKEY",
            "SETTING_DOMAINS",
            "SETTING_BEACONTYPE",
            "SETTING_PORT",
            "SETTING_SLEEPTIME",
            "SETTING_JITTER",
            "SETTING_MAXGET",
            "SETTING_SPAWNTO_X86",
            "SETTING_SPAWNTO_X64",
            "SETTING_PIPENAME",
            "SETTING_WATERMARK",
            "SETTING_C2_VERB_GET",
            "SETTING_C2_VERB_POST",
            "SETTING_USERAGENT",
            "SETTING_PROTOCOL",
        ]

        for field in critical_fields:
            value = settings.get(field, "N/A")
            print(f"  {field}: {value}")

        return settings

    return None


def extract_c2_indicators(config):
    """Extract actionable C2 indicators from beacon config."""
    indicators = {
        "c2_domains": [],
        "c2_ips": [],
        "c2_urls": [],
        "user_agent": "",
        "named_pipes": [],
        "spawn_processes": [],
        "watermark": "",
    }

    if not config:
        return indicators

    # Extract C2 domains
    domains = config.get("SETTING_DOMAINS", "")
    if domains:
        for domain in str(domains).split(","):
            domain = domain.strip().rstrip("/")
            if domain:
                indicators["c2_domains"].append(domain)

    # Extract user agent
    indicators["user_agent"] = str(config.get("SETTING_USERAGENT", ""))

    # Extract named pipes
    pipe = config.get("SETTING_PIPENAME", "")
    if pipe:
        indicators["named_pipes"].append(str(pipe))

    # Extract spawn-to processes
    for arch in ["SETTING_SPAWNTO_X86", "SETTING_SPAWNTO_X64"]:
        proc = config.get(arch, "")
        if proc:
            indicators["spawn_processes"].append(str(proc))

    # Extract watermark
    indicators["watermark"] = str(config.get("SETTING_WATERMARK", ""))

    return indicators


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(f"Usage: {sys.argv[0]} <beacon_file_or_dump>")
        sys.exit(1)

    config = extract_beacon_config(sys.argv[1])
    if config:
        indicators = extract_c2_indicators(config)
        print(f"\n[+] Extracted C2 Indicators:")
        print(json.dumps(indicators, indent=2))

Schritt 2: Manuelle XOR-Entschlüsselung der Beacon-Konfiguration

import struct

def find_and_decrypt_config(data):
    """Manually locate and decrypt beacon configuration."""
    # Cobalt Strike 4.x uses 0x2e as XOR key
    xor_keys = [0x2e, 0x69]  # v4, v3

    for xor_key in xor_keys:
        # Search for the config magic bytes after XOR
        # Config starts with 0x0001 (BeaconType) XOR'd with key
        magic = bytes([0x00 ^ xor_key, 0x01 ^ xor_key,
                       0x00 ^ xor_key, 0x02 ^ xor_key])

        offset = data.find(magic)
        if offset == -1:
            continue

        print(f"[+] Found config at offset 0x{offset:x} (XOR key: 0x{xor_key:02x})")

        # Decrypt the config blob (typically 4096 bytes)
        config_size = 4096
        encrypted = data[offset:offset + config_size]
        decrypted = bytes([b ^ xor_key for b in encrypted])

        # Parse TLV entries
        entries = parse_tlv(decrypted)
        return entries

    return None


def parse_tlv(data):
    """Parse Type-Length-Value configuration entries."""
    entries = {}
    offset = 0

    # TLV field type mapping
    field_names = {
        0x0001: "BeaconType",
        0x0002: "Port",
        0x0003: "SleepTime",
        0x0004: "MaxGetSize",
        0x0005: "Jitter",
        0x0006: "MaxDNS",
        0x0007: "Deprecated_PublicKey",
        0x0008: "C2Server",
        0x0009: "UserAgent",
        0x000a: "PostURI",
        0x000b: "Malleable_C2_Instructions",
        0x000c: "Deprecated_HttpGet_Metadata",
        0x000d: "SpawnTo_x86",
        0x000e: "SpawnTo_x64",
        0x000f: "CryptoScheme",
        0x001a: "Watermark",
        0x001d: "C2_HostHeader",
        0x0024: "PipeName",
        0x0025: "Year",
        0x0026: "Month",
        0x0027: "Day",
        0x0036: "ProxyHostname",
    }

    while offset + 6 <= len(data):
        entry_type = struct.unpack(">H", data[offset:offset+2])[0]
        entry_len_type = struct.unpack(">H", data[offset+2:offset+4])[0]
        entry_len = struct.unpack(">H", data[offset+4:offset+6])[0]

        if entry_type == 0:
            break

        value_start = offset + 6
        value_end = value_start + entry_len
        value_data = data[value_start:value_end]

        field_name = field_names.get(entry_type, f"Unknown_0x{entry_type:04x}")

        if entry_len_type == 1:  # Short
            value = struct.unpack(">H", value_data[:2])[0]
        elif entry_len_type == 2:  # Int
            value = struct.unpack(">I", value_data[:4])[0]
        elif entry_len_type == 3:  # String/Blob
            value = value_data.rstrip(b'\x00').decode('utf-8', errors='replace')
        else:
            value = value_data.hex()

        entries[field_name] = value
        print(f"  {field_name}: {value}")

        offset = value_end

    return entries

Schritt 3: YARA-Regel zur Beacon-Erkennung

import yara

cobalt_strike_rule = """
rule CobaltStrike_Beacon_Config {
    meta:
        description = "Detects Cobalt Strike beacon configuration"
        author = "Malware Analysis Team"
        date = "2025-01-01"

    strings:
        // XOR'd config marker for CS 4.x (key 0x2e)
        $config_v4 = { 2e 2f 2e 2c }

        // XOR'd config marker for CS 3.x (key 0x69)
        $config_v3 = { 69 68 69 6b }

        // Common beacon strings
        $str_pipe = "\\\\\\.\\\\pipe\\\\" ascii wide
        $str_beacon = "beacon" ascii nocase
        $str_sleeptime = "sleeptime" ascii nocase

        // Reflective loader pattern
        $reflective = { 4D 5A 41 52 55 48 89 E5 }

    condition:
        ($config_v4 or $config_v3) or
        (2 of ($str_*) and $reflective)
}
"""

def scan_for_beacons(filepath):
    """Scan file with YARA rules for Cobalt Strike beacons."""
    rules = yara.compile(source=cobalt_strike_rule)
    matches = rules.match(filepath)

    for match in matches:
        print(f"[+] YARA Match: {match.rule}")
        for string_match in match.strings:
            offset = string_match.instances[0].offset
            print(f"    String: {string_match.identifier} at offset 0x{offset:x}")

    return matches

Schritt 4: Korrelation von Netzwerkverkehr

from dissect.cobaltstrike.c2 import HttpC2Config

def analyze_c2_profile(beacon_config):
    """Analyze malleable C2 profile from beacon configuration."""
    print("\n[+] Malleable C2 Profile Analysis")
    print("=" * 60)

    # HTTP GET configuration
    get_verb = beacon_config.get("SETTING_C2_VERB_GET", "GET")
    get_uri = beacon_config.get("SETTING_C2_REQUEST", "")
    print(f"\n  HTTP GET Request:")
    print(f"    Verb: {get_verb}")
    print(f"    URI: {get_uri}")

    # HTTP POST configuration
    post_verb = beacon_config.get("SETTING_C2_VERB_POST", "POST")
    post_uri = beacon_config.get("SETTING_C2_POSTREQ", "")
    print(f"\n  HTTP POST Request:")
    print(f"    Verb: {post_verb}")
    print(f"    URI: {post_uri}")

    # User Agent
    ua = beacon_config.get("SETTING_USERAGENT", "")
    print(f"\n  User-Agent: {ua}")

    # Host header
    host = beacon_config.get("SETTING_C2_HOSTHEADER", "")
    print(f"  Host Header: {host}")

    # Sleep and jitter for traffic pattern
    sleep_ms = beacon_config.get("SETTING_SLEEPTIME", 60000)
    jitter = beacon_config.get("SETTING_JITTER", 0)
    print(f"\n  Sleep Time: {sleep_ms}ms")
    print(f"  Jitter: {jitter}%")

    # Generate Suricata/Snort signatures
    print(f"\n[+] Suggested Network Signatures:")
    if ua:
        print(f'  alert http any any -> any any (msg:"CS Beacon UA"; '
              f'content:"{ua}"; http_user_agent; sid:1000001; rev:1;)')
    if get_uri:
        print(f'  alert http any any -> any any (msg:"CS Beacon URI"; '
              f'content:"{get_uri}"; http_uri; sid:1000002; rev:1;)')

Validierungskriterien

  • Beacon-Konfiguration erfolgreich aus PE-Datei oder Speicherauszug extrahiert.
  • C2-Server-Domains/IPs korrekt mit Port und Protokoll identifiziert.
  • Malleable C2-Profil-Parameter dekodiert, die HTTP-Transformationen anzeigen.
  • Wasserzeichenwert für die Zuordnungskorrelation extrahiert.
  • Schlafzeit- und Jitter-Werte stimmen mit beobachteten Netzwerk-Beacon-Intervallen überein.
  • YARA-Regeln erkennen Beacon in gepackten und ungepackten Proben.
  • Aus dem extrahierten C2-Profil generierte Netzwerksignaturen.

Referenzen

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

abusing-dpapi-for-credential-access

Extract and decrypt Windows DPAPI-protected secrets (Credential Manager, browser logins/cookies, Wi-Fi credentials, KeePass keys) online or offline using SharpDPAPI, SharpChrome, Mimikatz, or Impacket

abusing-shadow-credentials-for-privesc

Take over Active Directory accounts by writing attacker-controlled public keys to msDS-KeyCredentialLink (Shadow Credentials) with pyWhisker, Whisker, or Certipy, then authenticate via PKINIT to recover the target

achieving-cmmc-level-2-compliance

>-

acquiring-disk-image-with-dd-and-dcfldd

Create forensically sound bit-for-bit disk images with dd or dcfldd on a Linux forensic workstation, preserving evidence integrity through hash verification (MD5/SHA) during acquisition. Use when imaging a suspect drive, USB device, or memory card for investigation, preserving volatile disk evidence during incident response, or producing a verified copy for legal or law-enforcement proceedings before any destructive analysis.

analyzing-active-directory-acl-abuse

Detect dangerous ACL misconfigurations in Active Directory using ldap3

analyzing-android-malware-with-apktool

Perform static analysis of Android APK malware using apktool for resource decompilation, jadx for Java source recovery, and androguard for manifest inspection, dangerous permission-combination detection, and identification of obfuscated code, dynamic code loading, and reflection-based API calls. Use to statically triage a suspicious APK without executing it or to build mobile malware detection rules.

analyzing-api-gateway-access-logs

Parses API Gateway access logs (AWS API Gateway, Kong, Nginx) to detect

analyzing-apt-group-with-mitre-navigator

Query ATT&CK data with attackcti, mitreattack-python, and stix2, then build MITRE ATT&CK Navigator layers and multi-layer heatmap overlays mapping one or more APT groups

analyzing-azure-activity-logs-for-threats

Queries Azure Monitor activity logs and sign-in logs via azure-monitor-query

analyzing-bootkit-and-rootkit-samples

Analyzes bootkit and advanced rootkit malware infecting the Master

analyzing-browser-forensics-with-hindsight

Parse Chromium-based browser databases with Hindsight to extract and correlate browsing history, downloads, cookies, cached content, autofill data, saved passwords, and extensions from Chrome, Edge, Brave, Opera, and Vivaldi into a unified timeline (XLSX, JSON, or SQLite output). Use during incident response, insider-threat investigations, or criminal cases when you need to reconstruct a user

analyzing-campaign-attribution-evidence

Systematically evaluate cyber-campaign evidence to attribute an operation to a threat actor, using the Diamond Model and Analysis of Competing Hypotheses (ACH) to weigh infrastructure overlaps, TTP consistency, malware code similarity, and timing/language artifacts into confidence-weighted attribution assessments. Use when an incident investigation needs a defensible attribution confidence level.

analyzing-certificate-transparency-for-phishing

Monitor Certificate Transparency logs using crt.sh and Certstream to

analyzing-cloud-storage-access-patterns

Detect abnormal access in AWS S3, GCS, and Azure Blob Storage by analyzing CloudTrail Data Events, GCS audit logs, and Azure Storage Analytics for after-hours bulk downloads, new-IP access, and API-call spikes (e.g. GetObject) via statistical baselines and time-series anomaly detection. Use when investigating suspected cloud data exfiltration or building related detection rules.

analyzing-cobaltstrike-malleable-c2-profiles

Parse and analyze Cobalt Strike Malleable C2 profiles with dissect.cobaltstrike (profiles and beacon-payload configs) and pyMalleableC2 (AST parsing) to extract HTTP/DNS transforms, URIs, headers, sleep/jitter, and injection behavior, then generate network detection signatures. Use when reverse-engineering a captured malleable profile or building detections against Cobalt Strike Beacon traffic.

analyzing-command-and-control-communication

Analyzes malware C2 communication over HTTP, HTTPS, DNS, and custom

analyzing-cyber-kill-chain

Analyzes intrusion activity against the Lockheed Martin Cyber Kill Chain

analyzing-disk-image-with-autopsy

Perform comprehensive forensic analysis of raw (dd), E01, or AFF disk images with Autopsy and The Sleuth Kit, recovering deleted files, examining metadata and embedded artifacts, keyword searching, and building investigation timelines with visual reports. Use for structured analysis of a forensic disk image or when stakeholders need visual reports from evidence.

analyzing-dns-logs-for-exfiltration

Analyzes DNS query logs to detect data exfiltration via DNS tunneling,

analyzing-docker-container-forensics

Investigate compromised Docker containers by analyzing images, layers,

Verwandte Skills