SharpHound aide-mémoire
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, session information, group memberships, and ACLs to help identify attack paths and escalade de privilèges opportunities in Active Directory environments.
⚠️ Warning: Only use SharpHound in environments you own or have explicit permission to test. Unauthorized use may violate terms of service or local laws.
Installation
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:configuration=Release
# Build with .NET Core
dotnet build -c Release
# Output location
ls bin/Release/net*/SharpHound.exe
PowerShell Module Installation
# Import PowerShell module
Import-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 utilisation
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 session,LoggedOn,Trusts
# Collection with domain specification
SharpHound.exe -d exemple.com
SharpHound.exe -d exemple.com -c All
# Collection with specific domain controller
SharpHound.exe -d exemple.com -s dc01.exemple.com
PowerShell utilisation
# Basic PowerShell collection
Invoke-BloodHound
# Collection with specific methods
Invoke-BloodHound -CollectionMethod All
Invoke-BloodHound -CollectionMethod Default,session,Trusts
# Collection with domain specification
Invoke-BloodHound -Domain exemple.com
Invoke-BloodHound -Domain exemple.com -DomainController dc01.exemple.com
# Collection with identifiants
$cred = Get-Credential
Invoke-BloodHound -Credential $cred -Domain exemple.com
Collection Methods
Available Collection Methods
# Default - Standard collection (Group, LocalAdmin, session, 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 protocole rights
SharpHound.exe -c RDP
# DCOM - Distributed COM rights
SharpHound.exe -c DCOM
# PSRemote - PowerShell remoting rights
SharpHound.exe -c PSRemote
# session - User sessions
SharpHound.exe -c session
# Trusts - Domain trusts
SharpHound.exe -c Trusts
# ACL - Contrôle d'Accès 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
# SPNcibles - service Principal Name cibles
SharpHound.exe -c SPNcibles
# CARegistry - certificat Authority registry
SharpHound.exe -c CARegistry
Combined Collection Methods
# Common combinations
SharpHound.exe -c Group,LocalAdmin,session
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 options
authentification and identifiants
# Use current user identifiants
SharpHound.exe -d exemple.com
# Specify nom d'utilisateur and mot de passe
SharpHound.exe -d exemple.com -u nom d'utilisateur -p mot de passe
# Use domain\nom d'utilisateur format
SharpHound.exe -d exemple.com -u "exemple\nom d'utilisateur" -p mot de passe
# LDAP authentification
SharpHound.exe --Ldapnom d'utilisateur nom d'utilisateur --Ldapmot de passe mot de passe
# Kerberos authentification
SharpHound.exe --AuthType Kerberos
Output options
# Specify output directory
SharpHound.exe -d exemple.com --OutputDirectory C:\temp\
# Specify output filename prefix
SharpHound.exe -d exemple.com --OutputPrefix "audit_2024"
# Compress output (default)
SharpHound.exe -d exemple.com --ZipFileName audit.zip
# No compression
SharpHound.exe -d exemple.com --NoZip
# Pretty print JSON (larger files)
SharpHound.exe -d exemple.com --PrettyJson
# Randomize output filename
SharpHound.exe -d exemple.com --RandomFilenames
Performance and Stealth options
# Stealth mode (slower but less detectable)
SharpHound.exe -c All --Stealth
# Specify thread count
SharpHound.exe -c All --threads 10
# LDAP timeout
SharpHound.exe -c All --LdapTimeout 120
# Skip scan de ports
SharpHound.exe -c All --SkipportScan
# 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 options
# 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 utilisation
Credential Management
# Create credential object
$nom d'utilisateur = "exemple\administrator"
$mot de passe = ConvertTo-SecureString "mot de passe123" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($nom d'utilisateur, $mot de passe)
# Use credential with SharpHound
Invoke-BloodHound -Credential $cred -Domain exemple.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 session,LoggedOn -OutputPrefix "sessions_$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-hôte "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 --threads 1
# Avoid session collection (noisy)
SharpHound.exe -c Default --ExcludeMethod session
# 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 certificat authorities
SharpHound.exe -c All,CARegistry
# Include container ACLs
SharpHound.exe -c All,Container
# Include GPO local groups
SharpHound.exe -c All,GPOLocalGroup
cibleed Collection
# Focus on specific computers
SharpHound.exe -c LocalAdmin,session --ComputerFile cibles.txt
# Focus on high-value cibles
SharpHound.exe -c All --ComputerFilter "DC*,EXCH*,SQL*"
# Focus on specific OUs
SharpHound.exe -c All --OU "OU=Servers,DC=exemple,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 |
Import into BloodHound
# Start BloodHound application
# File > Import Data > Select ZIP file
# Or use neo4j-admin import (for large datasets)
neo4j-admin import --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]$threads = 10
)
# Create output directory
if (!(Test-Path $OutputDir)) \\\\{
New-Item -ItemType Directory -Path $OutputDir -Force
\\\\}
# Set collection paramètres
$params = @\\\\{
Domain = $Domain
CollectionMethod = $CollectionMethod
OutputDirectory = $OutputDir
OutputPrefix = "$(Get-Date -Format 'yyyyMMdd_HHmmss')"
threads = $threads
\\\\}
if ($Stealth) \\\\{
$params.Add("Stealth", $true)
$params.threads = 1
\\\\}
try \\\\{
Write-hôte "[+] Starting SharpHound collection for domain: $Domain"
Write-hôte "[+] Collection method: $CollectionMethod"
Write-hôte "[+] Output directory: $OutputDir"
# Import SharpHound module
Import-Module .\SharpHound.ps1 -Force
# Run collection
Invoke-BloodHound @params
Write-hôte "[+] 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 \
--threads 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 session monitoring
param(
[int]$IntervalMinutes = 60,
[string]$OutputDir = "C:\temp\sessions"
)
while ($true) \\\\{
try \\\\{
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$outputPrefix = "sessions_$timestamp"
Write-hôte "[$(Get-Date)] Starting session collection..."
Invoke-BloodHound -CollectionMethod session,LoggedOn -OutputDirectory $OutputDir -OutputPrefix $outputPrefix
Write-hôte "[$(Get-Date)] session collection completed"
# Clean up old files (keep last 24 hours)
$cutoffTime = (Get-Date).AddHours(-24)
| Get-ChildItem $OutputDir -Filter "sessions_*.zip" | Where-Object \\\\{ $_.LastWriteTime -lt $cutoffTime \\\\} | Remove-Item -Force |
\\\\} catch \\\\{
Write-Error "[$(Get-Date)] Collection failed: $($_.Exception.Message)"
\\\\}
Start-Sleep -Seconds ($IntervalMinutes * 60)
\\\\}
Integration exemples
SIEM Integration
# Export to SIEM-friendly format
function Export-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
# processus 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)
\\\\}
\\\\}
\\\\}
# Export to CSV for SIEM ingestion
$siemData|Export-Csv -Path $OutputFile -NoTypeInformation
# Cleanup
Remove-Item $tempDir -Recurse -Force
\\\\}
# utilisation
Export-BloodHoundToSIEM -BloodHoundZip "collection.zip" -OutputFile "bloodhound_siem.csv"
Automated Analysis
#!/usr/bin/env python3
import json
import zipfile
import os
from datetime import 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_cibles(self):
"""Identify high-value cibles"""
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'],
'cible': trust['cibleDomainName'],
'direction': trust['TrustDirection'],
'type': trust['TrustType']
\\\\})
return trusts
def generate_report(self):
"""Generate analysis report"""
report = \\\\{
'timestamp': datetime.now().isoformat(),
'source_file': self.zip_path,
'admin_rights': self.analyze_admin_rights(),
'high_value_cibles': self.find_high_value_cibles(),
'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 report
# utilisation
if __name__ == "__main__":
import sys
if len(sys.argv) != 2:
print("utilisation: python3 analyze_bloodhound.py <bloodhound_zip>")
sys.exit(1)
analyzer = BloodHoundAnalyzer(sys.argv[1])
report = analyzer.generate_report()
# Save report
with open('bloodhound_analysis.json', 'w') as f:
json.dump(report, f, indent=2)
print(f"[+] Analysis complete. Report saved to bloodhound_analysis.json")
print(f"[+] Found \\\\{len(report['admin_rights'])\\\\} admin relationships")
print(f"[+] Found \\\\{len(report['high_value_cibles'])\\\\} high-value cibles")
print(f"[+] Found \\\\{len(report['domain_trusts'])\\\\} domain trusts")
dépannage
Common Issues
authentification Problems
# Test LDAP connectivity
ldapsearch -H ldap://dc01.exemple.com -D "nom d'utilisateur@exemple.com" -W -b "DC=exemple,DC=com" "(objectClass=user)"
# Verify Kerberos tickets
klist
# Clear Kerberos cache
kdestroy
# Test with different authentification methods
SharpHound.exe -d exemple.com --AuthType Negotiate
SharpHound.exe -d exemple.com --AuthType Ntlm
SharpHound.exe -d exemple.com --AuthType Kerberos
Permission Issues
# Check current user permissions
whoami /groups
whoami /priv
# Test with different user context
runas /user:DOMAIN\nom d'utilisateur SharpHound.exe
# Verify domain controller accessibility
nslookup exemple.com
telnet dc01.exemple.com 389
telnet dc01.exemple.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 session --Verbose
# Reduce thread count
SharpHound.exe -c All --threads 1
# Increase timeouts
SharpHound.exe -c All --LdapTimeout 300 --Timeout 300
Network Issues
# Test network connectivity
ping dc01.exemple.com
nmap -p 389,636,3268,3269 dc01.exemple.com
# Check firewall rules
netsh advfirewall firewall show rule name=all|findstr LDAP
# Test with different ports
SharpHound.exe -d exemple.com --Ldapport 389
SharpHound.exe -d exemple.com --Ldapport 636 --SecureLdap
Performance Optimization
# Optimize for large environments
SharpHound.exe -c All --threads 20 --Throttle 0
# Use caching for repeated collections
SharpHound.exe -c All --CacheFilename cache.bin
SharpHound.exe -c session --CacheFilename cache.bin # Reuse cache
# Skip expensive operations
SharpHound.exe -c All --SkipportScan --ExcludeDCs
# Use stealth mode for sensitive environments
SharpHound.exe -c All --Stealth --Jitter 30
Memory and Storage Issues
# Monitor memory utilisation
Get-processus SharpHound|Select-Object processusName, WorkingSet, VirtualMemorySize
# Use compression
SharpHound.exe -c All --CompressData
# Split large collections
SharpHound.exe -c Group,ACL --OutputPrefix "part1"
SharpHound.exe -c session,LocalAdmin --OutputPrefix "part2"
# Clean up temporary files
Remove-Item $env:TEMP\SharpHound* -Force
Resources
- Official SharpHound documentation
- SharpHound GitHub Repository
- BloodHound documentation
- Active Directory Security Blog
- BloodHound Community
- PowerShell Empire Integration
- Cobalt Strike Integration
This aide-mémoire provides a comprehensive reference for using SharpHound for Active Directory data collection. Always ensure you have proper autorisation before using this tool in any environment.