Saltar a contenido

SharpHound hoja de trucos

Overview

SharpHound is the official data collector for BloodHound, designed to gather information from Active Directory environments. It collects various types of data including domain trusts, local admin rights, sesión information, group memberships, and ACLs to help identify attack paths and escalada de privilegios oppuertounities in Active Directory environments.

⚠️ Warning: Only use SharpHound in environments you own or have explicit permission to test. Unauthorized use may violate terms of servicio or local laws.

instalación

Pre-compiled Binaries

# Download latest release from GitHub
wget https://github.com/BloodHoundAD/SharpHound/releases/latest/download/SharpHound.exe

# Download specific version
wget https://github.com/BloodHoundAD/SharpHound/releases/download/v1.1.1/SharpHound.exe

# Download PowerShell version
wget https://github.com/BloodHoundAD/BloodHound/raw/master/Collectors/SharpHound.ps1

Building from Source

# Clone repository
git clone https://github.com/BloodHoundAD/SharpHound.git
cd SharpHound

# Build with .NET Framework
msbuild SharpHound.sln /p:configuración=Release

# Build with .NET Core
dotnet build -c Release

# Output location
ls bin/Release/net*/SharpHound.exe

PowerShell Module instalación

# Impuerto PowerShell module
Impuerto-Module .\SharpHound.ps1

# Alternative: Download and execute in memory
IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/BloodHoundAD/BloodHound/master/Collectors/SharpHound.ps1')

# Bypass execution policy if needed
powershell -ExecutionPolicy Bypass -File SharpHound.ps1

Basic uso

Standard Collection

# Basic collection (default: Default collection method)
SharpHound.exe

# Specify collection methods
SharpHound.exe -c All
SharpHound.exe -c Default,GPOLocalGroup
SharpHound.exe -c sesión,LoggedOn,Trusts

# Collection with domain specification
SharpHound.exe -d ejemplo.com
SharpHound.exe -d ejemplo.com -c All

# Collection with specific domain controller
SharpHound.exe -d ejemplo.com -s dc01.ejemplo.com

PowerShell uso

# Basic PowerShell collection
Invoke-BloodHound

# Collection with specific methods
Invoke-BloodHound -CollectionMethod All
Invoke-BloodHound -CollectionMethod Default,sesión,Trusts

# Collection with domain specification
Invoke-BloodHound -Domain ejemplo.com
Invoke-BloodHound -Domain ejemplo.com -DomainController dc01.ejemplo.com

# Collection with credenciales
$cred = Get-Credential
Invoke-BloodHound -Credential $cred -Domain ejemplo.com

Collection Methods

Available Collection Methods

# Default - Standard collection (Group, LocalAdmin, sesión, Trusts, ACL)
SharpHound.exe -c Default

# All - All collection methods
SharpHound.exe -c All

# Group - Group memberships
SharpHound.exe -c Group

# LocalAdmin - Local administrator rights
SharpHound.exe -c LocalAdmin

# RDP - Remote Desktop protocolo rights
SharpHound.exe -c RDP

# DCOM - Distributed COM rights
SharpHound.exe -c DCOM

# PSRemote - PowerShell remoting rights
SharpHound.exe -c PSRemote

# sesión - User sesións
SharpHound.exe -c sesión

# Trusts - Domain trusts
SharpHound.exe -c Trusts

# ACL - Control de Acceso Lists
SharpHound.exe -c ACL

# Container - Container ACLs
SharpHound.exe -c Container

# GPOLocalGroup - Group Policy local groups
SharpHound.exe -c GPOLocalGroup

# LoggedOn - Logged on users
SharpHound.exe -c LoggedOn

# ObjectProps - Object properties
SharpHound.exe -c ObjectProps

# SPNobjetivos - servicio Principal Name objetivos
SharpHound.exe -c SPNobjetivos

# CARegistry - certificado Authority registry
SharpHound.exe -c CARegistry

Combined Collection Methods

# Common combinations
SharpHound.exe -c Group,LocalAdmin,sesión
SharpHound.exe -c Default,GPOLocalGroup,Container
SharpHound.exe -c All --ExcludeDCs

# Stealth collection (minimal noise)
SharpHound.exe -c Group,Trusts,ACL --Stealth

# Comprehensive collection
SharpHound.exe -c All --CollectAllProperties

Advanced opcións

autenticación and credenciales

# Use current user credenciales
SharpHound.exe -d ejemplo.com

# Specify nombre de usuario and contraseña
SharpHound.exe -d ejemplo.com -u nombre de usuario -p contraseña

# Use domain\nombre de usuario format
SharpHound.exe -d ejemplo.com -u "ejemplo\nombre de usuario" -p contraseña

# LDAP autenticación
SharpHound.exe --Ldapnombre de usuario nombre de usuario --Ldapcontraseña contraseña

# Kerberos autenticación
SharpHound.exe --AuthType Kerberos

Output opcións

# Specify output directory
SharpHound.exe -d ejemplo.com --OutputDirectory C:\temp\

# Specify output filename prefix
SharpHound.exe -d ejemplo.com --OutputPrefix "audit_2024"

# Compress output (default)
SharpHound.exe -d ejemplo.com --ZipFileName audit.zip

# No compression
SharpHound.exe -d ejemplo.com --NoZip

# Pretty print JSON (larger files)
SharpHound.exe -d ejemplo.com --PrettyJson

# Randomize output filename
SharpHound.exe -d ejemplo.com --RandomFilenames

Performance and Stealth opcións

# Stealth mode (slower but less detectable)
SharpHound.exe -c All --Stealth

# Specify hilo count
SharpHound.exe -c All --hilos 10

# LDAP timeout
SharpHound.exe -c All --LdapTimeout 120

# Skip escaneo de puertos
SharpHound.exe -c All --SkippuertoScan

# Exclude domain controllers from certain collections
SharpHound.exe -c All --ExcludeDCs

# Throttle requests
SharpHound.exe -c All --Throttle 1000

# Jitter (randomize timing)
SharpHound.exe -c All --Jitter 20

Filtering opcións

# Exclude specific computers
SharpHound.exe -c All --ExcludeComputers "DC01,DC02"

# Computer filter
SharpHound.exe -c All --ComputerFile computers.txt

# Search forest
SharpHound.exe -c All --SearchForest

# Collect all properties
SharpHound.exe -c All --CollectAllProperties

# Skip registry collection
SharpHound.exe -c All --SkipRegistryLoggedOn

# Cache filename
SharpHound.exe -c All --CacheFilename cache.bin

# Invalidate cache
SharpHound.exe -c All --InvalidateCache

PowerShell Advanced uso

Credential Management

# Create credential object
$nombre de usuario = "ejemplo\administrator"
$contraseña = ConvertTo-SecureString "contraseña123" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($nombre de usuario, $contraseña)

# Use credential with SharpHound
Invoke-BloodHound -Credential $cred -Domain ejemplo.com -CollectionMethod All

# Pass-the-hash (requires additional tools)
# Use with Invoke-Mimikatz or similar tools first

Loop Collection

# Continuous collection loop
while ($true) \\\\{
    $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
    Invoke-BloodHound -CollectionMethod sesión,LoggedOn -OutputPrefix "sesións_$timestamp"
    Start-Sleep -Seconds 3600  # Wait 1 hour
\\\\}

# Scheduled collection
$trigger = New-ScheduledTaskTrigger -Daily -At "02:00AM"
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-File C:\tools\collect.ps1"
Register-ScheduledTask -TaskName "BloodHound Collection" -Trigger $trigger -Action $action

Multi-Domain Collection

# Collect from multiple domains
$domains = @("domain1.com", "domain2.com", "domain3.com")

foreach ($domain in $domains) \\\\{
    Write-host "Collecting from $domain"
    Invoke-BloodHound -Domain $domain -CollectionMethod All -OutputPrefix $domain.Replace(".", "_")
\\\\}

Collection Strategies

Stealth Collection

# Minimal footprint collection
SharpHound.exe -c Group,Trusts,ACL --Stealth --hilos 1

# Avoid sesión collection (noisy)
SharpHound.exe -c Default --ExcludeMethod sesión

# Use LDAP only
SharpHound.exe -c Group,ACL --LdapOnly

# Randomize timing
SharpHound.exe -c All --Jitter 50 --Throttle 2000

Comprehensive Collection

# Full environment mapping
SharpHound.exe -c All --CollectAllProperties --SearchForest

# Include certificado authorities
SharpHound.exe -c All,CARegistry

# Include container ACLs
SharpHound.exe -c All,Container

# Include GPO local groups
SharpHound.exe -c All,GPOLocalGroup

objetivoed Collection

# Focus on specific computers
SharpHound.exe -c LocalAdmin,sesión --ComputerFile objetivos.txt

# Focus on high-value objetivos
SharpHound.exe -c All --ComputerFilter "DC*,EXCH*,SQL*"

# Focus on specific OUs
SharpHound.exe -c All --OU "OU=Servers,DC=ejemplo,DC=com"

Output Analysis

Understanding Output Files

# Default output files
# computers.json - Computer objects and properties
# users.json - User objects and properties
# groups.json - Group objects and memberships
# domains.json - Domain information and trusts
# gpos.json - Group Policy Objects
# ous.json - Organizational Units
# containers.json - Container objects

# Compressed output
# BloodHound_YYYYMMDD_HHMMSS.zip - All JSON files compressed

File Structure Analysis

# Extract and examine files
unzip BloodHound_20240101_120000.zip

# Count objects collected
jq '.data|length' computers.json
jq '.data|length' users.json
jq '.data|length' groups.json

# Examine specific data
jq '.data[0]' computers.json  # First computer object
| jq '.data[] | select(.Properties.name | contains("ADMIN"))' users.json  # Admin users |

Impuerto into BloodHound

# Start BloodHound application
# File > Impuerto Data > Select ZIP file

# Or use neo4j-admin impuerto (for large datasets)
neo4j-admin impuerto --database=bloodhound --nodes=computers.json --nodes=users.json --relationships=relationships.json

Automation Scripts

Batch Collection Script

#!/usr/bin/env powershell
# SharpHound Automation Script

param(
    [string]$Domain = $env:USERDNSDOMAIN,
    [string]$OutputDir = "C:\temp\bloodhound",
    [string]$CollectionMethod = "All",
    [switch]$Stealth,
    [int]$hilos = 10
)

# Create output directory
if (!(Test-Path $OutputDir)) \\\\{
    New-Item -ItemType Directory -Path $OutputDir -Force
\\\\}

# Set collection parámetros
$params = @\\\\{
    Domain = $Domain
    CollectionMethod = $CollectionMethod
    OutputDirectory = $OutputDir
    OutputPrefix = "$(Get-Date -Format 'yyyyMMdd_HHmmss')"
    hilos = $hilos
\\\\}

if ($Stealth) \\\\{
    $params.Add("Stealth", $true)
    $params.hilos = 1
\\\\}

try \\\\{
    Write-host "[+] Starting SharpHound collection for domain: $Domain"
    Write-host "[+] Collection method: $CollectionMethod"
    Write-host "[+] Output directory: $OutputDir"

    # Impuerto SharpHound module
    Impuerto-Module .\SharpHound.ps1 -Force

    # Run collection
    Invoke-BloodHound @params

    Write-host "[+] Collection completed successfully"

    # List output files
| Get-ChildItem $OutputDir -Filter "*.zip" | Sort-Object LastWriteTime -Descending | Select-Object -First 5 |

\\\\} catch \\\\{
    Write-Error "[-] Collection failed: $($_.Exception.Message)"
    exit 1
\\\\}

Multi-Domain Collection Script

#!/bin/bash
# Multi-domain SharpHound collection

DOMAINS=("domain1.com" "domain2.com" "domain3.com")
OUTPUT_DIR="/tmp/bloodhound_collection"
SHARPHOUND_PATH="./SharpHound.exe"

# Create output directory
mkdir -p "$OUTPUT_DIR"

for domain in "$\\\\{DOMAINS[@]\\\\}"; do
    echo "[+] Collecting from domain: $domain"

    # Create domain-specific directory
    domain_dir="$OUTPUT_DIR/$\\\\{domain//./_\\\\}"
    mkdir -p "$domain_dir"

    # Run SharpHound
    wine "$SHARPHOUND_PATH" \
        -d "$domain" \
        -c All \
        --OutputDirectory "$domain_dir" \
        --OutputPrefix "$\\\\{domain//./_\\\\}_$(date +%Y%m%d_%H%M%S)" \
        --Stealth \
        --hilos 5

    if [ $? -eq 0 ]; then
        echo "[+] Collection completed for $domain"
    else
        echo "[-] Collection failed for $domain"
    fi

    # Wait between collections
    sleep 60
done

echo "[+] All collections completed"
ls -la "$OUTPUT_DIR"/*/*.zip

Continuous Monitoring Script

# Continuous sesión monitoring
param(
    [int]$IntervalMinutes = 60,
    [string]$OutputDir = "C:\temp\sesións"
)

while ($true) \\\\{
    try \\\\{
        $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
        $outputPrefix = "sesións_$timestamp"

        Write-host "[$(Get-Date)] Starting sesión collection..."

        Invoke-BloodHound -CollectionMethod sesión,LoggedOn -OutputDirectory $OutputDir -OutputPrefix $outputPrefix

        Write-host "[$(Get-Date)] sesión collection completed"

        # Clean up old files (keep last 24 hours)
        $cutoffTime = (Get-Date).AddHours(-24)
| Get-ChildItem $OutputDir -Filter "sesións_*.zip" | Where-Object \\\\{ $_.LastWriteTime -lt $cutoffTime \\\\} | Remove-Item -Force |

    \\\\} catch \\\\{
        Write-Error "[$(Get-Date)] Collection failed: $($_.Exception.Message)"
    \\\\}

    Start-Sleep -Seconds ($IntervalMinutes * 60)
\\\\}

Integration ejemplos

SIEM Integration

# Expuerto to SIEM-friendly format
function Expuerto-BloodHoundToSIEM \\\\{
    param(
        [string]$BloodHoundZip,
        [string]$OutputFile
    )

    # Extract ZIP
    $tempDir = New-TemporaryFile|ForEach-Object \\\\{ Remove-Item $_; New-Item -ItemType Directory -Path $_ \\\\}
    Expand-Archive -Path $BloodHoundZip -DestinationPath $tempDir

    # proceso each JSON file
    $siemData = @()

    Get-ChildItem $tempDir -Filter "*.json"|ForEach-Object \\\\{
        $data = Get-Content $_.FullName|ConvertFrom-Json

        foreach ($item in $data.data) \\\\{
            $siemData += [PSCustomObject]@\\\\{
                Timestamp = Get-Date -Format "yyyy-MM-ddTHH:mm:ssZ"
                Source = "BloodHound"
                Type = $_.BaseName
                ObjectName = $item.Properties.name
                Domain = $item.Properties.domain
                Data = ($item|ConvertTo-Json -Compress)
            \\\\}
        \\\\}
    \\\\}

    # Expuerto to CSV for SIEM ingestion
    $siemData|Expuerto-Csv -Path $OutputFile -NoTypeInformation

    # Cleanup
    Remove-Item $tempDir -Recurse -Force
\\\\}

# uso
Expuerto-BloodHoundToSIEM -BloodHoundZip "collection.zip" -OutputFile "bloodhound_siem.csv"

Automated Analysis

#!/usr/bin/env python3
impuerto json
impuerto zipfile
impuerto os
from datetime impuerto datetime

class BloodHoundAnalyzer:
    def __init__(self, zip_path):
        self.zip_path = zip_path
        self.data = \\\\{\\\\}
        self.extract_data()

    def extract_data(self):
        """Extract and load BloodHound data"""
        with zipfile.ZipFile(self.zip_path, 'r') as zip_ref:
            for file_name in zip_ref.namelist():
                if file_name.endswith('.json'):
                    with zip_ref.open(file_name) as json_file:
                        data_type = file_name.replace('.json', '')
                        self.data[data_type] = json.load(json_file)

    def analyze_admin_rights(self):
        """Analyze local admin rights"""
        admin_rights = []

        if 'computers' in self.data:
            for computer in self.data['computers']['data']:
                if 'LocalAdmins' in computer:
                    for admin in computer['LocalAdmins']:
                        admin_rights.append(\\\\{
                            'computer': computer['Properties']['name'],
                            'admin': admin['ObjectIdentifier'],
                            'type': admin['ObjectType']
                        \\\\})

        return admin_rights

    def find_high_value_objetivos(self):
        """Identify high-value objetivos"""
        hvt = []

        if 'users' in self.data:
            for user in self.data['users']['data']:
                if user['Properties'].get('highvalue', False):
                    hvt.append(\\\\{
                        'name': user['Properties']['name'],
                        'domain': user['Properties']['domain'],
                        'enabled': user['Properties'].get('enabled', False)
                    \\\\})

        return hvt

    def analyze_domain_trusts(self):
        """Analyze domain trusts"""
        trusts = []

        if 'domains' in self.data:
            for domain in self.data['domains']['data']:
                if 'Trusts' in domain:
                    for trust in domain['Trusts']:
                        trusts.append(\\\\{
                            'source': domain['Properties']['name'],
                            'objetivo': trust['objetivoDomainName'],
                            'direction': trust['TrustDirection'],
                            'type': trust['TrustType']
                        \\\\})

        return trusts

    def generate_repuerto(self):
        """Generate analysis repuerto"""
        repuerto = \\\\{
            'timestamp': datetime.now().isoformat(),
            'source_file': self.zip_path,
            'admin_rights': self.analyze_admin_rights(),
            'high_value_objetivos': self.find_high_value_objetivos(),
            'domain_trusts': self.analyze_domain_trusts(),
            'statistics': \\\\{
                'total_computers': len(self.data.get('computers', \\\\{\\\\}).get('data', [])),
                'total_users': len(self.data.get('users', \\\\{\\\\}).get('data', [])),
                'total_groups': len(self.data.get('groups', \\\\{\\\\}).get('data', []))
            \\\\}
        \\\\}

        return repuerto

# uso
if __name__ == "__main__":
    impuerto sys

    if len(sys.argv) != 2:
        print("uso: python3 analyze_bloodhound.py <bloodhound_zip>")
        sys.exit(1)

    analyzer = BloodHoundAnalyzer(sys.argv[1])
    repuerto = analyzer.generate_repuerto()

    # Save repuerto
    with open('bloodhound_analysis.json', 'w') as f:
        json.dump(repuerto, f, indent=2)

    print(f"[+] Analysis complete. Repuerto saved to bloodhound_analysis.json")
    print(f"[+] Found \\\\{len(repuerto['admin_rights'])\\\\} admin relationships")
    print(f"[+] Found \\\\{len(repuerto['high_value_objetivos'])\\\\} high-value objetivos")
    print(f"[+] Found \\\\{len(repuerto['domain_trusts'])\\\\} domain trusts")

solución de problemas

Common Issues

autenticación Problems

# Test LDAP connectivity
ldapsearch -H ldap://dc01.ejemplo.com -D "nombre de usuario@ejemplo.com" -W -b "DC=ejemplo,DC=com" "(objectClass=user)"

# Verify Kerberos tickets
klist

# Clear Kerberos cache
kdestroy

# Test with different autenticación methods
SharpHound.exe -d ejemplo.com --AuthType Negotiate
SharpHound.exe -d ejemplo.com --AuthType Ntlm
SharpHound.exe -d ejemplo.com --AuthType Kerberos

Permission Issues

# Check current user permissions
whoami /groups
whoami /priv

# Test with different user context
runas /user:DOMAIN\nombre de usuario SharpHound.exe

# Verify domain controller accessibility
nslookup ejemplo.com
telnet dc01.ejemplo.com 389
telnet dc01.ejemplo.com 636

Collection Failures

# Enable verbose logging
SharpHound.exe -c All --Verbose

# Check for specific errors
SharpHound.exe -c All --Debug

# Test individual collection methods
SharpHound.exe -c Group --Verbose
SharpHound.exe -c LocalAdmin --Verbose
SharpHound.exe -c sesión --Verbose

# Reduce hilo count
SharpHound.exe -c All --hilos 1

# Increase timeouts
SharpHound.exe -c All --LdapTimeout 300 --Timeout 300

Network Issues

# Test network connectivity
ping dc01.ejemplo.com
nmap -p 389,636,3268,3269 dc01.ejemplo.com

# Check firewall rules
netsh advfirewall firewall show rule name=all|findstr LDAP

# Test with different puertos
SharpHound.exe -d ejemplo.com --Ldappuerto 389
SharpHound.exe -d ejemplo.com --Ldappuerto 636 --SecureLdap

Performance Optimization

# Optimize for large environments
SharpHound.exe -c All --hilos 20 --Throttle 0

# Use caching for repeated collections
SharpHound.exe -c All --CacheFilename cache.bin
SharpHound.exe -c sesión --CacheFilename cache.bin  # Reuse cache

# Skip expensive operations
SharpHound.exe -c All --SkippuertoScan --ExcludeDCs

# Use stealth mode for sensitive environments
SharpHound.exe -c All --Stealth --Jitter 30

Memory and Storage Issues

# Monitor memory uso
Get-proceso SharpHound|Select-Object procesoName, WorkingSet, VirtualMemorySize

# Use compression
SharpHound.exe -c All --CompressData

# Split large collections
SharpHound.exe -c Group,ACL --OutputPrefix "part1"
SharpHound.exe -c sesión,LocalAdmin --OutputPrefix "part2"

# Clean up temporary files
Remove-Item $env:TEMP\SharpHound* -Force

Resources


This hoja de trucos provides a comprehensive reference for using SharpHound for Active Directory data collection. Always ensure you have proper autorización before using this tool in any environment.