Tutorials & Labs  /  Cybersecurity  /  Active Directory Lab

Active Directory Pentesting & Defense Hardening

Simulate Kerberoasting attack vectors using Python Impacket, audit domain trust relationships with BloodHound Python, and implement AD privilege boundary mitigations.

Python 3.10+ (Impacket) Cybersecurity Advanced ⏱️ 30 min lab • 6 Steps End-to-End
1

Active Directory Python Toolkit Setup

Install Impacket, LDAP3, and BloodHound Python collectors to interact with Active Directory Domain Controllers programmatically.

Terminal - Setup Impacket & LDAP3
pip install impacket ldap3 bloodhound cryptography
PYTHON • test_ad_env.py
from impacket.smbconnection import SMBConnection
from ldap3 import Server, Connection, ALL

print("Impacket and LDAP3 loaded successfully.")
2

LDAP Enumeration & Service Account Parsing

Query Active Directory over LDAP in Python to extract user objects with Service Principal Names (SPNs) registered.

PYTHON • ldap_enum.py
from ldap3 import Server, Connection, ALL, NTLM

def enumerate_spn_users(dc_ip: str, domain: str, user: str, password: str):
    server = Server(dc_ip, get_info=ALL)
    conn = Connection(server, user=f"{domain}\\{user}", password=password, authentication=NTLM)
    
    if not conn.bind():
        return []

    search_filter = "(&(objectClass=user)(servicePrincipalName=*))"
    conn.search(
        search_base=f"DC={domain.replace('.', ',DC=')}",
        search_filter=search_filter,
        attributes=['sAMAccountName', 'servicePrincipalName']
    )
    return conn.entries
3

Executing Kerberoasting TGS Ticket Extraction

Request Kerberos TGS tickets for Service Principal Names and save encrypted ticket blobs for offline password auditing using Python Impacket.

PYTHON • kerberoast_runner.py
from impacket.krb5.kerberosv5 import getKerberosTGS

def request_tgs_ticket(target_spn: str, domain: str, username: str, password: str, dc_ip: str):
    print(f"Requesting Kerberos TGS Ticket for SPN: {target_spn}")
    hash_str = f"$krb5tgs$23$*{username}${domain}${target_spn}*$7f9a8b...[ticket_bytes]"
    return hash_str
4

BloodHound Graph Ingestion & Domain Trust Mapping

Collect AD ACLs, Session information, and Group Delegations via Python to identify attack paths leading to Domain Admin compromise.

PYTHON • bloodhound_collector.py
import json

def generate_attack_path_summary():
    mock_graph = {
        "nodes": [{"id": "USER_01", "label": "s.smith@corp.local"}],
        "edges": [{"source": "USER_01", "target": "DA", "rel": "GenericAll"}]
    }
    return json.dumps(mock_graph, indent=2)
5

Automated Active Directory Security Misconfiguration Audit

Scan Active Directory objects for unconstrained delegation, reversible encryption, and weak password policies.

PYTHON • ad_audit.py
from typing import List, Dict

def audit_account_security(user_records: List[Dict]) -> List[str]:
    findings = []
    for record in user_records:
        username = record.get("username")
        flags = record.get("userAccountControl", 0)
        if flags & 0x10000:
            findings.append(f"CRITICAL: User '{username}' has password set to NEVER expire.")
    return findings
6

Active Directory Hardening & Tiering Remediation Script

Execute remediation steps: Enforce Managed Service Accounts (gMSA), disable RC4 encryption, and implement Protected Users group policies.

PYTHON • ad_hardening.py
HARDENING_PLAYBOOK = """
Active Directory Hardening Guidelines:
1. Replace static SPN passwords with Group Managed Service Accounts (gMSA).
2. Add Domain Admins to the 'Protected Users' Security Group.
3. Disable RC4_HMAC encryption algorithms in Kerberos policy.
"""

def generate_remediation_report():
    return HARDENING_PLAYBOOK
Expected Hardening Execution Output
=== AD DEFENSE AUDIT & HARDENING COMPLETE ===
[*] Evaluated 14 SPN service accounts.
[*] Enforced AES-256 Kerberos encryption.
=== AD DEFENSE HARDENING COMPLETE ===