返回网格
SKILL / GITHUB

analyzing-cobalt-strike-beacon-configuration

公开中

Extract and analyze Cobalt Strike beacon configuration from PE files

效率 analyzing-cobalt-strike-beacon-configuration 8 FILES 4 VIEWS 2026-08-18 09:00 SOURCE
GrokClaude CodeCursorCodexCLI
安装

一键装到本地 agent

和 SkillsMP 一样,先看源码再安装。Grok 用分享链接;Claude / Cursor / Codex 下载 zip 解到技能目录。

META

NAMEanalyzing-cobalt-strike-beacon-configuration
SLUGanalyzing-cobalt-strike-beacon-configuration
SOURCEgithub
BYTES55182

AI 怎么用

  1. 复制上面的 AI URL
  2. 粘贴到 Claude / ChatGPT / Grok / Cursor
  3. 再说你要做什么,AI 会先读 skill 再动手

SKILL.MD

AGENT READABLE

name: analyzing-cobalt-strike-beacon-configuration
description: Extract and analyze Cobalt Strike beacon configuration from PE files
and memory dumps to identify C2 infrastructure, malleable profiles, and operator
tradecraft.
domain: cybersecurity
subdomain: malware-analysis
tags:
- cobalt-strike
- beacon
- c2
- malware-analysis
- config-extraction
- threat-hunting
- red-team-tools
version: '1.0'
author: mahipal
license: Apache-2.0
nist_csf:
- DE.AE-02
- RS.AN-03
- ID.RA-01
- DE.CM-01
mitre_attack:
- T1071.001
- T1573.001
- T1090.004
- T1105
- T1027

Analyzing Cobalt Strike Beacon Configuration

Overview

Cobalt Strike is a commercial adversary simulation tool widely abused by threat actors for post-exploitation operations. Beacon payloads contain embedded configuration data that reveals C2 server addresses, communication protocols, sleep intervals, jitter values, malleable C2 profile settings, watermark identifiers, and encryption keys. Extracting this configuration from PE files, shellcode, or memory dumps is critical for incident responders to map attacker infrastructure and attribute campaigns. The beacon configuration is XOR-encoded using a single byte (0x69 for version 3, 0x2e for version 4) and stored in a Type-Length-Value (TLV) format within the .data section.

When to Use

  • When investigating security incidents that require analyzing cobalt strike beacon configuration
  • When building detection rules or threat hunting queries for this domain
  • When SOC analysts need structured procedures for this analysis type
  • When validating security monitoring coverage for related attack techniques

Prerequisites

  • Python 3.9+ with dissect.cobaltstrike, pefile, yara-python
  • SentinelOne CobaltStrikeParser (parse_beacon_config.py)
  • Hex editor (010 Editor, HxD) for manual inspection
  • Understanding of PE file format and XOR encoding
  • Memory dump acquisition tools (Volatility3, WinDbg)
  • Network analysis tools (Wireshark) for C2 traffic correlation

Key Concepts

Beacon Configuration Structure

Cobalt Strike beacons store their configuration as a blob of TLV (Type-Length-Value) entries within the .data section of the PE. Stageless beacons XOR the entire beacon code with a 4-byte key. The configuration blob itself uses a single-byte XOR key. Each TLV entry contains a 2-byte type identifier (e.g., 0x0001 for BeaconType, 0x0008 for C2Server), a 2-byte length, and variable-length data.

Malleable C2 Profiles

The beacon configuration encodes the malleable C2 profile that dictates HTTP request/response transformations, including URI paths, headers, metadata encoding (Base64, NetBIOS), and data transforms. Analyzing these settings reveals how the beacon disguises its traffic to blend with legitimate web traffic.

Watermark and License Identification

Each Cobalt Strike license embeds a unique watermark (4-byte integer) into generated beacons. Extracting the watermark can link multiple beacons to the same operator or cracked license. Known watermark databases maintained by threat intelligence providers map watermarks to specific threat actors or leaked license keys.

Workflow

Step 1: Extract Configuration with CobaltStrikeParser

#!/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))

Step 2: Manual XOR Decryption of Beacon Config

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

Step 3: YARA Rule for Beacon Detection

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

Step 4: Network Traffic Correlation

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;)')

Validation Criteria

  • Beacon configuration successfully extracted from PE file or memory dump
  • C2 server domains/IPs correctly identified with port and protocol
  • Malleable C2 profile parameters decoded showing HTTP transforms
  • Watermark value extracted for attribution correlation
  • Sleep time and jitter values match observed network beacon intervals
  • YARA rules detect beacon in both packed and unpacked samples
  • Network signatures generated from extracted C2 profile

References

FULL BUNDLE (8 files)
# Agent Skill Package: analyzing-cobalt-strike-beacon-configuration

You are loading a published Agent Skill. Follow SKILL.md exactly.
Supporting files from the original zip are inlined below.
When SKILL.md says to read `references/...` or `scripts/...`, use the matching FILE section here — do not say the file is missing.

Canonical URL: https://skill.hk/s/analyzing-cobalt-strike-beacon-configuration.md
Human page: https://skill.hk/s/analyzing-cobalt-strike-beacon-configuration

Files (8):
- SKILL.md
- assets/template.md
- LICENSE
- references/api-reference.md
- references/standards.md
- references/workflows.md
- scripts/agent.py
- scripts/process.py

========================================================================
FILE: SKILL.md
========================================================================

---
name: analyzing-cobalt-strike-beacon-configuration
description: Extract and analyze Cobalt Strike beacon configuration from PE files
  and memory dumps to identify C2 infrastructure, malleable profiles, and operator
  tradecraft.
domain: cybersecurity
subdomain: malware-analysis
tags:
- cobalt-strike
- beacon
- c2
- malware-analysis
- config-extraction
- threat-hunting
- red-team-tools
version: '1.0'
author: mahipal
license: Apache-2.0
nist_csf:
- DE.AE-02
- RS.AN-03
- ID.RA-01
- DE.CM-01
mitre_attack:
- T1071.001
- T1573.001
- T1090.004
- T1105
- T1027
---
# Analyzing Cobalt Strike Beacon Configuration

## Overview

Cobalt Strike is a commercial adversary simulation tool widely abused by threat actors for post-exploitation operations. Beacon payloads contain embedded configuration data that reveals C2 server addresses, communication protocols, sleep intervals, jitter values, malleable C2 profile settings, watermark identifiers, and encryption keys. Extracting this configuration from PE files, shellcode, or memory dumps is critical for incident responders to map attacker infrastructure and attribute campaigns. The beacon configuration is XOR-encoded using a single byte (0x69 for version 3, 0x2e for version 4) and stored in a Type-Length-Value (TLV) format within the .data section.


## When to Use

- When investigating security incidents that require analyzing cobalt strike beacon configuration
- When building detection rules or threat hunting queries for this domain
- When SOC analysts need structured procedures for this analysis type
- When validating security monitoring coverage for related attack techniques

## Prerequisites

- Python 3.9+ with `dissect.cobaltstrike`, `pefile`, `yara-python`
- SentinelOne CobaltStrikeParser (`parse_beacon_config.py`)
- Hex editor (010 Editor, HxD) for manual inspection
- Understanding of PE file format and XOR encoding
- Memory dump acquisition tools (Volatility3, WinDbg)
- Network analysis tools (Wireshark) for C2 traffic correlation

## Key Concepts

### Beacon Configuration Structure

Cobalt Strike beacons store their configuration as a blob of TLV (Type-Length-Value) entries within the .data section of the PE. Stageless beacons XOR the entire beacon code with a 4-byte key. The configuration blob itself uses a single-byte XOR key. Each TLV entry contains a 2-byte type identifier (e.g., 0x0001 for BeaconType, 0x0008 for C2Server), a 2-byte length, and variable-length data.

### Malleable C2 Profiles

The beacon configuration encodes the malleable C2 profile that dictates HTTP request/response transformations, including URI paths, headers, metadata encoding (Base64, NetBIOS), and data transforms. Analyzing these settings reveals how the beacon disguises its traffic to blend with legitimate web traffic.

### Watermark and License Identification

Each Cobalt Strike license embeds a unique watermark (4-byte integer) into generated beacons. Extracting the watermark can link multiple beacons to the same operator or cracked license. Known watermark databases maintained by threat intelligence providers map watermarks to specific threat actors or leaked license keys.

## Workflow

### Step 1: Extract Configuration with CobaltStrikeParser

```python
#!/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))
```

### Step 2: Manual XOR Decryption of Beacon Config

```python
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
```

### Step 3: YARA Rule for Beacon Detection

```python
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
```

### Step 4: Network Traffic Correlation

```python
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;)')
```

## Validation Criteria

- Beacon configuration successfully extracted from PE file or memory dump
- C2 server domains/IPs correctly identified with port and protocol
- Malleable C2 profile parameters decoded showing HTTP transforms
- Watermark value extracted for attribution correlation
- Sleep time and jitter values match observed network beacon intervals
- YARA rules detect beacon in both packed and unpacked samples
- Network signatures generated from extracted C2 profile

## References

- [SentinelOne CobaltStrikeParser](https://github.com/Sentinel-One/CobaltStrikeParser)
- [dissect.cobaltstrike Library](https://github.com/fox-it/dissect.cobaltstrike)
- [SentinelLabs Beacon Configuration Analysis](https://www.sentinelone.com/labs/the-anatomy-of-an-apt-attack-and-cobaltstrike-beacons-encoded-configuration/)
- [Cobalt Strike Staging and Config Extraction](https://blog.securehat.co.uk/cobaltstrike/extracting-config-from-cobaltstrike-stager-shellcode)
- [MITRE ATT&CK - Cobalt Strike S0154](https://attack.mitre.org/software/S0154/)


========================================================================
FILE: assets/template.md
========================================================================

# Cobalt Strike Beacon Analysis Report Template

## Report Metadata
| Field | Value |
|-------|-------|
| Report ID | CS-BEACON-YYYY-NNNN |
| Date | YYYY-MM-DD |
| Sample Hash (SHA-256) | |
| Classification | TLP:AMBER |
| Analyst | |

## Beacon Configuration Summary

| Setting | Value |
|---------|-------|
| Beacon Type | HTTP / HTTPS / SMB / DNS |
| C2 Server(s) | |
| Port | |
| Sleep Time | ms |
| Jitter | % |
| User-Agent | |
| Watermark | |
| SpawnTo (x86) | |
| SpawnTo (x64) | |
| Named Pipe | |
| Host Header | |
| Crypto Scheme | |

## C2 Infrastructure

| Indicator | Type | Value | Context |
|-----------|------|-------|---------|
| C2 Domain | domain | | Primary callback |
| C2 IP | ip | | Resolved address |
| URI Path (GET) | uri | | Beacon check-in |
| URI Path (POST) | uri | | Data exfiltration |

## Malleable C2 Profile

### HTTP GET Configuration
| Parameter | Value |
|-----------|-------|
| URI | |
| Verb | |
| Headers | |
| Metadata Encoding | |

### HTTP POST Configuration
| Parameter | Value |
|-----------|-------|
| URI | |
| Verb | |
| ID Encoding | |
| Output Encoding | |

## Watermark Attribution

| Watermark | Known Association | Confidence |
|-----------|------------------|------------|
| | Cracked / Licensed / Threat Actor | High/Med/Low |

## Network Detection Signatures

```
# Suricata signature for beacon C2 traffic
alert http $HOME_NET any -> $EXTERNAL_NET any (
    msg:"Cobalt Strike Beacon C2 Communication";
    content:"[USER_AGENT]"; http_user_agent;
    content:"[URI_PATH]"; http_uri;
    sid:1000001; rev:1;
)
```

## YARA Detection Rule

```yara
rule CobaltStrike_Beacon_[CAMPAIGN] {
    meta:
        description = "Detects Cobalt Strike beacon from [CAMPAIGN]"
        hash = "[SHA256]"
    strings:
        $c2 = "[C2_DOMAIN]" ascii
        $pipe = "[NAMED_PIPE]" ascii
        $ua = "[USER_AGENT]" ascii
    condition:
        2 of them
}
```

## Recommendations

1. **Block**: Add C2 domains/IPs to firewall deny lists
2. **Hunt**: Search for named pipe and spawn-to process in endpoint logs
3. **Detect**: Deploy YARA and network signatures to detection stack
4. **Correlate**: Check watermark against threat intelligence databases


========================================================================
FILE: LICENSE
========================================================================


                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to the Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by the Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding any notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. Please do not remove or change
      the license header comment from a contributed file except when
      necessary.

   Copyright 2026 mukul975

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


========================================================================
FILE: references/api-reference.md
========================================================================

# API Reference: Cobalt Strike Beacon Configuration Analysis

## Beacon Config TLV Format

### Structure
```
[Field ID: 2 bytes][Type: 2 bytes][Value: variable]
Type 1 = short (2 bytes), Type 2 = int (4 bytes), Type 3 = string/blob (2-byte length + data)
```

### XOR Encoding
| Version | XOR Key |
|---------|---------|
| CS 3.x | `0x69` |
| CS 4.x | `0x2E` |

### Key Configuration Fields
| ID | Name | Description |
|----|------|-------------|
| 1 | BeaconType | 0=HTTP, 1=Hybrid, 2=SMB, 8=HTTPS |
| 2 | Port | C2 communication port |
| 3 | SleepTime | Beacon interval (ms) |
| 5 | Jitter | Random sleep variation (%) |
| 7 | PublicKey | RSA public key for encryption |
| 8 | C2Server | Command and control server(s) |
| 9 | UserAgent | HTTP User-Agent string |
| 10 | PostURI | POST callback URI |
| 37 | Watermark | License watermark (operator ID) |
| 54 | PipeName | Named pipe for SMB beacons |

## 1768.py (Didier Stevens) - Config Extractor

### Syntax
```bash
python 1768.py <beacon_file>           # Extract config
python 1768.py -j <beacon_file>        # JSON output
python 1768.py -r <beacon_file>        # Raw config dump
```

## CobaltStrikeParser (SentinelOne)

### Syntax
```bash
python parse_beacon_config.py <file>
python parse_beacon_config.py --json <file>
```

### Output Fields
```
BeaconType:        HTTPS
Port:              443
SleepTime:         60000
Jitter:            37
C2Server:          update.microsoft-cdn.com,/api/v2
UserAgent:         Mozilla/5.0 (Windows NT 10.0; Win64; x64)
Watermark:         305419896
SpawnToX86:        %windir%\syswow64\dllhost.exe
SpawnToX64:        %windir%\sysnative\dllhost.exe
```

## JARM Fingerprinting

### Cobalt Strike Default JARM
```bash
# Default CS JARM hash (pre-4.7)
07d14d16d21d21d07c42d41d00041d24a458a375eef0c576d23a7bab9a9fb1

# Scan with JARM
python jarm.py <target_ip> -p 443
```

## Known Watermark Values
| Watermark | Attribution |
|-----------|------------|
| 0 | Trial/cracked version |
| 305419896 | Common cracked version |
| 1359593325 | Known threat actor toolkit |
| 1580103824 | Known APT usage |

## Detection Signatures

### Suricata
```
alert http $HOME_NET any -> $EXTERNAL_NET any (
    msg:"ET MALWARE Cobalt Strike Beacon";
    content:"/submit.php"; http_uri;
    content:"Cookie:"; http_header;
    pcre:"/Cookie:\s[A-Za-z0-9+/=]{60,}/H";
    sid:2028591; rev:1;)
```

### YARA
```yara
rule CobaltStrike_Beacon {
    strings:
        $config_v3 = { 00 01 00 01 00 02 ?? ?? 00 01 00 02 }
        $magic = "MSSE-%d-server"
        $pipe = "\\\\.\\pipe\\msagent_"
    condition:
        uint16(0) == 0x5A4D and any of them
}
```

## Malleable C2 Profile Elements
| Element | Description |
|---------|-------------|
| `http-get` | GET request profile (URI, headers, metadata transform) |
| `http-post` | POST request profile (URI, body transform) |
| `set sleeptime` | Default beacon interval |
| `set jitter` | Randomization percentage |
| `set useragent` | HTTP User-Agent |
| `set pipename` | SMB named pipe name |


========================================================================
FILE: references/standards.md
========================================================================

# Standards and Frameworks Reference

## Cobalt Strike Beacon Configuration Fields

### Configuration TLV Types
| Type ID | Field Name | Data Type | Description |
|---------|-----------|-----------|-------------|
| 0x0001 | BeaconType | Short | 0=HTTP, 1=Hybrid HTTP/DNS, 8=HTTPS, 10=TCP Bind |
| 0x0002 | Port | Short | C2 communication port |
| 0x0003 | SleepTime | Int | Beacon callback interval in milliseconds |
| 0x0005 | Jitter | Short | Percentage of sleep time randomization (0-99) |
| 0x0008 | C2Server | String | Comma-separated C2 domains/IPs |
| 0x0009 | UserAgent | String | HTTP User-Agent header value |
| 0x000a | PostURI | String | URI for HTTP POST requests |
| 0x000d | SpawnTo_x86 | String | 32-bit process to spawn for post-ex |
| 0x000e | SpawnTo_x64 | String | 64-bit process to spawn for post-ex |
| 0x001a | Watermark | Int | License watermark identifier |
| 0x0024 | PipeName | String | Named pipe for SMB beacon |
| 0x001d | HostHeader | String | HTTP Host header value |
| 0x0032 | ProxyHostname | String | Proxy server address |

### XOR Encoding Scheme
- **Cobalt Strike 3.x**: XOR key = 0x69
- **Cobalt Strike 4.x**: XOR key = 0x2e
- Configuration blob size: 4096 bytes (typical)
- Encoding: Single-byte XOR across entire config blob

### Stageless Beacon Structure
- PE with beacon code in .data section
- 4-byte XOR key applied to .data section content
- Configuration embedded after beacon code
- Reflective DLL loader prepended to beacon

## MITRE ATT&CK Mappings

### Cobalt Strike Techniques (S0154)
| Technique | ID | Description |
|-----------|-----|------------|
| Application Layer Protocol | T1071.001 | HTTP/HTTPS C2 communication |
| Encrypted Channel | T1573.002 | AES-256 encrypted C2 |
| Ingress Tool Transfer | T1105 | Download additional payloads |
| Process Injection | T1055 | Inject into spawned processes |
| Named Pipes | T1570 | SMB beacon lateral movement |
| Service Execution | T1569.002 | PSExec-style lateral movement |
| Reflective Code Loading | T1620 | In-memory beacon loading |

## Malleable C2 Profile Structure

### HTTP GET Block
```
http-get {
    set uri "/path";
    client {
        header "Accept" "text/html";
        metadata {
            base64url;
            prepend "session=";
            header "Cookie";
        }
    }
    server {
        header "Content-Type" "text/html";
        output {
            print;
        }
    }
}
```

### HTTP POST Block
```
http-post {
    set uri "/submit";
    client {
        id {
            uri-append;
        }
        output {
            base64;
            print;
        }
    }
    server {
        output {
            print;
        }
    }
}
```

## References
- [Cobalt Strike Documentation](https://hstechdocs.helpsystems.com/manuals/cobaltstrike/)
- [Malleable C2 Profile Reference](https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/content/topics/malleable-c2_main.htm)
- [MITRE ATT&CK Cobalt Strike](https://attack.mitre.org/software/S0154/)


========================================================================
FILE: references/workflows.md
========================================================================

# Cobalt Strike Beacon Analysis Workflows

## Workflow 1: PE File Configuration Extraction

```
[Suspicious PE] --> [Unpack if packed] --> [Locate .data section] --> [XOR Decrypt]
                                                                          |
                                                                          v
                                                                  [Parse TLV Config]
                                                                          |
                                                                          v
                                                              [Extract C2 Indicators]
```

### Steps:
1. **Triage**: Identify file as potential Cobalt Strike beacon via YARA or AV detection
2. **Unpacking**: If packed, unpack using appropriate tool (UPX, custom unpacker)
3. **Section Analysis**: Locate .data section containing XOR'd beacon code
4. **XOR Key Discovery**: Try known keys (0x2e, 0x69) or brute-force 4-byte key
5. **Config Parsing**: Parse decrypted TLV entries for C2 and operational settings
6. **IOC Extraction**: Extract domains, IPs, URIs, user agents, watermarks

## Workflow 2: Memory Dump Beacon Extraction

```
[Memory Dump] --> [Volatility3 malfind] --> [Dump Injected Regions] --> [Parse Config]
                                                                            |
                                                                            v
                                                                   [C2 Infrastructure Map]
```

### Steps:
1. **Acquisition**: Capture memory dump from compromised system
2. **Process Scan**: Use Volatility3 to identify suspicious processes
3. **Injection Detection**: Use malfind to find RWX memory regions
4. **Region Extraction**: Dump injected memory regions to files
5. **Config Search**: Scan dumps for beacon configuration signatures
6. **Infrastructure Mapping**: Correlate extracted C2 with network logs

## Workflow 3: Watermark Attribution

```
[Multiple Beacons] --> [Extract Watermarks] --> [Cluster by Watermark] --> [Attribution]
                                                                               |
                                                                               v
                                                                     [Campaign Correlation]
```

### Steps:
1. **Collection**: Gather beacon samples from incident or threat intel feeds
2. **Watermark Extraction**: Extract watermark value from each sample
3. **Database Lookup**: Check watermark against known databases
4. **Clustering**: Group beacons sharing the same watermark
5. **Infrastructure Overlap**: Correlate C2 infrastructure across cluster
6. **Attribution Assessment**: Link to known threat actor or cracked license

## Workflow 4: C2 Traffic Detection

```
[Beacon Config] --> [Extract C2 Profile] --> [Generate Signatures] --> [Deploy to NIDS]
                                                                            |
                                                                            v
                                                                   [Monitor Network Traffic]
```

### Steps:
1. **Profile Extraction**: Parse malleable C2 profile from beacon config
2. **Pattern Identification**: Identify unique HTTP headers, URIs, and encoding
3. **Signature Creation**: Write Suricata/Snort rules matching C2 patterns
4. **Deployment**: Deploy signatures to network detection infrastructure
5. **Validation**: Test signatures against captured beacon traffic
6. **Monitoring**: Alert on matching network flows for active beacons


========================================================================
FILE: scripts/agent.py
========================================================================

#!/usr/bin/env python3
"""Cobalt Strike beacon configuration extraction and analysis agent.

Extracts C2 configuration from beacon payloads including server addresses,
communication settings, malleable C2 profile details, and watermark values.
"""

import struct
import os
import sys
import hashlib
from collections import OrderedDict

# Cobalt Strike beacon configuration field IDs (Type-Length-Value format)
BEACON_CONFIG_FIELDS = {
    1: ("BeaconType", "short"),
    2: ("Port", "short"),
    3: ("SleepTime", "int"),
    4: ("MaxGetSize", "int"),
    5: ("Jitter", "short"),
    7: ("PublicKey", "bytes"),
    8: ("C2Server", "str"),
    9: ("UserAgent", "str"),
    10: ("PostURI", "str"),
    11: ("Malleable_C2_Instructions", "bytes"),
    12: ("HttpGet_Metadata", "bytes"),
    13: ("HttpPost_Metadata", "bytes"),
    14: ("SpawnToX86", "str"),
    15: ("SpawnToX64", "str"),
    19: ("CryptoScheme", "short"),
    26: ("GetVerb", "str"),
    27: ("PostVerb", "str"),
    28: ("HttpPostChunk", "int"),
    29: ("Spawnto_x86", "str"),
    30: ("Spawnto_x64", "str"),
    31: ("CryptoScheme2", "str"),
    37: ("Watermark", "int"),
    38: ("StageCleanup", "short"),
    39: ("CFGCaution", "short"),
    43: ("DNS_Idle", "int"),
    44: ("DNS_Sleep", "int"),
    50: ("HostHeader", "str"),
    54: ("PipeName", "str"),
}

BEACON_TYPES = {0: "HTTP", 1: "Hybrid HTTP/DNS", 2: "SMB", 4: "TCP", 8: "HTTPS", 16: "DNS over HTTPS"}

XOR_KEY_V3 = 0x69
XOR_KEY_V4 = 0x2E


def compute_hash(filepath):
    """Compute SHA-256 hash of file."""
    sha256 = hashlib.sha256()
    with open(filepath, "rb") as f:
        for chunk in iter(lambda: f.read(65536), b""):
            sha256.update(chunk)
    return sha256.hexdigest()


def find_config_offset(data):
    """Find the beacon configuration blob in PE data or shellcode."""
    # Look for XOR-encoded config patterns
    for xor_key in [XOR_KEY_V3, XOR_KEY_V4]:
        # Config starts with 0x0001 (BeaconType field ID) XOR-encoded
        encoded_marker = bytes([0x00 ^ xor_key, 0x01 ^ xor_key, 0x00 ^ xor_key, 0x01 ^ xor_key])
        offset = data.find(encoded_marker)
        if offset != -1:
            return offset, xor_key
    # Try unencoded
    for offset in range(len(data) - 100):
        if data[offset:offset+4] == b"\x00\x01\x00\x01":
            return offset, None
    return -1, None


def xor_decode(data, key):
    """XOR decode data with single byte key."""
    if key is None:
        return data
    return bytes(b ^ key for b in data)


def parse_config_field(data, offset):
    """Parse a single TLV config field."""
    if offset + 6 > len(data):
        return None, None, None, offset
    field_id = struct.unpack_from(">H", data, offset)[0]
    field_type = struct.unpack_from(">H", data, offset + 2)[0]
    if field_type == 1:  # short
        value = struct.unpack_from(">H", data, offset + 4)[0]
        return field_id, "short", value, offset + 6
    elif field_type == 2:  # int
        value = struct.unpack_from(">I", data, offset + 4)[0]
        return field_id, "int", value, offset + 8
    elif field_type == 3:  # str/bytes
        length = struct.unpack_from(">H", data, offset + 4)[0]
        if offset + 6 + length > len(data):
            return None, None, None, offset
        value = data[offset + 6:offset + 6 + length]
        return field_id, "str", value, offset + 6 + length
    return None, None, None, offset + 2


def extract_beacon_config(filepath):
    """Extract and parse Cobalt Strike beacon configuration."""
    with open(filepath, "rb") as f:
        data = f.read()

    config_offset, xor_key = find_config_offset(data)
    if config_offset == -1:
        return {"error": "No beacon configuration found", "file": filepath}

    config_data = xor_decode(data[config_offset:config_offset + 4096], xor_key)
    config = OrderedDict()
    config["_meta"] = {
        "config_offset": f"0x{config_offset:08X}",
        "xor_key": f"0x{xor_key:02X}" if xor_key else "none",
        "version_guess": "4.x" if xor_key == XOR_KEY_V4 else "3.x" if xor_key == XOR_KEY_V3 else "unknown",
    }

    offset = 0
    max_fields = 100
    parsed = 0
    while offset < len(config_data) - 4 and parsed < max_fields:
        field_id, field_type, value, new_offset = parse_config_field(config_data, offset)
        if field_id is None or new_offset == offset:
            break
        offset = new_offset
        parsed += 1

        field_info = BEACON_CONFIG_FIELDS.get(field_id)
        if field_info:
            field_name, expected_type = field_info
            if isinstance(value, bytes):
                try:
                    str_value = value.rstrip(b"\x00").decode("utf-8", errors="replace")
                    config[field_name] = str_value
                except Exception:
                    config[field_name] = value.hex()[:100]
            elif field_id == 1:
                config[field_name] = BEACON_TYPES.get(value, f"Unknown({value})")
            else:
                config[field_name] = value

    return config


def extract_c2_indicators(config):
    """Extract C2 indicators from parsed config for threat intelligence."""
    indicators = {"c2_servers": [], "user_agents": [], "uris": [],
                  "pipes": [], "watermark": None, "dns": []}
    c2 = config.get("C2Server", "")
    if c2:
        for server in c2.split(","):
            server = server.strip().rstrip("/")
            if server:
                indicators["c2_servers"].append(server)
    ua = config.get("UserAgent", "")
    if ua:
        indicators["user_agents"].append(ua)
    for key in ["PostURI"]:
        uri = config.get(key, "")
        if uri:
            indicators["uris"].append(uri)
    pipe = config.get("PipeName", "")
    if pipe:
        indicators["pipes"].append(pipe)
    wm = config.get("Watermark")
    if wm:
        indicators["watermark"] = wm
    return indicators


def assess_operator_opsec(config):
    """Assess operator OPSEC based on beacon configuration."""
    findings = []
    sleep = config.get("SleepTime", 0)
    jitter = config.get("Jitter", 0)
    if sleep < 30000:
        findings.append({"level": "INFO", "detail": f"Low sleep time: {sleep}ms - high beacon frequency"})
    if jitter == 0:
        findings.append({"level": "WARN", "detail": "No jitter configured - predictable beacon interval"})
    ua = config.get("UserAgent", "")
    if "Mozilla" not in ua and ua:
        findings.append({"level": "WARN", "detail": f"Non-standard User-Agent: {ua[:60]}"})
    spawn86 = config.get("SpawnToX86", config.get("Spawnto_x86", ""))
    if "rundll32" in spawn86.lower():
        findings.append({"level": "INFO", "detail": "Default spawn-to process (rundll32) - easy to detect"})
    cleanup = config.get("StageCleanup", 0)
    if cleanup == 0:
        findings.append({"level": "INFO", "detail": "Stage cleanup disabled - beacon stub remains in memory"})
    return findings


if __name__ == "__main__":
    print("=" * 60)
    print("Cobalt Strike Beacon Configuration Extractor")
    print("C2 extraction, watermark analysis, OPSEC assessment")
    print("=" * 60)

    target = sys.argv[1] if len(sys.argv) > 1 else None

    if not target or not os.path.exists(target):
        print("\n[DEMO] Usage: python agent.py <beacon_sample.exe>")
        print("  Extracts: C2 servers, sleep/jitter, watermark, malleable profile")
        sys.exit(0)

    print(f"\n[*] Analyzing: {target}")
    print(f"[*] SHA-256: {compute_hash(target)}")
    print(f"[*] Size: {os.path.getsize(target)} bytes")

    config = extract_beacon_config(target)

    if "error" in config:
        print(f"\n[!] {config['error']}")
        sys.exit(1)

    print("\n--- Beacon Configuration ---")
    for key, value in config.items():
        if key == "_meta":
            for mk, mv in value.items():
                print(f"  {mk}: {mv}")
        else:
            print(f"  {key}: {value}")

    indicators = extract_c2_indicators(config)
    print("\n--- C2 Indicators ---")
    for c2 in indicators["c2_servers"]:
        print(f"  [C2] {c2}")
    if indicators["watermark"]:
        print(f"  [Watermark] {indicators['watermark']}")
    for pipe in indicators["pipes"]:
        print(f"  [Pipe] {pipe}")

    opsec = assess_operator_opsec(config)
    print("\n--- Operator OPSEC Assessment ---")
    for f in opsec:
        print(f"  [{f['level']}] {f['detail']}")


========================================================================
FILE: scripts/process.py
========================================================================

#!/usr/bin/env python3
"""
Cobalt Strike Beacon Configuration Analyzer

Extracts and analyzes beacon configurations from PE files, shellcode,
and memory dumps using dissect.cobaltstrike and manual parsing.

Requirements:
    pip install dissect.cobaltstrike pefile yara-python

Usage:
    python process.py --file beacon.exe --output report.json
    python process.py --file memdump.bin --scan-memory
    python process.py --directory ./samples --batch
"""

import argparse
import json
import os
import struct
import sys
from collections import defaultdict
from datetime import datetime
from pathlib import Path

try:
    from dissect.cobaltstrike.beacon import BeaconConfig
except ImportError:
    print("ERROR: dissect.cobaltstrike not installed.")
    print("Run: pip install dissect.cobaltstrike")
    sys.exit(1)


# TLV field type mapping
TLV_FIELDS = {
    0x0001: ("BeaconType", "short"),
    0x0002: ("Port", "short"),
    0x0003: ("SleepTime", "int"),
    0x0004: ("MaxGetSize", "int"),
    0x0005: ("Jitter", "short"),
    0x0006: ("MaxDNS", "short"),
    0x0008: ("C2Server", "str"),
    0x0009: ("UserAgent", "str"),
    0x000a: ("PostURI", "str"),
    0x000b: ("Malleable_C2_Instructions", "blob"),
    0x000d: ("SpawnTo_x86", "str"),
    0x000e: ("SpawnTo_x64", "str"),
    0x000f: ("CryptoScheme", "short"),
    0x001a: ("Watermark", "int"),
    0x001d: ("HostHeader", "str"),
    0x0024: ("PipeName", "str"),
    0x0025: ("Year", "short"),
    0x0026: ("Month", "short"),
    0x0027: ("Day", "short"),
    0x002c: ("ProxyHostname", "str"),
    0x002d: ("ProxyUsername", "str"),
    0x002e: ("ProxyPassword", "str"),
}

BEACON_TYPES = {
    0: "HTTP",
    1: "Hybrid HTTP/DNS",
    2: "SMB",
    4: "TCP",
    8: "HTTPS",
    10: "TCP Bind",
    14: "External C2",
}


class BeaconAnalyzer:
    """Analyze Cobalt Strike beacon configurations."""

    def __init__(self):
        self.results = []

    def analyze_file(self, filepath):
        """Extract beacon config from a file."""
        filepath = Path(filepath)
        if not filepath.exists():
            print(f"[-] File not found: {filepath}")
            return None

        print(f"[*] Analyzing: {filepath}")

        # Try dissect.cobaltstrike first
        result = self._extract_with_dissect(filepath)

        # Fall back to manual extraction
        if not result:
            result = self._extract_manual(filepath)

        if result:
            result["source_file"] = str(filepath)
            result["analysis_time"] = datetime.now().isoformat()
            self.results.append(result)

        return result

    def _extract_with_dissect(self, filepath):
        """Extract config using dissect.cobaltstrike library."""
        try:
            configs = list(BeaconConfig.from_path(filepath))
            if not configs:
                return None

            config = configs[0]
            settings = config.as_dict()

            result = {
                "method": "dissect.cobaltstrike",
                "config": {},
                "indicators": {},
            }

            for key, value in settings.items():
                if value is not None:
                    result["config"][key] = str(value)

            result["indicators"] = self._extract_indicators(settings)
            return result

        except Exception as e:
            print(f"  [!] dissect extraction failed: {e}")
            return None

    def _extract_manual(self, filepath):
        """Manual XOR-based config extraction."""
        try:
            with open(filepath, "rb") as f:
                data = f.read()
        except Exception as e:
            print(f"  [!] Read failed: {e}")
            return None

        for xor_key in [0x2e, 0x69]:
            # Search for XOR'd config start marker
            magic = bytes([0x00 ^ xor_key, 0x01 ^ xor_key,
                           0x00 ^ xor_key, 0x02 ^ xor_key])

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

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

            config_blob = data[offset:offset + 4096]
            decrypted = bytes([b ^ xor_key for b in config_blob])

            entries = self._parse_tlv(decrypted)
            if entries:
                return {
                    "method": "manual_xor",
                    "xor_key": f"0x{xor_key:02x}",
                    "config_offset": f"0x{offset:x}",
                    "config": entries,
                    "indicators": self._extract_indicators(entries),
                }

        return None

    def _parse_tlv(self, data):
        """Parse TLV configuration entries."""
        entries = {}
        offset = 0

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

            if entry_type == 0 or entry_len > 4096:
                break

            value_data = data[offset+6:offset+6+entry_len]
            field_info = TLV_FIELDS.get(entry_type)

            if field_info:
                field_name, expected_type = field_info
            else:
                field_name = f"Unknown_0x{entry_type:04x}"
                expected_type = "blob"

            if data_type == 1 and len(value_data) >= 2:
                value = struct.unpack(">H", value_data[:2])[0]
            elif data_type == 2 and len(value_data) >= 4:
                value = struct.unpack(">I", value_data[:4])[0]
            elif data_type == 3:
                value = value_data.rstrip(b'\x00').decode('utf-8', errors='replace')
            else:
                value = value_data.hex()

            # Resolve beacon type names
            if field_name == "BeaconType" and isinstance(value, int):
                value = BEACON_TYPES.get(value, f"Unknown ({value})")

            entries[field_name] = value
            offset += 6 + entry_len

        return entries

    def _extract_indicators(self, config):
        """Extract IOCs from parsed configuration."""
        indicators = {
            "c2_servers": [],
            "user_agent": "",
            "named_pipes": [],
            "spawn_processes": [],
            "watermark": "",
            "beacon_type": "",
            "sleep_time_ms": 0,
            "jitter_pct": 0,
        }

        # Handle both dissect dict keys and manual parse keys
        c2_keys = ["SETTING_DOMAINS", "C2Server"]
        for key in c2_keys:
            domains = config.get(key, "")
            if domains:
                for d in str(domains).split(","):
                    d = d.strip().rstrip("/")
                    if d:
                        indicators["c2_servers"].append(d)

        ua_keys = ["SETTING_USERAGENT", "UserAgent"]
        for key in ua_keys:
            ua = config.get(key, "")
            if ua:
                indicators["user_agent"] = str(ua)

        pipe_keys = ["SETTING_PIPENAME", "PipeName"]
        for key in pipe_keys:
            pipe = config.get(key, "")
            if pipe:
                indicators["named_pipes"].append(str(pipe))

        spawn_keys = [
            ("SETTING_SPAWNTO_X86", "SpawnTo_x86"),
            ("SETTING_SPAWNTO_X64", "SpawnTo_x64"),
        ]
        for dissect_key, manual_key in spawn_keys:
            for key in [dissect_key, manual_key]:
                proc = config.get(key, "")
                if proc:
                    indicators["spawn_processes"].append(str(proc))

        wm_keys = ["SETTING_WATERMARK", "Watermark"]
        for key in wm_keys:
            wm = config.get(key, "")
            if wm:
                indicators["watermark"] = str(wm)

        return indicators

    def batch_analyze(self, directory):
        """Analyze all files in a directory."""
        directory = Path(directory)
        extensions = {".exe", ".dll", ".bin", ".dmp", ".raw"}

        for filepath in directory.rglob("*"):
            if filepath.suffix.lower() in extensions:
                self.analyze_file(filepath)

        return self.results

    def cluster_by_watermark(self):
        """Cluster analyzed beacons by watermark."""
        clusters = defaultdict(list)

        for result in self.results:
            wm = result.get("indicators", {}).get("watermark", "unknown")
            clusters[wm].append(result.get("source_file", "unknown"))

        return dict(clusters)

    def generate_report(self, output_path=None):
        """Generate JSON analysis report."""
        report = {
            "analysis_date": datetime.now().isoformat(),
            "total_beacons": len(self.results),
            "watermark_clusters": self.cluster_by_watermark(),
            "all_c2_servers": list(set(
                server
                for r in self.results
                for server in r.get("indicators", {}).get("c2_servers", [])
            )),
            "results": self.results,
        }

        if output_path:
            with open(output_path, "w") as f:
                json.dump(report, f, indent=2, default=str)
            print(f"[+] Report saved to {output_path}")

        return report


def main():
    parser = argparse.ArgumentParser(
        description="Cobalt Strike Beacon Configuration Analyzer"
    )
    parser.add_argument("--file", help="Single file to analyze")
    parser.add_argument("--directory", help="Directory for batch analysis")
    parser.add_argument("--output", default="beacon_report.json",
                        help="Output report path")
    parser.add_argument("--scan-memory", action="store_true",
                        help="Treat input as raw memory dump")
    parser.add_argument("--batch", action="store_true",
                        help="Batch analyze directory")

    args = parser.parse_args()
    analyzer = BeaconAnalyzer()

    if args.file:
        result = analyzer.analyze_file(args.file)
        if result:
            print(json.dumps(result, indent=2, default=str))

    elif args.directory and args.batch:
        results = analyzer.batch_analyze(args.directory)
        print(f"\n[+] Analyzed {len(results)} beacons")

    else:
        parser.print_help()
        sys.exit(1)

    report = analyzer.generate_report(args.output)
    print(f"\n[+] Total C2 servers found: {len(report['all_c2_servers'])}")
    for server in report["all_c2_servers"]:
        print(f"    {server}")


if __name__ == "__main__":
    main()

assets/template.md

IN BUNDLE
# Cobalt Strike Beacon Analysis Report Template

## Report Metadata
| Field | Value |
|-------|-------|
| Report ID | CS-BEACON-YYYY-NNNN |
| Date | YYYY-MM-DD |
| Sample Hash (SHA-256) | |
| Classification | TLP:AMBER |
| Analyst | |

## Beacon Configuration Summary

| Setting | Value |
|---------|-------|
| Beacon Type | HTTP / HTTPS / SMB / DNS |
| C2 Server(s) | |
| Port | |
| Sleep Time | ms |
| Jitter | % |
| User-Agent | |
| Watermark | |
| SpawnTo (x86) | |
| SpawnTo (x64) | |
| Named Pipe | |
| Host Header | |
| Crypto Scheme | |

## C2 Infrastructure

| Indicator | Type | Value | Context |
|-----------|------|-------|---------|
| C2 Domain | domain | | Primary callback |
| C2 IP | ip | | Resolved address |
| URI Path (GET) | uri | | Beacon check-in |
| URI Path (POST) | uri | | Data exfiltration |

## Malleable C2 Profile

### HTTP GET Configuration
| Parameter | Value |
|-----------|-------|
| URI | |
| Verb | |
| Headers | |
| Metadata Encoding | |

### HTTP POST Configuration
| Parameter | Value |
|-----------|-------|
| URI | |
| Verb | |
| ID Encoding | |
| Output Encoding | |

## Watermark Attribution

| Watermark | Known Association | Confidence |
|-----------|------------------|------------|
| | Cracked / Licensed / Threat Actor | High/Med/Low |

## Network Detection Signatures

```
# Suricata signature for beacon C2 traffic
alert http $HOME_NET any -> $EXTERNAL_NET any (
    msg:"Cobalt Strike Beacon C2 Communication";
    content:"[USER_AGENT]"; http_user_agent;
    content:"[URI_PATH]"; http_uri;
    sid:1000001; rev:1;
)
```

## YARA Detection Rule

```yara
rule CobaltStrike_Beacon_[CAMPAIGN] {
    meta:
        description = "Detects Cobalt Strike beacon from [CAMPAIGN]"
        hash = "[SHA256]"
    strings:
        $c2 = "[C2_DOMAIN]" ascii
        $pipe = "[NAMED_PIPE]" ascii
        $ua = "[USER_AGENT]" ascii
    condition:
        2 of them
}
```

## Recommendations

1. **Block**: Add C2 domains/IPs to firewall deny lists
2. **Hunt**: Search for named pipe and spawn-to process in endpoint logs
3. **Detect**: Deploy YARA and network signatures to detection stack
4. **Correlate**: Check watermark against threat intelligence databases

LICENSE

IN BUNDLE
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to the Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by the Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding any notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. Please do not remove or change
      the license header comment from a contributed file except when
      necessary.

   Copyright 2026 mukul975

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

references/api-reference.md

IN BUNDLE
# API Reference: Cobalt Strike Beacon Configuration Analysis

## Beacon Config TLV Format

### Structure
```
[Field ID: 2 bytes][Type: 2 bytes][Value: variable]
Type 1 = short (2 bytes), Type 2 = int (4 bytes), Type 3 = string/blob (2-byte length + data)
```

### XOR Encoding
| Version | XOR Key |
|---------|---------|
| CS 3.x | `0x69` |
| CS 4.x | `0x2E` |

### Key Configuration Fields
| ID | Name | Description |
|----|------|-------------|
| 1 | BeaconType | 0=HTTP, 1=Hybrid, 2=SMB, 8=HTTPS |
| 2 | Port | C2 communication port |
| 3 | SleepTime | Beacon interval (ms) |
| 5 | Jitter | Random sleep variation (%) |
| 7 | PublicKey | RSA public key for encryption |
| 8 | C2Server | Command and control server(s) |
| 9 | UserAgent | HTTP User-Agent string |
| 10 | PostURI | POST callback URI |
| 37 | Watermark | License watermark (operator ID) |
| 54 | PipeName | Named pipe for SMB beacons |

## 1768.py (Didier Stevens) - Config Extractor

### Syntax
```bash
python 1768.py <beacon_file>           # Extract config
python 1768.py -j <beacon_file>        # JSON output
python 1768.py -r <beacon_file>        # Raw config dump
```

## CobaltStrikeParser (SentinelOne)

### Syntax
```bash
python parse_beacon_config.py <file>
python parse_beacon_config.py --json <file>
```

### Output Fields
```
BeaconType:        HTTPS
Port:              443
SleepTime:         60000
Jitter:            37
C2Server:          update.microsoft-cdn.com,/api/v2
UserAgent:         Mozilla/5.0 (Windows NT 10.0; Win64; x64)
Watermark:         305419896
SpawnToX86:        %windir%\syswow64\dllhost.exe
SpawnToX64:        %windir%\sysnative\dllhost.exe
```

## JARM Fingerprinting

### Cobalt Strike Default JARM
```bash
# Default CS JARM hash (pre-4.7)
07d14d16d21d21d07c42d41d00041d24a458a375eef0c576d23a7bab9a9fb1

# Scan with JARM
python jarm.py <target_ip> -p 443
```

## Known Watermark Values
| Watermark | Attribution |
|-----------|------------|
| 0 | Trial/cracked version |
| 305419896 | Common cracked version |
| 1359593325 | Known threat actor toolkit |
| 1580103824 | Known APT usage |

## Detection Signatures

### Suricata
```
alert http $HOME_NET any -> $EXTERNAL_NET any (
    msg:"ET MALWARE Cobalt Strike Beacon";
    content:"/submit.php"; http_uri;
    content:"Cookie:"; http_header;
    pcre:"/Cookie:\s[A-Za-z0-9+/=]{60,}/H";
    sid:2028591; rev:1;)
```

### YARA
```yara
rule CobaltStrike_Beacon {
    strings:
        $config_v3 = { 00 01 00 01 00 02 ?? ?? 00 01 00 02 }
        $magic = "MSSE-%d-server"
        $pipe = "\\\\.\\pipe\\msagent_"
    condition:
        uint16(0) == 0x5A4D and any of them
}
```

## Malleable C2 Profile Elements
| Element | Description |
|---------|-------------|
| `http-get` | GET request profile (URI, headers, metadata transform) |
| `http-post` | POST request profile (URI, body transform) |
| `set sleeptime` | Default beacon interval |
| `set jitter` | Randomization percentage |
| `set useragent` | HTTP User-Agent |
| `set pipename` | SMB named pipe name |

references/standards.md

IN BUNDLE
# Standards and Frameworks Reference

## Cobalt Strike Beacon Configuration Fields

### Configuration TLV Types
| Type ID | Field Name | Data Type | Description |
|---------|-----------|-----------|-------------|
| 0x0001 | BeaconType | Short | 0=HTTP, 1=Hybrid HTTP/DNS, 8=HTTPS, 10=TCP Bind |
| 0x0002 | Port | Short | C2 communication port |
| 0x0003 | SleepTime | Int | Beacon callback interval in milliseconds |
| 0x0005 | Jitter | Short | Percentage of sleep time randomization (0-99) |
| 0x0008 | C2Server | String | Comma-separated C2 domains/IPs |
| 0x0009 | UserAgent | String | HTTP User-Agent header value |
| 0x000a | PostURI | String | URI for HTTP POST requests |
| 0x000d | SpawnTo_x86 | String | 32-bit process to spawn for post-ex |
| 0x000e | SpawnTo_x64 | String | 64-bit process to spawn for post-ex |
| 0x001a | Watermark | Int | License watermark identifier |
| 0x0024 | PipeName | String | Named pipe for SMB beacon |
| 0x001d | HostHeader | String | HTTP Host header value |
| 0x0032 | ProxyHostname | String | Proxy server address |

### XOR Encoding Scheme
- **Cobalt Strike 3.x**: XOR key = 0x69
- **Cobalt Strike 4.x**: XOR key = 0x2e
- Configuration blob size: 4096 bytes (typical)
- Encoding: Single-byte XOR across entire config blob

### Stageless Beacon Structure
- PE with beacon code in .data section
- 4-byte XOR key applied to .data section content
- Configuration embedded after beacon code
- Reflective DLL loader prepended to beacon

## MITRE ATT&CK Mappings

### Cobalt Strike Techniques (S0154)
| Technique | ID | Description |
|-----------|-----|------------|
| Application Layer Protocol | T1071.001 | HTTP/HTTPS C2 communication |
| Encrypted Channel | T1573.002 | AES-256 encrypted C2 |
| Ingress Tool Transfer | T1105 | Download additional payloads |
| Process Injection | T1055 | Inject into spawned processes |
| Named Pipes | T1570 | SMB beacon lateral movement |
| Service Execution | T1569.002 | PSExec-style lateral movement |
| Reflective Code Loading | T1620 | In-memory beacon loading |

## Malleable C2 Profile Structure

### HTTP GET Block
```
http-get {
    set uri "/path";
    client {
        header "Accept" "text/html";
        metadata {
            base64url;
            prepend "session=";
            header "Cookie";
        }
    }
    server {
        header "Content-Type" "text/html";
        output {
            print;
        }
    }
}
```

### HTTP POST Block
```
http-post {
    set uri "/submit";
    client {
        id {
            uri-append;
        }
        output {
            base64;
            print;
        }
    }
    server {
        output {
            print;
        }
    }
}
```

## References
- [Cobalt Strike Documentation](https://hstechdocs.helpsystems.com/manuals/cobaltstrike/)
- [Malleable C2 Profile Reference](https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/content/topics/malleable-c2_main.htm)
- [MITRE ATT&CK Cobalt Strike](https://attack.mitre.org/software/S0154/)

references/workflows.md

IN BUNDLE
# Cobalt Strike Beacon Analysis Workflows

## Workflow 1: PE File Configuration Extraction

```
[Suspicious PE] --> [Unpack if packed] --> [Locate .data section] --> [XOR Decrypt]
                                                                          |
                                                                          v
                                                                  [Parse TLV Config]
                                                                          |
                                                                          v
                                                              [Extract C2 Indicators]
```

### Steps:
1. **Triage**: Identify file as potential Cobalt Strike beacon via YARA or AV detection
2. **Unpacking**: If packed, unpack using appropriate tool (UPX, custom unpacker)
3. **Section Analysis**: Locate .data section containing XOR'd beacon code
4. **XOR Key Discovery**: Try known keys (0x2e, 0x69) or brute-force 4-byte key
5. **Config Parsing**: Parse decrypted TLV entries for C2 and operational settings
6. **IOC Extraction**: Extract domains, IPs, URIs, user agents, watermarks

## Workflow 2: Memory Dump Beacon Extraction

```
[Memory Dump] --> [Volatility3 malfind] --> [Dump Injected Regions] --> [Parse Config]
                                                                            |
                                                                            v
                                                                   [C2 Infrastructure Map]
```

### Steps:
1. **Acquisition**: Capture memory dump from compromised system
2. **Process Scan**: Use Volatility3 to identify suspicious processes
3. **Injection Detection**: Use malfind to find RWX memory regions
4. **Region Extraction**: Dump injected memory regions to files
5. **Config Search**: Scan dumps for beacon configuration signatures
6. **Infrastructure Mapping**: Correlate extracted C2 with network logs

## Workflow 3: Watermark Attribution

```
[Multiple Beacons] --> [Extract Watermarks] --> [Cluster by Watermark] --> [Attribution]
                                                                               |
                                                                               v
                                                                     [Campaign Correlation]
```

### Steps:
1. **Collection**: Gather beacon samples from incident or threat intel feeds
2. **Watermark Extraction**: Extract watermark value from each sample
3. **Database Lookup**: Check watermark against known databases
4. **Clustering**: Group beacons sharing the same watermark
5. **Infrastructure Overlap**: Correlate C2 infrastructure across cluster
6. **Attribution Assessment**: Link to known threat actor or cracked license

## Workflow 4: C2 Traffic Detection

```
[Beacon Config] --> [Extract C2 Profile] --> [Generate Signatures] --> [Deploy to NIDS]
                                                                            |
                                                                            v
                                                                   [Monitor Network Traffic]
```

### Steps:
1. **Profile Extraction**: Parse malleable C2 profile from beacon config
2. **Pattern Identification**: Identify unique HTTP headers, URIs, and encoding
3. **Signature Creation**: Write Suricata/Snort rules matching C2 patterns
4. **Deployment**: Deploy signatures to network detection infrastructure
5. **Validation**: Test signatures against captured beacon traffic
6. **Monitoring**: Alert on matching network flows for active beacons

scripts/agent.py

IN BUNDLE
#!/usr/bin/env python3
"""Cobalt Strike beacon configuration extraction and analysis agent.

Extracts C2 configuration from beacon payloads including server addresses,
communication settings, malleable C2 profile details, and watermark values.
"""

import struct
import os
import sys
import hashlib
from collections import OrderedDict

# Cobalt Strike beacon configuration field IDs (Type-Length-Value format)
BEACON_CONFIG_FIELDS = {
    1: ("BeaconType", "short"),
    2: ("Port", "short"),
    3: ("SleepTime", "int"),
    4: ("MaxGetSize", "int"),
    5: ("Jitter", "short"),
    7: ("PublicKey", "bytes"),
    8: ("C2Server", "str"),
    9: ("UserAgent", "str"),
    10: ("PostURI", "str"),
    11: ("Malleable_C2_Instructions", "bytes"),
    12: ("HttpGet_Metadata", "bytes"),
    13: ("HttpPost_Metadata", "bytes"),
    14: ("SpawnToX86", "str"),
    15: ("SpawnToX64", "str"),
    19: ("CryptoScheme", "short"),
    26: ("GetVerb", "str"),
    27: ("PostVerb", "str"),
    28: ("HttpPostChunk", "int"),
    29: ("Spawnto_x86", "str"),
    30: ("Spawnto_x64", "str"),
    31: ("CryptoScheme2", "str"),
    37: ("Watermark", "int"),
    38: ("StageCleanup", "short"),
    39: ("CFGCaution", "short"),
    43: ("DNS_Idle", "int"),
    44: ("DNS_Sleep", "int"),
    50: ("HostHeader", "str"),
    54: ("PipeName", "str"),
}

BEACON_TYPES = {0: "HTTP", 1: "Hybrid HTTP/DNS", 2: "SMB", 4: "TCP", 8: "HTTPS", 16: "DNS over HTTPS"}

XOR_KEY_V3 = 0x69
XOR_KEY_V4 = 0x2E


def compute_hash(filepath):
    """Compute SHA-256 hash of file."""
    sha256 = hashlib.sha256()
    with open(filepath, "rb") as f:
        for chunk in iter(lambda: f.read(65536), b""):
            sha256.update(chunk)
    return sha256.hexdigest()


def find_config_offset(data):
    """Find the beacon configuration blob in PE data or shellcode."""
    # Look for XOR-encoded config patterns
    for xor_key in [XOR_KEY_V3, XOR_KEY_V4]:
        # Config starts with 0x0001 (BeaconType field ID) XOR-encoded
        encoded_marker = bytes([0x00 ^ xor_key, 0x01 ^ xor_key, 0x00 ^ xor_key, 0x01 ^ xor_key])
        offset = data.find(encoded_marker)
        if offset != -1:
            return offset, xor_key
    # Try unencoded
    for offset in range(len(data) - 100):
        if data[offset:offset+4] == b"\x00\x01\x00\x01":
            return offset, None
    return -1, None


def xor_decode(data, key):
    """XOR decode data with single byte key."""
    if key is None:
        return data
    return bytes(b ^ key for b in data)


def parse_config_field(data, offset):
    """Parse a single TLV config field."""
    if offset + 6 > len(data):
        return None, None, None, offset
    field_id = struct.unpack_from(">H", data, offset)[0]
    field_type = struct.unpack_from(">H", data, offset + 2)[0]
    if field_type == 1:  # short
        value = struct.unpack_from(">H", data, offset + 4)[0]
        return field_id, "short", value, offset + 6
    elif field_type == 2:  # int
        value = struct.unpack_from(">I", data, offset + 4)[0]
        return field_id, "int", value, offset + 8
    elif field_type == 3:  # str/bytes
        length = struct.unpack_from(">H", data, offset + 4)[0]
        if offset + 6 + length > len(data):
            return None, None, None, offset
        value = data[offset + 6:offset + 6 + length]
        return field_id, "str", value, offset + 6 + length
    return None, None, None, offset + 2


def extract_beacon_config(filepath):
    """Extract and parse Cobalt Strike beacon configuration."""
    with open(filepath, "rb") as f:
        data = f.read()

    config_offset, xor_key = find_config_offset(data)
    if config_offset == -1:
        return {"error": "No beacon configuration found", "file": filepath}

    config_data = xor_decode(data[config_offset:config_offset + 4096], xor_key)
    config = OrderedDict()
    config["_meta"] = {
        "config_offset": f"0x{config_offset:08X}",
        "xor_key": f"0x{xor_key:02X}" if xor_key else "none",
        "version_guess": "4.x" if xor_key == XOR_KEY_V4 else "3.x" if xor_key == XOR_KEY_V3 else "unknown",
    }

    offset = 0
    max_fields = 100
    parsed = 0
    while offset < len(config_data) - 4 and parsed < max_fields:
        field_id, field_type, value, new_offset = parse_config_field(config_data, offset)
        if field_id is None or new_offset == offset:
            break
        offset = new_offset
        parsed += 1

        field_info = BEACON_CONFIG_FIELDS.get(field_id)
        if field_info:
            field_name, expected_type = field_info
            if isinstance(value, bytes):
                try:
                    str_value = value.rstrip(b"\x00").decode("utf-8", errors="replace")
                    config[field_name] = str_value
                except Exception:
                    config[field_name] = value.hex()[:100]
            elif field_id == 1:
                config[field_name] = BEACON_TYPES.get(value, f"Unknown({value})")
            else:
                config[field_name] = value

    return config


def extract_c2_indicators(config):
    """Extract C2 indicators from parsed config for threat intelligence."""
    indicators = {"c2_servers": [], "user_agents": [], "uris": [],
                  "pipes": [], "watermark": None, "dns": []}
    c2 = config.get("C2Server", "")
    if c2:
        for server in c2.split(","):
            server = server.strip().rstrip("/")
            if server:
                indicators["c2_servers"].append(server)
    ua = config.get("UserAgent", "")
    if ua:
        indicators["user_agents"].append(ua)
    for key in ["PostURI"]:
        uri = config.get(key, "")
        if uri:
            indicators["uris"].append(uri)
    pipe = config.get("PipeName", "")
    if pipe:
        indicators["pipes"].append(pipe)
    wm = config.get("Watermark")
    if wm:
        indicators["watermark"] = wm
    return indicators


def assess_operator_opsec(config):
    """Assess operator OPSEC based on beacon configuration."""
    findings = []
    sleep = config.get("SleepTime", 0)
    jitter = config.get("Jitter", 0)
    if sleep < 30000:
        findings.append({"level": "INFO", "detail": f"Low sleep time: {sleep}ms - high beacon frequency"})
    if jitter == 0:
        findings.append({"level": "WARN", "detail": "No jitter configured - predictable beacon interval"})
    ua = config.get("UserAgent", "")
    if "Mozilla" not in ua and ua:
        findings.append({"level": "WARN", "detail": f"Non-standard User-Agent: {ua[:60]}"})
    spawn86 = config.get("SpawnToX86", config.get("Spawnto_x86", ""))
    if "rundll32" in spawn86.lower():
        findings.append({"level": "INFO", "detail": "Default spawn-to process (rundll32) - easy to detect"})
    cleanup = config.get("StageCleanup", 0)
    if cleanup == 0:
        findings.append({"level": "INFO", "detail": "Stage cleanup disabled - beacon stub remains in memory"})
    return findings


if __name__ == "__main__":
    print("=" * 60)
    print("Cobalt Strike Beacon Configuration Extractor")
    print("C2 extraction, watermark analysis, OPSEC assessment")
    print("=" * 60)

    target = sys.argv[1] if len(sys.argv) > 1 else None

    if not target or not os.path.exists(target):
        print("\n[DEMO] Usage: python agent.py <beacon_sample.exe>")
        print("  Extracts: C2 servers, sleep/jitter, watermark, malleable profile")
        sys.exit(0)

    print(f"\n[*] Analyzing: {target}")
    print(f"[*] SHA-256: {compute_hash(target)}")
    print(f"[*] Size: {os.path.getsize(target)} bytes")

    config = extract_beacon_config(target)

    if "error" in config:
        print(f"\n[!] {config['error']}")
        sys.exit(1)

    print("\n--- Beacon Configuration ---")
    for key, value in config.items():
        if key == "_meta":
            for mk, mv in value.items():
                print(f"  {mk}: {mv}")
        else:
            print(f"  {key}: {value}")

    indicators = extract_c2_indicators(config)
    print("\n--- C2 Indicators ---")
    for c2 in indicators["c2_servers"]:
        print(f"  [C2] {c2}")
    if indicators["watermark"]:
        print(f"  [Watermark] {indicators['watermark']}")
    for pipe in indicators["pipes"]:
        print(f"  [Pipe] {pipe}")

    opsec = assess_operator_opsec(config)
    print("\n--- Operator OPSEC Assessment ---")
    for f in opsec:
        print(f"  [{f['level']}] {f['detail']}")

scripts/process.py

IN BUNDLE
#!/usr/bin/env python3
"""
Cobalt Strike Beacon Configuration Analyzer

Extracts and analyzes beacon configurations from PE files, shellcode,
and memory dumps using dissect.cobaltstrike and manual parsing.

Requirements:
    pip install dissect.cobaltstrike pefile yara-python

Usage:
    python process.py --file beacon.exe --output report.json
    python process.py --file memdump.bin --scan-memory
    python process.py --directory ./samples --batch
"""

import argparse
import json
import os
import struct
import sys
from collections import defaultdict
from datetime import datetime
from pathlib import Path

try:
    from dissect.cobaltstrike.beacon import BeaconConfig
except ImportError:
    print("ERROR: dissect.cobaltstrike not installed.")
    print("Run: pip install dissect.cobaltstrike")
    sys.exit(1)


# TLV field type mapping
TLV_FIELDS = {
    0x0001: ("BeaconType", "short"),
    0x0002: ("Port", "short"),
    0x0003: ("SleepTime", "int"),
    0x0004: ("MaxGetSize", "int"),
    0x0005: ("Jitter", "short"),
    0x0006: ("MaxDNS", "short"),
    0x0008: ("C2Server", "str"),
    0x0009: ("UserAgent", "str"),
    0x000a: ("PostURI", "str"),
    0x000b: ("Malleable_C2_Instructions", "blob"),
    0x000d: ("SpawnTo_x86", "str"),
    0x000e: ("SpawnTo_x64", "str"),
    0x000f: ("CryptoScheme", "short"),
    0x001a: ("Watermark", "int"),
    0x001d: ("HostHeader", "str"),
    0x0024: ("PipeName", "str"),
    0x0025: ("Year", "short"),
    0x0026: ("Month", "short"),
    0x0027: ("Day", "short"),
    0x002c: ("ProxyHostname", "str"),
    0x002d: ("ProxyUsername", "str"),
    0x002e: ("ProxyPassword", "str"),
}

BEACON_TYPES = {
    0: "HTTP",
    1: "Hybrid HTTP/DNS",
    2: "SMB",
    4: "TCP",
    8: "HTTPS",
    10: "TCP Bind",
    14: "External C2",
}


class BeaconAnalyzer:
    """Analyze Cobalt Strike beacon configurations."""

    def __init__(self):
        self.results = []

    def analyze_file(self, filepath):
        """Extract beacon config from a file."""
        filepath = Path(filepath)
        if not filepath.exists():
            print(f"[-] File not found: {filepath}")
            return None

        print(f"[*] Analyzing: {filepath}")

        # Try dissect.cobaltstrike first
        result = self._extract_with_dissect(filepath)

        # Fall back to manual extraction
        if not result:
            result = self._extract_manual(filepath)

        if result:
            result["source_file"] = str(filepath)
            result["analysis_time"] = datetime.now().isoformat()
            self.results.append(result)

        return result

    def _extract_with_dissect(self, filepath):
        """Extract config using dissect.cobaltstrike library."""
        try:
            configs = list(BeaconConfig.from_path(filepath))
            if not configs:
                return None

            config = configs[0]
            settings = config.as_dict()

            result = {
                "method": "dissect.cobaltstrike",
                "config": {},
                "indicators": {},
            }

            for key, value in settings.items():
                if value is not None:
                    result["config"][key] = str(value)

            result["indicators"] = self._extract_indicators(settings)
            return result

        except Exception as e:
            print(f"  [!] dissect extraction failed: {e}")
            return None

    def _extract_manual(self, filepath):
        """Manual XOR-based config extraction."""
        try:
            with open(filepath, "rb") as f:
                data = f.read()
        except Exception as e:
            print(f"  [!] Read failed: {e}")
            return None

        for xor_key in [0x2e, 0x69]:
            # Search for XOR'd config start marker
            magic = bytes([0x00 ^ xor_key, 0x01 ^ xor_key,
                           0x00 ^ xor_key, 0x02 ^ xor_key])

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

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

            config_blob = data[offset:offset + 4096]
            decrypted = bytes([b ^ xor_key for b in config_blob])

            entries = self._parse_tlv(decrypted)
            if entries:
                return {
                    "method": "manual_xor",
                    "xor_key": f"0x{xor_key:02x}",
                    "config_offset": f"0x{offset:x}",
                    "config": entries,
                    "indicators": self._extract_indicators(entries),
                }

        return None

    def _parse_tlv(self, data):
        """Parse TLV configuration entries."""
        entries = {}
        offset = 0

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

            if entry_type == 0 or entry_len > 4096:
                break

            value_data = data[offset+6:offset+6+entry_len]
            field_info = TLV_FIELDS.get(entry_type)

            if field_info:
                field_name, expected_type = field_info
            else:
                field_name = f"Unknown_0x{entry_type:04x}"
                expected_type = "blob"

            if data_type == 1 and len(value_data) >= 2:
                value = struct.unpack(">H", value_data[:2])[0]
            elif data_type == 2 and len(value_data) >= 4:
                value = struct.unpack(">I", value_data[:4])[0]
            elif data_type == 3:
                value = value_data.rstrip(b'\x00').decode('utf-8', errors='replace')
            else:
                value = value_data.hex()

            # Resolve beacon type names
            if field_name == "BeaconType" and isinstance(value, int):
                value = BEACON_TYPES.get(value, f"Unknown ({value})")

            entries[field_name] = value
            offset += 6 + entry_len

        return entries

    def _extract_indicators(self, config):
        """Extract IOCs from parsed configuration."""
        indicators = {
            "c2_servers": [],
            "user_agent": "",
            "named_pipes": [],
            "spawn_processes": [],
            "watermark": "",
            "beacon_type": "",
            "sleep_time_ms": 0,
            "jitter_pct": 0,
        }

        # Handle both dissect dict keys and manual parse keys
        c2_keys = ["SETTING_DOMAINS", "C2Server"]
        for key in c2_keys:
            domains = config.get(key, "")
            if domains:
                for d in str(domains).split(","):
                    d = d.strip().rstrip("/")
                    if d:
                        indicators["c2_servers"].append(d)

        ua_keys = ["SETTING_USERAGENT", "UserAgent"]
        for key in ua_keys:
            ua = config.get(key, "")
            if ua:
                indicators["user_agent"] = str(ua)

        pipe_keys = ["SETTING_PIPENAME", "PipeName"]
        for key in pipe_keys:
            pipe = config.get(key, "")
            if pipe:
                indicators["named_pipes"].append(str(pipe))

        spawn_keys = [
            ("SETTING_SPAWNTO_X86", "SpawnTo_x86"),
            ("SETTING_SPAWNTO_X64", "SpawnTo_x64"),
        ]
        for dissect_key, manual_key in spawn_keys:
            for key in [dissect_key, manual_key]:
                proc = config.get(key, "")
                if proc:
                    indicators["spawn_processes"].append(str(proc))

        wm_keys = ["SETTING_WATERMARK", "Watermark"]
        for key in wm_keys:
            wm = config.get(key, "")
            if wm:
                indicators["watermark"] = str(wm)

        return indicators

    def batch_analyze(self, directory):
        """Analyze all files in a directory."""
        directory = Path(directory)
        extensions = {".exe", ".dll", ".bin", ".dmp", ".raw"}

        for filepath in directory.rglob("*"):
            if filepath.suffix.lower() in extensions:
                self.analyze_file(filepath)

        return self.results

    def cluster_by_watermark(self):
        """Cluster analyzed beacons by watermark."""
        clusters = defaultdict(list)

        for result in self.results:
            wm = result.get("indicators", {}).get("watermark", "unknown")
            clusters[wm].append(result.get("source_file", "unknown"))

        return dict(clusters)

    def generate_report(self, output_path=None):
        """Generate JSON analysis report."""
        report = {
            "analysis_date": datetime.now().isoformat(),
            "total_beacons": len(self.results),
            "watermark_clusters": self.cluster_by_watermark(),
            "all_c2_servers": list(set(
                server
                for r in self.results
                for server in r.get("indicators", {}).get("c2_servers", [])
            )),
            "results": self.results,
        }

        if output_path:
            with open(output_path, "w") as f:
                json.dump(report, f, indent=2, default=str)
            print(f"[+] Report saved to {output_path}")

        return report


def main():
    parser = argparse.ArgumentParser(
        description="Cobalt Strike Beacon Configuration Analyzer"
    )
    parser.add_argument("--file", help="Single file to analyze")
    parser.add_argument("--directory", help="Directory for batch analysis")
    parser.add_argument("--output", default="beacon_report.json",
                        help="Output report path")
    parser.add_argument("--scan-memory", action="store_true",
                        help="Treat input as raw memory dump")
    parser.add_argument("--batch", action="store_true",
                        help="Batch analyze directory")

    args = parser.parse_args()
    analyzer = BeaconAnalyzer()

    if args.file:
        result = analyzer.analyze_file(args.file)
        if result:
            print(json.dumps(result, indent=2, default=str))

    elif args.directory and args.batch:
        results = analyzer.batch_analyze(args.directory)
        print(f"\n[+] Analyzed {len(results)} beacons")

    else:
        parser.print_help()
        sys.exit(1)

    report = analyzer.generate_report(args.output)
    print(f"\n[+] Total C2 servers found: {len(report['all_c2_servers'])}")
    for server in report["all_c2_servers"]:
        print(f"    {server}")


if __name__ == "__main__":
    main()
SKILL GRID · 上传 ZIP 或 GitHub 链接,把技能变成一张可分享的卡 ■■□■ GOOGLE 四色 · PIXEL DECK