red teaming

Conducting Internal Reconnaissance with BloodHound CE

Conduct internal Active Directory reconnaissance using BloodHound Community Edition to map attack paths, identify privilege escalation chains, and discover misconfigurations in domain environments.

active-directoryattack-pathsbloodhoundgraph-analysisprivilege-escalationreconnaissancered-team
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

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

Overview

BloodHound Community Edition (CE) is a modern, web-based Active Directory reconnaissance platform developed by SpecterOps that uses graph theory to reveal hidden relationships and attack paths within AD environments. Unlike the legacy BloodHound application, BloodHound CE uses a PostgreSQL backend with a dedicated graph database, providing improved performance, a modern web UI, and enhanced API capabilities. Red teams use BloodHound CE to collect AD objects, ACLs, sessions, group memberships, and trust relationships, then visualize attack paths from compromised low-privileged accounts to high-value targets like Domain Admins. The SharpHound collector (v2 for CE) gathers data from Active Directory, while AzureHound collects from Azure AD / Entra ID environments.

When to Use

  • When conducting security assessments that involve conducting internal reconnaissance with bloodhound ce
  • When following incident response procedures for related security events
  • When performing scheduled security testing or auditing activities
  • When validating security controls through hands-on testing

Prerequisites

  • Familiarity with red teaming concepts and tools
  • Access to a test or lab environment for safe execution
  • Python 3.8+ with required dependencies installed
  • Appropriate authorization for any testing activities

Objectives

  • Deploy BloodHound CE server using Docker Compose
  • Collect AD data using SharpHound v2 or BloodHound.py
  • Import collected data into BloodHound CE for graph analysis
  • Identify shortest attack paths from owned principals to Domain Admins
  • Discover ACL-based attack paths, Kerberoastable accounts, and delegation abuse
  • Execute custom Cypher queries for advanced attack path analysis
  • Generate attack path reports for engagement documentation

MITRE ATT&CK Mapping

  • T1087.002 - Account Discovery: Domain Account
  • T1069.002 - Permission Groups Discovery: Domain Groups
  • T1482 - Domain Trust Discovery
  • T1615 - Group Policy Discovery
  • T1018 - Remote System Discovery
  • T1033 - System Owner/User Discovery
  • T1016 - System Network Configuration Discovery

Workflow

Phase 1: BloodHound CE Deployment

  1. Deploy BloodHound CE using Docker Compose:
    curl -L https://ghst.ly/getbhce -o docker-compose.yml
    docker compose pull
    docker compose up -d
  2. Access the web interface at https://localhost:8080
  3. Log in with the default admin credentials (displayed in Docker logs):
    docker compose logs | grep "Initial Password"
  4. Change the default admin password immediately

Phase 2: Data Collection with SharpHound v2

  1. Transfer SharpHound v2 to the compromised Windows host:
    # Execute full collection
    .\SharpHound.exe -c All --outputdirectory C:\Temp
     
    # DCOnly collection (LDAP only, stealthier)
    .\SharpHound.exe -c DCOnly
     
    # Session collection for logged-on user mapping
    .\SharpHound.exe -c Session --loop --loopduration 02:00:00
     
    # Collect from specific domain
    .\SharpHound.exe -c All -d child.domain.local
  2. Alternative: Use BloodHound.py from Linux:
    bloodhound-python -u user -p 'Password123' -d domain.local -ns 10.10.10.1 -c All
  3. Exfiltrate the generated ZIP file to the analysis workstation

Phase 3: Data Import and Initial Analysis

  1. Upload collected data via the BloodHound CE web interface (File Ingest)
  2. Mark compromised accounts as "Owned" in the interface
  3. Run built-in analysis queries:
    • Shortest Path to Domain Admin
    • Kerberoastable Users with Path to DA
    • AS-REP Roastable Users
    • Users with DCSync Rights
    • Computers with Unconstrained Delegation

Phase 4: Custom Cypher Queries

  1. Execute custom Cypher queries in the BloodHound CE search bar:
    // Find shortest path from owned principals to Domain Admins
    MATCH p=shortestPath((n {owned:true})-[*1..]->(m:Group {name:"DOMAIN ADMINS@DOMAIN.LOCAL"}))
    RETURN p
     
    // Find Kerberoastable users with path to DA
    MATCH (u:User {hasspn:true})
    MATCH p=shortestPath((u)-[*1..]->(g:Group {name:"DOMAIN ADMINS@DOMAIN.LOCAL"}))
    RETURN p
     
    // Find computers with sessions of DA members
    MATCH (c:Computer)-[:HasSession]->(u:User)-[:MemberOf*1..]->(g:Group {name:"DOMAIN ADMINS@DOMAIN.LOCAL"})
    RETURN c.name, u.name
     
    // Find ACL-based attack paths (GenericAll, WriteDACL, GenericWrite)
    MATCH p=(u:User)-[:GenericAll|GenericWrite|WriteDacl|WriteOwner|ForceChangePassword*1..]->(t)
    WHERE u.owned = true
    RETURN p
     
    // Find users who can DCSync
    MATCH (u)-[:MemberOf*0..]->()-[:DCSync|GetChanges|GetChangesAll*1..]->(d:Domain)
    RETURN u.name, d.name
     
    // Find computers with LAPS but readable by non-admins
    MATCH (c:Computer {haslaps:true})
    MATCH p=(u:User)-[:ReadLAPSPassword]->(c)
    RETURN p

Phase 5: Attack Path Prioritization

  1. Score identified attack paths by:
    • Number of hops (shorter = higher priority)
    • Stealth requirements (avoid noisy techniques)
    • Tool availability for each hop
    • Likelihood of detection at each step
  2. Create an execution plan for the highest-priority paths
  3. Identify required tools for each step in the chain
  4. Plan OPSEC considerations for each technique

Tools and Resources

Tool Purpose Platform
BloodHound CE Web-based graph analysis platform Docker
SharpHound v2 AD data collection (.NET, for CE) Windows
BloodHound.py AD data collection (Python) Linux
AzureHound Azure AD / Entra ID data collection Cross-platform
PlumHound Automated BloodHound reporting Python
BloodHound Query Library Community Cypher query repository Web

Key Attack Path Types

Path Type Description Example
ACL Abuse Exploit misconfigured ACLs GenericAll on DA group
Kerberoasting Crack service account passwords SPN account → DA
AS-REP Roasting Attack accounts without pre-auth No-preauth user → password crack
Delegation Abuse Exploit unconstrained/constrained delegation Computer → impersonate DA
GPO Abuse Modify GPOs applied to privileged OUs GPO write → code execution on DA
Session Hijack Leverage DA sessions on compromised hosts Admin session → token theft

Validation Criteria

  • BloodHound CE deployed and accessible
  • SharpHound v2 data collected from all domains in scope
  • Data successfully imported into BloodHound CE
  • Owned principals marked in the interface
  • Shortest paths to Domain Admin identified
  • ACL-based attack paths documented
  • Kerberoastable and AS-REP roastable accounts listed
  • Custom Cypher queries executed for advanced analysis
  • Attack paths prioritized by feasibility and stealth
  • Report generated with all identified paths and evidence
Source materials

References and resources

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

References 3

api-reference.md1.8 KB

BloodHound CE Reconnaissance — API Reference

Libraries

Library Install Purpose
neo4j pip install neo4j Neo4j graph database driver for Cypher queries
bloodhound pip install bloodhound Python ingestor for AD data collection
requests pip install requests BloodHound CE REST API client

Key neo4j Driver Methods

Method Description
GraphDatabase.driver(uri, auth=(user, pass)) Connect to Neo4j
driver.session() Open a session for queries
session.run(cypher, **params) Execute Cypher query
driver.close() Close driver connection

Critical Cypher Queries

Query Purpose Cypher Pattern
Path to DA MATCH p=shortestPath((u:User)-[*1..]->(g:Group {name:"DOMAIN ADMINS@..."}))
Kerberoastable MATCH (u:User) WHERE u.hasspn = true AND u.enabled = true
Unconstrained Delegation MATCH (c:Computer) WHERE c.unconstraineddelegation = true
AS-REP Roastable MATCH (u:User) WHERE u.dontreqpreauth = true
DCSync rights `MATCH p=(u)-[:GetChanges

BloodHound Python Ingestor

bloodhound-python -d domain.local -u user -p pass -ns DC_IP -c all --zip

Collection methods: all, group, localadmin, session, trusts, objectprops, acl

MITRE ATT&CK Mapping

Technique ID
Account Discovery T1087
Permission Groups Discovery T1069
Domain Trust Discovery T1482

External References

standards.md1.1 KB

Standards and References - BloodHound CE Reconnaissance

MITRE ATT&CK References

Technique ID Name Tactic
T1087.002 Account Discovery: Domain Account Discovery
T1069.002 Permission Groups Discovery: Domain Groups Discovery
T1482 Domain Trust Discovery Discovery
T1615 Group Policy Discovery Discovery
T1018 Remote System Discovery Discovery
T1033 System Owner/User Discovery Discovery
T1016 System Network Configuration Discovery Discovery

Official Resources

Key Research

  • SpecterOps: An Ace in the Hole - Stealthy Data Collection with BloodHound
  • Compass Security: BloodHound Community Edition Custom Queries (2025)
  • SpecterOps: Introducing the BloodHound Query Library (2025)
workflows.md1.9 KB

Workflows - BloodHound CE Reconnaissance

Complete Reconnaissance Workflow

1. Deployment
   ├── Pull BloodHound CE Docker images
   ├── Start services with docker compose up -d
   ├── Access web UI and set admin password
   └── Verify API connectivity
 
2. Data Collection
   ├── Choose collector: SharpHound v2 (Windows) or BloodHound.py (Linux)
   ├── Run All collection method for comprehensive data
   ├── Run Session collection in loop for user mapping
   ├── Collect from all reachable domains
   └── Exfiltrate ZIP data to analysis workstation
 
3. Import and Setup
   ├── Upload ZIP files via BloodHound CE web interface
   ├── Wait for data processing to complete
   ├── Mark owned/compromised principals
   └── Set high-value targets
 
4. Analysis
   ├── Run built-in attack path queries
   ├── Execute custom Cypher queries
   ├── Identify ACL abuse opportunities
   ├── Map delegation configurations
   ├── Find Kerberoastable / AS-REP roastable accounts
   └── Discover GPO modification paths
 
5. Attack Planning
   ├── Prioritize paths by hop count and stealth
   ├── Identify tools needed per hop
   ├── Plan OPSEC for each technique
   └── Document execution plan
 
6. Reporting
   ├── Export graph visualizations
   ├── Generate path summaries
   ├── Document all findings with evidence
   └── Provide remediation recommendations

Stealthy Collection Workflow

Low-Noise Collection:
  1. DCOnly mode: Only queries domain controllers via LDAP
     SharpHound.exe -c DCOnly
 
  2. Targeted collection: Specific container/OU
     SharpHound.exe -c All --searchbase "OU=Servers,DC=domain,DC=local"
 
  3. Session loop: Passive session enumeration over time
     SharpHound.exe -c Session --loop --loopduration 04:00:00 --loopinterval 00:05:00

Scripts 2

agent.py5.3 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
# For authorized penetration testing and educational environments only.
# Usage against targets without prior mutual consent is illegal.
# It is the end user's responsibility to obey all applicable local, state and federal laws.
"""BloodHound CE reconnaissance agent using bloodhound Python ingestor and Neo4j."""

import json
import sys
import argparse
import subprocess
from datetime import datetime

try:
    from neo4j import GraphDatabase
except ImportError:
    print("Install: pip install neo4j")
    sys.exit(1)


def collect_bloodhound_data(domain, username, password, dc_ip, method="all"):
    """Run BloodHound Python ingestor to collect AD data."""
    cmd = [
        "bloodhound-python", "-d", domain, "-u", username, "-p", password,
        "-ns", dc_ip, "-c", method, "--zip",
    ]
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
        return {"status": "completed", "output": result.stdout[:1000]}
    except FileNotFoundError:
        return {"status": "error", "message": "Install: pip install bloodhound"}
    except subprocess.TimeoutExpired:
        return {"status": "timeout"}


def query_shortest_path_to_da(driver):
    """Find shortest path to Domain Admins."""
    with driver.session() as session:
        result = session.run(
            "MATCH p=shortestPath((u:User)-[*1..]->(g:Group {name: $group})) "
            "WHERE u.enabled = true RETURN u.name AS user, length(p) AS hops "
            "ORDER BY hops LIMIT 10",
            group="DOMAIN ADMINS@DOMAIN.LOCAL",
        )
        return [{"user": r["user"], "hops": r["hops"]} for r in result]


def query_kerberoastable_users(driver):
    """Find kerberoastable user accounts."""
    with driver.session() as session:
        result = session.run(
            "MATCH (u:User) WHERE u.hasspn = true AND u.enabled = true "
            "RETURN u.name AS user, u.serviceprincipalnames AS spns, "
            "u.admincount AS admin_count ORDER BY u.admincount DESC"
        )
        return [{"user": r["user"], "spns": r["spns"],
                 "admin": r["admin_count"]} for r in result]


def query_unconstrained_delegation(driver):
    """Find computers with unconstrained delegation."""
    with driver.session() as session:
        result = session.run(
            "MATCH (c:Computer) WHERE c.unconstraineddelegation = true "
            "RETURN c.name AS computer, c.operatingsystem AS os"
        )
        return [{"computer": r["computer"], "os": r["os"]} for r in result]


def query_as_rep_roastable(driver):
    """Find AS-REP roastable accounts (no pre-auth required)."""
    with driver.session() as session:
        result = session.run(
            "MATCH (u:User) WHERE u.dontreqpreauth = true AND u.enabled = true "
            "RETURN u.name AS user, u.admincount AS admin_count"
        )
        return [{"user": r["user"], "admin": r["admin_count"]} for r in result]


def run_recon(neo4j_uri, neo4j_user, neo4j_password):
    """Run BloodHound reconnaissance queries."""
    driver = GraphDatabase.driver(neo4j_uri, auth=(neo4j_user, neo4j_password))
    print(f"\n{'='*60}")
    print(f"  BLOODHOUND CE RECONNAISSANCE")
    print(f"  Generated: {datetime.utcnow().isoformat()} UTC")
    print(f"{'='*60}\n")

    paths = query_shortest_path_to_da(driver)
    print(f"--- SHORTEST PATHS TO DOMAIN ADMIN ({len(paths)}) ---")
    for p in paths:
        print(f"  {p['user']}: {p['hops']} hops")

    kerb = query_kerberoastable_users(driver)
    print(f"\n--- KERBEROASTABLE USERS ({len(kerb)}) ---")
    for k in kerb[:10]:
        print(f"  {k['user']} (admin={k['admin']})")

    deleg = query_unconstrained_delegation(driver)
    print(f"\n--- UNCONSTRAINED DELEGATION ({len(deleg)}) ---")
    for d in deleg:
        print(f"  {d['computer']}: {d['os']}")

    asrep = query_as_rep_roastable(driver)
    print(f"\n--- AS-REP ROASTABLE ({len(asrep)}) ---")
    for a in asrep:
        print(f"  {a['user']} (admin={a['admin']})")

    driver.close()
    return {"paths_to_da": paths, "kerberoastable": kerb,
            "unconstrained_delegation": deleg, "asrep_roastable": asrep}


def main():
    parser = argparse.ArgumentParser(description="BloodHound CE Recon Agent")
    parser.add_argument("--neo4j-uri", default="bolt://localhost:7687", help="Neo4j URI")
    parser.add_argument("--neo4j-user", default="neo4j", help="Neo4j username")
    parser.add_argument("--neo4j-password", required=True, help="Neo4j password")
    parser.add_argument("--collect", action="store_true", help="Run data collection first")
    parser.add_argument("--domain", help="AD domain for collection")
    parser.add_argument("--ad-user", help="AD username for collection")
    parser.add_argument("--ad-pass", help="AD password for collection")
    parser.add_argument("--dc-ip", help="Domain controller IP")
    parser.add_argument("--output", help="Save report to JSON file")
    args = parser.parse_args()

    if args.collect and args.domain:
        result = collect_bloodhound_data(args.domain, args.ad_user, args.ad_pass, args.dc_ip)
        print(json.dumps(result, indent=2))

    report = run_recon(args.neo4j_uri, args.neo4j_user, args.neo4j_password)
    if args.output:
        with open(args.output, "w") as f:
            json.dump(report, f, indent=2, default=str)
        print(f"\n[+] Report saved to {args.output}")


if __name__ == "__main__":
    main()
process.py7.3 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
BloodHound CE Attack Path Analysis Script

Processes BloodHound CE data exports and generates prioritized
attack path reports. For authorized red team engagements only.
"""

import json
import sys
import os
from datetime import datetime
from collections import defaultdict


def load_bloodhound_data(filepath: str) -> dict:
    """Load BloodHound CE exported JSON data."""
    try:
        with open(filepath, "r") as f:
            return json.load(f)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        print(f"Error loading data: {e}")
        return {}


def analyze_users(data: dict) -> dict:
    """Analyze user objects for attack opportunities."""
    analysis = {
        "total_users": 0,
        "enabled_users": 0,
        "kerberoastable": [],
        "asreproastable": [],
        "dcsync_capable": [],
        "admin_count_set": [],
        "password_not_required": [],
        "unconstrained_delegation": []
    }

    users = data.get("data", data.get("users", []))
    if isinstance(users, list):
        for user in users:
            props = user.get("Properties", user.get("properties", {}))
            name = props.get("name", props.get("samaccountname", "Unknown"))
            analysis["total_users"] += 1

            if props.get("enabled", True):
                analysis["enabled_users"] += 1

            if props.get("hasspn", False):
                analysis["kerberoastable"].append(name)

            if not props.get("dontreqpreauth", True) is False:
                if props.get("dontreqpreauth", False):
                    analysis["asreproastable"].append(name)

            if props.get("admincount", False):
                analysis["admin_count_set"].append(name)

            if props.get("passwordnotreqd", False):
                analysis["password_not_required"].append(name)

    return analysis


def analyze_computers(data: dict) -> dict:
    """Analyze computer objects for attack opportunities."""
    analysis = {
        "total_computers": 0,
        "unconstrained_delegation": [],
        "constrained_delegation": [],
        "laps_enabled": [],
        "laps_disabled": [],
        "unsupported_os": [],
        "domain_controllers": []
    }

    computers = data.get("data", data.get("computers", []))
    if isinstance(computers, list):
        for computer in computers:
            props = computer.get("Properties", computer.get("properties", {}))
            name = props.get("name", "Unknown")
            analysis["total_computers"] += 1

            if props.get("unconstraineddelegation", False):
                analysis["unconstrained_delegation"].append(name)

            if props.get("allowedtodelegate", []):
                analysis["constrained_delegation"].append({
                    "name": name,
                    "delegates_to": props.get("allowedtodelegate", [])
                })

            if props.get("haslaps", False):
                analysis["laps_enabled"].append(name)
            else:
                analysis["laps_disabled"].append(name)

            os_name = props.get("operatingsystem", "").lower()
            unsupported = ["2003", "2008", "xp", "vista", "windows 7"]
            if any(ver in os_name for ver in unsupported):
                analysis["unsupported_os"].append({
                    "name": name,
                    "os": props.get("operatingsystem", "Unknown")
                })

            if props.get("isdc", False):
                analysis["domain_controllers"].append(name)

    return analysis


def generate_report(user_analysis: dict, computer_analysis: dict) -> str:
    """Generate a comprehensive attack path analysis report."""
    report = [
        "=" * 70,
        "BloodHound CE Attack Path Analysis Report",
        f"Generated: {datetime.now().isoformat()}",
        "=" * 70,
        "",
        "[User Analysis]",
        f"  Total Users: {user_analysis['total_users']}",
        f"  Enabled Users: {user_analysis['enabled_users']}",
        f"  Kerberoastable: {len(user_analysis['kerberoastable'])}",
        f"  AS-REP Roastable: {len(user_analysis['asreproastable'])}",
        f"  AdminCount Set: {len(user_analysis['admin_count_set'])}",
        f"  Password Not Required: {len(user_analysis['password_not_required'])}",
        ""
    ]

    if user_analysis["kerberoastable"]:
        report.append("  Kerberoastable Accounts:")
        for acct in user_analysis["kerberoastable"][:20]:
            report.append(f"    - {acct}")

    if user_analysis["asreproastable"]:
        report.append("  AS-REP Roastable Accounts:")
        for acct in user_analysis["asreproastable"][:20]:
            report.append(f"    - {acct}")

    report.extend([
        "",
        "[Computer Analysis]",
        f"  Total Computers: {computer_analysis['total_computers']}",
        f"  Domain Controllers: {len(computer_analysis['domain_controllers'])}",
        f"  Unconstrained Delegation: {len(computer_analysis['unconstrained_delegation'])}",
        f"  Constrained Delegation: {len(computer_analysis['constrained_delegation'])}",
        f"  LAPS Enabled: {len(computer_analysis['laps_enabled'])}",
        f"  LAPS Disabled: {len(computer_analysis['laps_disabled'])}",
        f"  Unsupported OS: {len(computer_analysis['unsupported_os'])}",
        ""
    ])

    if computer_analysis["unconstrained_delegation"]:
        report.append("  Unconstrained Delegation Computers:")
        for comp in computer_analysis["unconstrained_delegation"]:
            report.append(f"    - {comp}")

    if computer_analysis["unsupported_os"]:
        report.append("  Unsupported Operating Systems:")
        for comp in computer_analysis["unsupported_os"]:
            report.append(f"    - {comp['name']}: {comp['os']}")

    report.extend([
        "",
        "[Priority Attack Vectors]",
        "  1. Kerberoastable accounts with path to DA (crack SPN passwords)",
        "  2. AS-REP Roastable accounts (offline password cracking)",
        "  3. Unconstrained delegation abuse (TGT theft via coercion)",
        "  4. ACL-based paths (GenericAll, WriteDACL, ForceChangePassword)",
        "  5. GPO modification paths (code execution on privileged OUs)",
        "  6. Unsupported OS exploitation (unpatched vulnerabilities)",
        "",
        "=" * 70
    ])

    return "\n".join(report)


def main():
    """Main entry point."""
    if len(sys.argv) < 2:
        print("Usage: python process.py <bloodhound_users.json> [bloodhound_computers.json]")
        return

    users_file = sys.argv[1]
    computers_file = sys.argv[2] if len(sys.argv) > 2 else None

    user_data = load_bloodhound_data(users_file)
    user_analysis = analyze_users(user_data)

    computer_analysis = {
        "total_computers": 0, "unconstrained_delegation": [],
        "constrained_delegation": [], "laps_enabled": [], "laps_disabled": [],
        "unsupported_os": [], "domain_controllers": []
    }

    if computers_file:
        computer_data = load_bloodhound_data(computers_file)
        computer_analysis = analyze_computers(computer_data)

    report = generate_report(user_analysis, computer_analysis)
    print(report)

    report_file = f"bloodhound_analysis_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
    with open(report_file, "w") as f:
        f.write(report)
    print(f"\nReport saved to: {report_file}")


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 1.0 KB
Keep exploring