> For the complete documentation index, see [llms.txt](https://breakpoint-journal.gitbook.io/breakpoint/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://breakpoint-journal.gitbook.io/breakpoint/windows/pentest-sheet.md).

# PENTEST SHEET

PENTEST CHEAT SHEET

### **Enumeration**

#### SMB - 445

**smbclient**

* Anonymous authentication

> smbclient -U “” “\\\\\<share>”

* Anonymous authentication

### **Databases**

#### Redis

In-memory data structure store used as a database, cache, message broker, and streaming engine. Redis provides data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes, and streams. Redis has built-in replication, Lua scripting, LRU eviction, transactions, and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster.

**Commands (**[**https://redis.io/commands/**](https://redis.io/commands/)**)**

* info

Lists statistics regarding the database

* select

Selects the database with the given index

* keys \*

Lists all keys stored in a database

* get \<key\_name>

Retrieves stored value for key

### **Reverse Shells**

#### **Tunneling**

* [Ligolo : Reverse Tunneling made easy for pentesters, by pentesters](https://github.com/sysdream/ligolo)
* <https://0x00sec.org/t/tricks-of-the-trade-from-5-years-in-offensive-cyber-security/15794/11>
* TORIFY is an excellent binary which I keep in Handy to route my network requests through Tor.

### **PrivEsc**

#### **Command History**

Here goes some from my recent .zsh\_history

One nifty little trick I use often is to run echo before my actual command in xargs to see what commands would actually be executed. An example is :

cat text | xargs -n1 -I {} echo {}

### **Active Directory**

#### **TLDR**

**Delegation TLDR**

* Find machines w/ unconstrained delegation w/ PowerView’s ***-Unconstrained*** flag

| Get-DomainUser SQLService -Properties \ distinguishedname.msds-allowedtodelegateto.useraccountcontrol \| ConvertFrom-UACValue |
| ----------------------------------------------------------------------------------------------------------------------------- |

If TRUSTED\_TO\_AUTH\_FOR\_DELEGATION is enabled then anyone who compromises that account can impersonate any user to the SPNs set in msds-allowedtodelegateto.

* [PowerView/SharpView - HackTricks](https://book.hacktricks.xyz/windows-hardening/basic-powershell-for-pentesters/powerview) contains many Powershell tools for AD
  * Enumerate AllowedToDelegateTo lists of computers & users to see if we can move laterally to impersonate other services:

Find non-null ***msds-allowedtodelegateto*** field set. This can be done easily with PowerView’s ***-TrustedToAuth*** flag for ***Get-DomainUser/Get-DomainComputer***

| Get-DomainComputer -TrustedToAuth -Properties distinguishedname.msds-allowedtodelegateto.useraccountcontrol -Verbose \| fl |
| -------------------------------------------------------------------------------------------------------------------------- |

* [Rotten Potato – Privilege Escalation from Service Accounts to SYSTEM](https://foxglovesecurity.com/2016/09/26/rotten-potato-privilege-escalation-from-service-accounts-to-system/)
* [Kekeo - A little toolbox to play with Microsoft Kerberos in C](https://github.com/gentilkiwi/kekeo), good for use when you’ve compromised plaintext password of a service account
* See **Scenarios** under [S4U2Pwnage | by Will Schroeder](https://harmj0y.medium.com/s4u2pwnage-36efe1a2777c)
* **View user accounts that Allow or Disallow Delegation:**

$> Get-DomainUser -AllowDelegation/-DisallowDelegation) and you can use the ConvertFrom-UACValue

* Extract TGTs or TGSs from lsass or memory of other processes using Mimikatz
* Inject new Certificates or TGS information into service process memory
* S4U2Self works on any account that has an SPN, therefore if we don’t have an account with an SPN we can add a computer w/ the ***impacket/examples/addcomputer.py*** script (abusing the MachineAccountQuota)
  * Will need to verify whether you can add computers w/ CrackMapExec ldap tool

**ADCS TLDR**

* If the system runs ADCS, search for vulnerable templates w/ certipy-ad
* You can also abuse Delegation rights via **PassTheCert** so that you can use a requested certificate to give RBCD or delegation rights over the DC machine computer account.
* **Defensive Tool to audit ADCS:**[GitHub - GhostPack/PSPKIAudit: PowerShell toolkit for AD CS auditing based on the PSPKI toolkit.](https://github.com/GhostPack/PSPKIAudit)

#### **Delegation 101**

**Delegation** allows a service to impersonate the client user to interact with a second service, with the privileges and permissions of the client itself. There are three types, **Unconstrained, Constrained, and Resource-Based Constrained Delegation (RBCD)**.

**Unconstrained Delegation:**

Allows a service to impersonate any user that was authenticated against it w/o limitations. Service acquires a valid TGT for the client user, which is equivalent to become that user in Kerberos’ world (and therefore on the domain). I.e. the client delegates the service to act as them (by using their TGT).

The client sends the TGT to the service to request a TGS. The KDC includes the client’s TGT inside the TGS response. Note that the included TGT is in the part of the TGS encrypted with the service owner key

**What is&#x20;*****TrustedForDelegation?***

KDC includes the TGT in case the TrustedForDelegation (or ADS\_UF\_TRUSTED\_FOR\_DELEGATION) flag is set for the owner of the target service. This flag is stored in the User-Account-Control attribute of Active Directory user accounts.

In order to modify the TrustedForDelegation flag of a user, it is necessary to have the privilege SeEnableDelegationPrivilege on a domain controller. Anyway, if the target user of delegation is protected against delegation because of Protected Users group or NotDelegated flag, delegation will not work.

![](https://content.gitbook.com/content/mGhYQRY1OEeL4zywZ9zS/blobs/LIVO7OyrWssGPoM4fWn2/Unknown%20image)

**Unconstrained Delegation Attacks:**

* If a pentester is able to compromise a computer which is hosting services with Unconstrained Delegation, there is a good chance that TGT’s can be found for the clients of those services.
* If a pentester is able to compromise the account of a user which has Unconstrained Delegation permissions, it could be possible to harvest TGT’s from the services belonging to that user.
* In any of the previous scenarios, if the pentester can persuade a privileged account to interact with one of the “controlled” services, then it would be possible to steal its TGT and compromise the domain
* In case of having the control of a domain, a way of persistence could be granting Unconstrained Delegation to a set of users that the pentester would control.

**How can you tell which machines have unconstrained delegation set?**

Search for any machine that has a [userAccountControl](https://msdn.microsoft.com/en-us/library/ms680832\(v=vs.85\).aspx) attribute containing [ADS\_UF\_TRUSTED\_FOR\_DELEGATION](https://msdn.microsoft.com/en-us/library/aa772300\(v=vs.85\).aspx). You can do this with an LDAP filter of ‘(userAccountControl:1.2.840.113556.1.4.803:=524288)’, which is what PowerView’s [**Get-DomainComputer**](http://powersploit.readthedocs.io/en/latest/Recon/Get-DomainComputer/#parameters) function does when passed the ***-Unconstrained*** flag:

* [S4U2Pwnage | by Will Schroeder](https://harmj0y.medium.com/s4u2pwnage-36efe1a2777c)

**Constrained Delegation and RBCD**

Delegation is constrained to only some whitelisted third-party services. Kerberos creates this whitelist using S4U2Proxy (Service for User to Proxy) and S4U2Self (Service for User to Self). These are services that grant special tickets to implement delegation for specific groups of services.

**S4U2Proxy:**

An extension that allows a service to use the TGS sent by the client user to order from the KDC a new TGS for a third service, on behalf of the client user.

**How does KDC know whether a user can order TGS to another service?**

The KDC checks two lists..

* User’s ***msDS-AllowedToDelegateTo*** attribute lists services with which it may request from. This attribute may only be used if ***SeEnableDelegationPrivilege*** is enabled on DC. Constrained delegation uses this list
* User’s ***msDS-AllowedToActOnBehalfOfOtherIdentity*** attribute lists other users which are allowed to ask a TGS for any of its services. The user by itself can edit his own list of allowed users on demand and so the KDC checks the following conditions...

(Note: this is the list used in RBCD)

**CD & RBCD Whitelist Check**

* If the service client is protected against delegation (member of Protected Users group or has the NotDelegated flag set), then S4U2Proxy will fail.

**CD Whitelist Check**

* If the requested service X is in *msDS-AllowedToDelegateTo* of currently-used service Z account
  * The KDC checks whether the sent TGS is ***forwardable***(forwardable flag is set), and if so, sends the forwardable TGS for the requested service (**constrained delegation applied)**.
  * OTHERWISE FAILURE!

**(Note: If both CD & RBCD applied, CD takes precedence)**

**RBCD Whitelist Check**

* If the user who is requesting the TGS is in the ***msDS-AllowedToActOnBehalfOfOtherIdentity*** of the requested service owner account, then the KDC will return a forwardable TGS **(RBCD)**.

**(Note: sent TGS need not be forwardable & CD could fail but RBCD succeeds)**

**CD Example**

![](https://content.gitbook.com/content/mGhYQRY1OEeL4zywZ9zS/blobs/znPB9SBNO6Nj5WZF7vxr/Unknown%20image)

**RBCD Example:**

![](https://content.gitbook.com/content/mGhYQRY1OEeL4zywZ9zS/blobs/g3GkKfL3XMTSX9zZS6pa/Unknown%20image)

**Service Name Change Attack**

You may use the same TGS for any service of the user. This is because the TGSs keep the name of the requested service in plaintext (it’s modifiable), AND all the services of a user share the same kerberos key. Therefore say we’re using ServiceZ, owned by UserZ, and want access to UserXY’s ServiceX, but we only have access to UserXY’s ServiceY. We can get a valid TGS to ServiceY, and then modify the name to ServiceX giving us access to ServiceX. Note that the ServiceZ does the name change.

![](https://content.gitbook.com/content/mGhYQRY1OEeL4zywZ9zS/blobs/SckwbrofK9fSm2DVUzUJ/Unknown%20image)

**S4U2Self:**

The purpose of S4U2Self is to allow the use of Delegation to services that do not support Kerberos authentication, and therefore, are unable to get a TGS from the client user. To bypass this limitation, S4U2Self allows a service to request the KDC for a TGS for itself, on behalf of another user. This is also known as Protocol Transition.

KDC responds differently according to the ***TrustedToAuthForDelegation*** (or ADS\_UF\_TRUSTED\_TO\_AUTHENTICATE\_FOR\_DELEGATION) flag is contained in the User-Account-Control attribute of user accounts. To modify this flag it is required to have the ***SeEnableDelegationPrivilege*** privilege in the DC.

* If user has no services, KDC will not return TGS
* If the target user for impersonation is not allowed to be delegated, then TGS will return a TGS w/o the forwardable flag. (Also TGS contains incorrect service name but this can be modified)
* If the ***TrustedToAuthForDelegation*** flag is set for the user, then KDC will return a TGS w/ the forwardable flag
* Otherwise returns TGS w/o the forwardable flag

![](https://content.gitbook.com/content/mGhYQRY1OEeL4zywZ9zS/blobs/qyXakeoRuaezunH7ULQ7/Unknown%20image)

1. *User1* performs authentication against *ServiceZ* without using Kerberos. NTLM or other protocols could be used in this situation.
2. *ServiceZ*, owned by *UserZ*, asks for a TGS for itself on behalf of *User1*.
3. The KDC checks:
4. If *UserZ* is the owner of any service (Yes).
5. If *TrustedToAuthForDelegation* flag is set for *UserZ* account (Yes).
6. The KDC returns to *ServiceZ* a *forwardable* TGS for itself, on behalf *User1*, which can be used in S4U2Proxy.

**Example of S4U2Self + S4U2Proxy**

Constrained Delegation Example

![](https://content.gitbook.com/content/mGhYQRY1OEeL4zywZ9zS/blobs/84jgMW862XS22YesXX2R/Unknown%20image)

The user is identified to the KDC using the user's name and realm. Alternatively, the user might be identified based on the user's certificate. The Kerberos ticket-granting service (TGS)

RBCD Example

![](https://content.gitbook.com/content/mGhYQRY1OEeL4zywZ9zS/blobs/3BwRqBCHfgy0Bocpz7Tb/Unknown%20image)

**CD Attacks**

* If a pentester is able to compromise a computer which is hosting services with Constrained Delegation, it could harvest the TGS’s for third-party services of the clients of each service and interact with them. Additionally, those TGS’s could be edited to change the target service and interact with other services belonging to the same target user.
* If a pentester is able to compromise the account of a user which has Constrained Delegation permissions, it could collect the TGS’s of the clients of services belonging to the compromised account. Moreover, in case the compromised user account has the flag TrustedToAuthForDelegation activated, the pentester itself could use S4U2Self to request TGS’s of the clients directly to the KDC.
* Moreover, in any of the previous scenarios, for each TGS it could be possible to modify the service name in order to increase the number of services the pentester could interact.

**How to view AllowedToDelegate Whitelist?**

The field of interest is **msds-allowedtodelegateto**, but there’s also a modification to the account’s userAccountControl property. Essentially, if a computer/user object has a userAccountControl value containing [TRUSTED\_TO\_AUTH\_FOR\_DELEGATION](https://msdn.microsoft.com/en-us/library/aa772300\(v=vs.85\).aspx) then anyone who compromises that account can impersonate **any** user to the SPNs set in **msds-allowedtodelegateto**

**RBCD Attacks**

If a pentester is able to compromise an account UserZ which is listed in the msDS-AllowedToActOnBehalfOfOtherIdentity attribute of another account named UserX, then it would be possible to chain the use of S4U2Self and S4U2Proxy to get access to the services of UserX by impersonating it. Here is an example of this scenario where UserZ uses S4U2Self and S4U2Proxy to interact with the service ServiceX by impersonating its owner UserX (it is assumed that UserX is not protected against delegation by Protected Users or NotDelegated):

![](https://content.gitbook.com/content/mGhYQRY1OEeL4zywZ9zS/blobs/qFWDMtrNdO2jyMFnKkHn/Unknown%20image)

1. *UserZ* (pentester), owner of *ServiceZ*, requests a TGS for *ServiceZ* on behalf for *UserX* (S4U2Self).
2. The KDC checks:
3. If *UserZ* is the owner of any service (Yes).
4. If *TrustedToAuthForDelegation* flag is set for *UserZ* account (No).
5. The KDC returns to *UserZ* a non-*forwardable* TGS for *ServiceZ* on behalf of *UserX*.
6. *UserZ* uses the new *non-forwardable* TGS to order another TGS (S4U2Proxy) for *ServiceX* on behalf of *UserX*.
7. The KDC checks:
8. If *ServiceX* is listed in *UserZ* *msDS-AllowedToDelegateTo* (No). Constrained Delegation cannot be applied.
9. If *UserZ* is listed in *msDS-AllowedToActOnBehalfOfOtherIdentity* of *UserX*, the owner of *ServiceX* (Yes). RBCD can be applied.
10. The KDC returns a *forwardable* TGS to *ServiceZ* to interact with *ServiceX* on behalf of *UserX*.
11. *UserZ* uses the new TGS to interact with *ServiceX*, by impersonating *UserX*.

Other interesting possibility, as a way of persistence, is to configure RBCD from arbitrary users to the krbtgt account. Thus, those arbitrary users will be able to generate TGS’s to the krbtgt service for any user, which means generating TGT’s (since TGT are just TGS’s to the krbtgt service) for any user in the domain, similarly of the Golden Ticket attack.

**Protections**

* Enabled **Protected Users** or or **NotDelegated** for important users

[Protected Users Security Group | Microsoft Learn](https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-R2-and-2012/dn466518\(v=ws.11\))

**Resources**

* [Kerberos (III): How does delegation work?](https://www.tarlogic.com/blog/kerberos-iii-how-does-delegation-work/)
* [Wagging the Dog: Abusing Resource-Based Constrained Delegation to Attack Active Directory | Shenanigans Labs](https://shenaniganslabs.io/2019/01/28/Wagging-the-Dog.html)
* [Abusing Kerberos S4U2self for local privilege escalation :: Cyberstoph's blog](https://cyberstoph.org/posts/2021/06/abusing-kerberos-s4u2self-for-local-privilege-escalation/)
* [Certified Pre-Owned. Active Directory Certificate Services… | by Will Schroeder | Posts By SpecterOps Team Members](https://posts.specterops.io/certified-pre-owned-d95910965cd2)
* [S4U2Pwnage | by Will Schroeder](https://harmj0y.medium.com/s4u2pwnage-36efe1a2777c)

#### **Active Directory Certificate Service (ADCS)**

ADCS is Microsoft’s PKI implementation that provides everything from encrypting file systems, to digital signatures, to user authentication (a large focus of our research), and more

**What is a certificate and how does it work?**

Certificates are X.509-formatted digitally signed electronic documents that can be used for encryption, message signing, and/or authentication (our research focus).

The information included in a certificate binds an identity (the subject) to a public/private key pair. An application can then use the key pair in operations as proof of the identity of the user. Certificate Authorities (CAs) are responsible for issuing certificates.

1. Clients generate a public-private key pair, and the public key is placed in a certificate signing request (CSR) message along with other details such as the subject of the certificate and the certificate template name.
2. Clients then send the CSR to the Enterprise CA server.
3. The CA server then checks if the client is allowed to request certificates.
4. If so, it determines if it will issue a certificate by looking up the certificate template AD object (more on these shortly) specified in the CSR.
5. The CA will check if the certificate template AD object’s permissions allow the authenticating account to obtain a certificate.
6. If so, the CA generates a certificate using the “blueprint” settings defined by the certificate template (e.g., EKUs, cryptography settings, issuance requirements, etc.) and using the other information supplied in the CSR if allowed by the certificate’s template settings.
7. The CA signs the certificate using its private key and then returns it to the client.

![](https://content.gitbook.com/content/mGhYQRY1OEeL4zywZ9zS/blobs/ZQlAS7OKhv3wJUPkq1Tl/Unknown%20image)

**What does a Certificate Template look like?**

Certificate templates contain information like…

* “How long is this certificate valid for?”
* “What is the certificate used for?”
* “How is the subject specified?”
* “Who is allowed to request a certificate?”

In particular, the ***pKIExtendedKeyUsage***, contains an array of object identifiers (OIDs) enabled for the template. These EKU object identifiers affect what the certificate can be used for (PKI Solutions has a breakdown of the [EKU OIDs available from Microsoft](https://www.pkisolutions.com/object-identifiers-oid-in-pki/)). The following lists EKUs that, when enabled, allow authentication to AD via the certificate.

![](https://content.gitbook.com/content/mGhYQRY1OEeL4zywZ9zS/blobs/469WbiNgwN7eco4QHGJY/Unknown%20image)

It’s important to note there are **Issuance Requirements** which can function as preventative controls.

**What is a Subject Alternative Name (SAN)?**

A Subject Alternative Name (SAN) is an extension that allows additional identities to be bound to a certificate beyond just the subject of the certificate. For example, if a web server hosts content for multiple domains, each applicable domain could be included in the SAN so that the web server only needs a single HTTPS certificate instead of one for each domain.

SAN can do this by associating multiple UPNs with certificates.

**ADSC Attacks**

So, if an attacker can specify an arbitrary SAN when requesting a certificate that enables domain authentication, and the CA creates and signs a certificate using the attacker-supplied SAN, the attacker can become any user in the domain! There’s a list of all ESC1-ESC8 vulnerabilities w/ ADSC listed here: [Exploiting AD CS: A quick look at ESC1 and ESC8 | Crowe LLP](https://www.crowe.com/cybersecurity-watch/exploiting-ad-cs-a-quick-look-at-esc1-esc8)

**ESC1-ESC8:**

**ESC1**

Using the low-level authentication that they have gained thus far, attackers can then use a tool such as Rubeus to request an authentication token from Kerberos (available to any user). The attackers then use Kerberos authentication to request a certificate using the vulnerable template and specify the request is on behalf of any domain admin they choose. Once attackers have that certificate, they then can simply request another Kerberos ticket-granting ticket (TGT) as the domain admin they requested the certificate for, and the domain admin is unlocked. Exhibit 4 demonstrates this process.

![](https://content.gitbook.com/content/mGhYQRY1OEeL4zywZ9zS/blobs/pMLRudsM5K9KDQKaMPKl/Unknown%20image)

This can be done w/ ***certipy-ad auth …*** command assuming Kerberos authentication is enabled for the user. This lateral movement is known as **Kerberos U2U (User-to-User**

**authentication)**, and allows us to decrypt the NT hash from the Privilege Attribute Certificate (PAC) and then use the NT hash to pass-the-hash and obtain administrator access.

**(See the Authority writeup from HackTheBox)**. If this doesn’t work however because PKINIT Is disabled, then we can use **PassTheCert** tool to authenticate to LDAP w/ Schannel (Secure Channel). In essence, the retrieved certificate (w/ on behalf of Administrator rights) can be used to give ***delegation (RBCD)*** writes **over the Administrator** to our attacker-controlled **machine** (adds EVIL$ to AUTHORITY$’s msDS-AllowedToActOnBehalfOfOtherIdentity whitelist, meaning EVIL$ can impersonate any user on AUTHORITY$ via S4U2Proxy).

From there you can use ***impacket-getST*** to impersonate the Administrator on AUTHORITY$ and get a TGT. We set the ***KRB5CCNAME*** to use the TGT (.ccache file), and, finally, using ***impacket-secretsdump*** as Administrator we can dump the all the hashes of users. The **Administrator**’s hash can be used in **Pass The Hash** to authenticate as Admin over **WinRM**.

For more info see [Certified Pre-Owned. ADCS](https://posts.specterops.io/certified-pre-owned-d95910965cd2) or [Exploiting AD CS: ESC1 and ESC8](https://www.crowe.com/cybersecurity-watch/exploiting-ad-cs-a-quick-look-at-esc1-esc8).

**ESC2**

A ESC2 occurs with the following conditions

* Entreprise CA grants low-privileged users enrollment rights
* Manager approval is disabled
* No authorized signatures required
* An overly permissive certificate template security descriptor grants certificate enrollment rights to low-privileged users.
* The certificate template defines Any Purpose EKUs or no EKU

Cannot request authentication certificates as other users without the CT\_FLAG\_ENROLLEE\_SUPPLIES\_SUBJECT flag being present, an attacker can use them to authenticate to AD as the user who requested them.

**Subordinate vs Non-Subordinate Certificate**

SubCA has no EKUs, this is different from an Any Purpose EKU which can be used for any purpose, i.e. client authentication, server authentication, code signing, etc. A subordinate certificate allows any purpose as well but could also use it to sign new certificates. As such, using a subordinate CA certificate, an attacker could specify arbitrary EKUs or fields in the new certificates.

**Protections**: The attacker may not create new certificates that will work for domain authentication if the subordinate CA is not trusted by the NTAuthCertificates object (which it won’t be by default). Even then, the attacker can create new certificates with any EKU and arbitrary certificate values, of which there’s plenty the attacker could potentially abuse (e.g., code signing, server authentication, etc.) and might have large implications for other applications in the network like SAML, AD FS, or IPSec.

**ESC3**

A ESC3 occurs with the following conditions

* The Enterprise CA grants low-privileged users enrollment rights
* Manager approval is disabled
* No authorized signatures are required
* An overly permissive certificate template security descriptor grants certificate enrollment rights to low-privileged users
* The certificate template defines the Certificate Request Agent EKU. The Certificate Request Agent OID (1.3.6.1.4.1.311.20.2.1) allows for requesting other certificate templates on behalf of other principals
* Enrollment agent restrictions are not implemented on the CA

**Enrollment Agent**

The Certificate Request Agent EKU (OID 1.3.6.1.4.1.311.20.2.1), known as “Enrollment Agent” in Microsoft documentation, allows a principal to enroll for a certificate on behalf of another user. For anyone who enrolls in such a template, the resulting certificate can be used to co-sign requests on behalf of any user, for any Schema Version 1 template or any Schema Version 2+ template that requires the appropriate “Authorized Signatures/Application Policy” Issuance Requirement. This also assumes that there are no limiting Enrollment Agent Restrictions on the CA.

**Example**: In the AUTHORITY HTB, this was used to request a certificate on behalf of Administrator and then request a TGT as Admin using the retrieved cert (.pfx file).

**Things I don’t really understand from**[**Certified Pre-Owned. ADCS**](https://posts.specterops.io/certified-pre-owned-d95910965cd2)

If an attacker is able to enroll in a template with a “Certificate Request Agent” EKU, they can enroll on behalf of any user for any Version 1 certificate template, or any Version 2+ template configured to explicitly require this co-signing scenario. Schema Version 1 templates don’t implement this type of Issuance Requirement, so all are on the table. Specifically, the User and Machine/Computer templates are prime targets as they contain the Client Authentication EKU and are published by default (though this can be changed), and there are other Version 1 templates that can be vulnerable if published.

If a Version 1 template is duplicated for modification, it automatically becomes Schema Version 2 by default, meaning a “Certificate Request Agent” template will NOT work unless such an issuance requirement is explicitly specified.

**ESC4**

For context, certificate templates have security descriptors that specify which Active Directory Principals have specific permissions over the templates.

We say that a template is misconfigured at the access control level if it has Access Control Entries (ACEs) that allow unintended, or otherwise unprivileged, Active Directory principals to edit sensitive security settings in the template.

That is, if an attacker is able to chain access to a point that they can actively push a misconfiguration to a template that is not otherwise vulnerable (e.g., by enabling the ***CT\_FLAG\_ENROLLEE\_SUPPLIES\_SUBJECT*** bit in the ***mspki-certificate-name-flag*** property for a template that allows for domain authentication), we end up with domain compromise scenarios similar to what we’ve already covered.

**Example:***Domain Computers* having FullControl or WriteDacl permissions over a certificate template’s AD object, allowing attackers with access to any AD computer modify the certificate template to a dangerous state. This is a scenario explored in [Christoph Falta’s GitHub repo](https://github.com/cfalta/PoshADCS).

**ESC5 Vulnerable PKI Object Access Control**

consists of the following:

* CA server’s AD computer object (i.e., compromise through RBCD)
* 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=,DC=** (e.g., the Certificate Templates container, Certification Authorities container, the NTAuthCertificates object, the Enrollment Services container, etc.)

**ESC6 - EDITF\_ATTRIBUTESUBJECTALTNAME2**

Another way to supply arbitrary SANs, described in a CQure Academy post, involves the EDITF\_ATTRIBUTESUBJECTALTNAME2 flag. As Microsoft describes, “If this flag is set on the CA, any request (including when the subject is built from Active Directory®) can have user defined values in the subject alternative name.” This means that ANY template configured for domain authentication that also allows unprivileged users to enroll (e.g., the default User template) can be abused to obtain a certificate that allows us to authenticate as a domain admin (or any other active user/machine). As this Keyfactor post describes, this setting “just makes it work”, which is why it’s likely flipped in many environments by sysadmins who don’t fully understand the security implications.

**ESC7 - Vulnerable Certificate Authority Access Control**

Outside of certificate templates, a certificate authority itself [has permissions](https://social.technet.microsoft.com/wiki/contents/articles/10942.ad-cs-security-guidance.aspx#Roles_and_activities) (accessible through *certsrv.msc*) that secure various CA actions. From a security perspective we care about the **ManageCA** (aka “CA Administrator”) and **ManageCertificates** (aka “Certificate Manager/Officer”) permissions.

The **ManageCA**permission grants a principal the ability to perform “Administrative” CA actions, including the modification of persistent configuration data. This includes the EDITF\_ATTRIBUTESUBJECTALTNAME2 flag, allowing any principal with the **ManageCA** permission to fixate ESC6. This can be done with PSPKI’s [Enable-PolicyModuleFlag](https://www.sysadmins.lv/projects/pspki/enable-policymoduleflag.aspx) cmdlet.

The **ManageCertificates** permission allows the principal to approve pending certificate requests, negating the “Manager Approval” Issuance Requirement/protection. So while it can’t be used on its own to compromise the domain, it can function as a protection bypass.

**ESC8 - NTLM Relay to AD CS HTTP Endpoints**

AD CS supports several HTTP-based enrollment methods via additional server roles that administrators can optionally install:

* The certificate enrollment web interface, via installing the Certificate Authority Web Enrollment role. Exposed as an IIS-hosted ASP web enrollment application running at http\:///certsrv/.
* Certificate enrollment service (CES), via installing the Certificate Enrollment Web Service role. Works in tandem with the Certificate Enrollment Policy (CEP) web service, via installing the Certificate Enrollment Policy Web Service role. Details in the whitepaper.
* The network device enrollment service (NDES), via installing the Network Device Enrollment Service role. Exposed as a series of interfaces described in the whitepaper.

These HTTP-based certificate enrollment interfaces are all vulnerable to NTLM relay attacks. Using NTLM relay, an attacker can impersonate an inbound-NTLM-authenticating victim user. While impersonating the victim user, an attacker could access these web interfaces and request a client authentication certificate based on the User or Machine certificate templates.

Like all NTLM Relay attacks, this one requires a victim account to authenticate to an attacker-controlled machine. An attacker can coerce authentication by many means, but a simple technique is to coerce a machine account to authenticate to the attacker’s host using the MS-RPRN RpcRemoteFindFirstPrinterChangeNotification(Ex) methods using a tool like SpoolSample or Dementor. The attacker can then use NTLM relay to impersonate the machine account and request a client authentication certificate (e.g., the default Machine/Computer template) as the victim machine account. If the victim machine account can perform privileged actions such as domain replication (e.g., domain controllers or Exchange servers), the attacker could use this certificate to compromise the domain. Otherwise, the attacker could logon as the victim machine account and use S4U2Self as previously described to access the victim machine’s host OS.

\*\*NOTE:\*\*Newer OS’es have patched the MS-RPRN coerced authentication “feature”. However, almost every environment we examine still has Server 2016 machines running, which are still vulnerable to this. There are other ways to coerce accounts to authenticate to an attacker as well.

In summary, if an environment has AD CS installed, along with a vulnerable web enrollment endpoint and at least one certificate template published that allows for domain computer enrollment and client authentication (like the default Machine/Computer template), then an attacker can compromise ANY computer with the spooler service running!

**Query certificate templates**

We need a template for domain authentication. The following command queries LDAP for available templates that we can examine for our desired criteria

$> Certify.exe find /clientauth

**Requesting a certificate**

If you have GUI access, you can use **certmgr.msc**. Alternatively could use **Certify**, **certreq.exe**, or **Certipy** to request certificates.

*$> certipy req -username <john@corp.local> -password Passw0rd -ca corp-DC-CA -target ca.corp.local -template User*

**Authenticating to AD w/ certificate**

There are several options for authenticating…

* Utilize the requested certificate with Rubeus to authenticate to AD for the given user (NOTE: this method doesn’t touch LSASS)
* Open LDAPS interactive shell using Schannel (TLS/SSL) and add a user into the administrators group. (See [PassTheCert](https://github.com/AlmondOffSec/PassTheCert), requires splitting the **.pfx** certificate into the key and the cert using ***openssl pkcs12 -nokeys/-nocerts*****&#x20;-in \<in\_file> -out** )
* Combine the machine ticket with [**S4U2Self**](https://cyberstoph.org/posts/2021/06/abusing-kerberos-s4u2self-for-local-privilege-escalation/)\*\*\*\*to obtain a Kerberos service ticket to any service on the host (e.g., CIFS, HTTP, RPCSS, etc.) as any user.

The auth command will use either the PKINIT Kerberos extension or Schannel protocol for authentication with the provided certificate. Kerberos can be used to retrieve a TGT and the NT hash for the target user, whereas Schannel will open a connection to LDAPS and drop into an interactive shell with limited LDAP commands. See the blog posts for more information on when to use which option.

**Tools**

* Certify (<https://github.com/GhostPack/Certify.git>)

a C# tool to enumerate and abuse misconfigurations in Active Directory Certificate Services (AD CS)

* Get-AuditCertificateTemplate | ?{$\_.HasAuthenticationEku}

Powershell command to query

* Certipy (<https://github.com/ly4k/Certipy>)

an offensive tool for enumerating and abusing Active Directory Certificate Services (AD CS)

* Rubeus (<https://github.com/GhostPack/Rubeus>)

a C# toolkit for Kerberos interaction and abuses. Kerberos, as we all know, is a ticket-based network authentication protocol and is used in Active Directories

#### **Kerberos**

Kerberos is an authentication protocol, not authorization. In other words, it allows identification of each user who provides a secret password, however, it does not validate to which resources or services this user may access.

**Basic Terminology**

* **User accounts vs Computer accounts**

Computer server names end w/ “$”, and are a subclass of “User” accounts

* **Service** identified by SPN (Service Principal Name) which indicates the service name and class, the owner and the host computer. These are executed as a process in the context/privileges of a user. A user must have a TGS to use it. A user’s services are stored in the ***ServicePrincipalName*** attribute. Adding an SPN to a user account requires the **Validated-SPN** permission.

**Encryption & Keys:**

Kerberos encrypts and transports data via UDP or TCP over port 88.

* **KDC or krbtgt key** which is derivative of the krbtgt account NTLM hash
* **User key** which is similar to the user NTLM hash
* **Service key** which is NTLM hash of service owner, which can be a user or computer account
* **Session key** which is negotiated between user and KDC
* **Service session key** is used b/w user and service

**Kerberos Services**

**KDC:** The Key Distribution Center, the main service of Kerberos, responsible for issuing the tickets, installed on the DC. It is supported by the AS (Authentication Service), which issues the TGTs (Ticket Granting Tickets)

**TGS (Ticket Granting Service)** is the ticket the user can use to authenticate against a service. It is encrypted with the service key

\*\*TGT (Ticket Granting Ticket)\*\*is the ticket presented to the KDC to request for TGSs. It is encrypted with the KDC key

**PAC (Privilege Attribute Certificate)** is a structure included in almost every ticket. This structure contains the privileges of the user and it is signed with the KDC key

**Kerberos Messages**

![](https://content.gitbook.com/content/mGhYQRY1OEeL4zywZ9zS/blobs/Tl0JsFVf6u21lzW0lARo/Unknown%20image)

* **KRB\_AS\_REQ:** Used to request the TGT to KDC.

Contains timestamp, username of user, service SPN w/ krbtgt account, and a nonce

* \*\*KRB\_AS\_REP:\*\*Used to deliver the TGT by KDC.

Responds w/ username, TGT (username, session key, expir, PAC w/ user privileges), encrypted data w/ session key, expir date, and nonce

* \*\*KRB\_TGS\_REQ:\*\*Used to request the TGS to KDC, using the TGT.

Encrypted data w/ session key consisting of username, timestamp, TGT, SPN of requested service, and a nonce

* \*\*KRB\_TGS\_REP:\*\*Used to deliver the TGS by KDC.

Includes username, TGS (service session key), username, expir date, PAC, & repeat data

* \*\*KRB\_AP\_REQ:\*\*Used to authenticate a user against a service, using the TGS.

User sends TGS and encrypted data w/ service session key. Server will \_potentially\_authenticate PAC against the KDC

* **KRB\_AP\_REP:**(Optional) Used by service to identify itself against the user.
* KRB\_ERROR: Message to comunicate error conditions.

**Kerberos Attacks**

**Pass the Hash**

If an attacker has a valid user hash they may impersonate that user against the KDC. User hashes can be extracted from SAM files in workstations or NTDS.DIT file of DCs, as well as from the lsass process memory (by using Mimikatz) where it is also possible to find cleartext passwords.

**Pass the Ticket**

If an attacker has a valid ticket they may impersonate that user, **HOWEVER**, the attacker must also have the **session key**. It’s possible to retrieve ticket by performing MITM over TCP/UDP, however, you cannot gain the session key that way. You could potentially use **Mimikatz** to to get ticket from lsass memory.

**Golden Ticket**

Using an NTLM hash of the krbtgt account, an attacker can build a TGT w/ a custom user & privileges. Example of generating a golden ticket & injecting it into process memory using Mimikatz ([Kerberos: Golden Tickets - Red Team Notes](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-golden-tickets))

**Silver Ticket**

A silver ticket is an attacker-generated TGS. In this case the **service key** is required, which is derived from service owner account. Nevertheless, it is not possible to sign correctly the PAC without krbtgt key. Therefore, if the service verifies the PAC, then this technique will not work

**Kerberoasting**

TGS contains an encrypted service key which is usually derived from the service account owner’s NTLM hash. Therefore if you obtain a TGS you may try to crack the NTLM hash. TGSs can be captured assuming you are a normal domain account since Kerberos doesn’t perform authorization checks.

**ASEPRoast**

If the attribute **DONT\_REQ\_PREAUTH** is set in a user account, then it is possible to build a KRB\_AS\_REQ message without specifying its password.

After that, the KDC will respond with a KRB\_AS\_REP message, which will contain some information encrypted with the user key. Thus, this message can be used to crack the user password.

**Escalating from Service / Network Account to Local Admin**

The “Network Service” account and the AppPool identities can act as the computer account in terms of Active Directory, they are only restrained locally. Therefore it is possible to invoke S4U2self if you run as one of these and request a service ticket for any user (e.g. someone with local admin rights, like DA) to yourself. There are however two minor obstacles to overcome:

To do so we need…

* a TGT or the computer accounts credentials to invoke S4U2self and we start with neither of both
* the SPN in the ticket returned by S4U2self is set to “Computername$” by default

**Retrieving a TGT:**

A usable TGT for the computer account can be acquired using @gentilkiwi’s tgt::deleg trick, explained here in the Rubeus [manual](https://github.com/GhostPack/Rubeus#tgtdeleg).![](https://content.gitbook.com/content/mGhYQRY1OEeL4zywZ9zS/blobs/93UVdiHHhPp4tpnyQtar/Unknown%20image)

**Fixing the SPN:**

With the TGT from the previous step, we can now invoke S4U2self to request a ticket for the User Chuck Norris, who is obviously a domain admin.

![](https://content.gitbook.com/content/mGhYQRY1OEeL4zywZ9zS/blobs/mom9cashRASfbVabomym/Unknown%20image)

Note however that the TGS is designated for the computer we’re currently running on, ADSEC-00$, which is **NOT** a valid SPN, therefore we cannot use this ticket for another host. **HOWEVER**, the SPN is unencrypted in the TGS, meaning we can modify it to whatever SPN we desire using Rubeus’ ***tgssub*** tool combined w/ ***altservice***.

![](https://content.gitbook.com/content/mGhYQRY1OEeL4zywZ9zS/blobs/LOO4lL4v45uWeiF7WE2N/Unknown%20image)

You can then copy the ticket to a different host, import it (you do not need local admin rights for that) and use the ticket.

![](https://content.gitbook.com/content/mGhYQRY1OEeL4zywZ9zS/blobs/SjGWbGQzqYDuq5aGfvXQ/Unknown%20image)

Using HTTP // PSRemoting from a different host we can authenticate as CNorris

![](https://content.gitbook.com/content/mGhYQRY1OEeL4zywZ9zS/blobs/FYEjWw38OI3FYwtYVaPS/Unknown%20image)

For more information on Rubeus see [A Detailed Guide on Rubeus - Hacking Articles](https://www.hackingarticles.in/a-detailed-guide-on-rubeus/). This whole article is from [Abusing Kerberos S4U2self for local privilege escalation :: Cyberstoph's blog](https://cyberstoph.org/posts/2021/06/abusing-kerberos-s4u2self-for-local-privilege-escalation/)

### **Glossary**

| **WORD**             | **DEFINITION**                                                                                                                                                                                             |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| ADCS                 | Active Directory Certificate Service                                                                                                                                                                       |
| CA                   | (Certificate Authority) — PKI server that issues certificates                                                                                                                                              |
| Certificate Template | a collection of settings and policies that defines the contents of a certificate issued by an enterprise CA                                                                                                |
| CSR                  | (Certificate Signing Request) — a message sent to a CA to request a signed certificate                                                                                                                     |
| Enterprise CA        | CA integrated with AD (as opposed to a standalone CA), offers certificate templates                                                                                                                        |
| LSASS                | Local Security Authority Subsystem Service, it verifies users logging on to a Windows computer or server, handles password changes, and creates access tokens. It also writes to the Windows Security Log. |
| PKI                  | (Public Key Infrastructure) — a system to manage certificates/public key encryption                                                                                                                        |
| EKU                  | (Extended/Enhanced Key Usage) — one or more object identifiers (OIDs) that define how a certificate can be used                                                                                            |
| UPN                  | user principal name, an identifier for an account used by SAN to associate certificates with multiple accounts                                                                                             |
| KDC                  | Key Distribution Center (KDC) is implemented as a domain service. It uses the Active Directory as its account database and the Global Catalog for directing referrals to KDCs in other domains             |
| Schannel             | (Secure Channel)                                                                                                                                                                                           |
| S4U2Proxy            | Service for User to Proxy                                                                                                                                                                                  |
| S4U2Self             | Service for User to Self                                                                                                                                                                                   |
