<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>Posts on Cyberstoph&#39;s blog</title>
        <link>https://cyberstoph.org/posts/</link>
        <description>Recent content in Posts on Cyberstoph&#39;s blog</description>
        <generator>Hugo -- gohugo.io</generator>
        <copyright>&lt;a href=&#34;https://creativecommons.org/licenses/by-nc/4.0/&#34; target=&#34;_blank&#34; rel=&#34;noopener&#34;&gt;CC BY-NC 4.0&lt;/a&gt;</copyright>
        <lastBuildDate>Mon, 21 Mar 2022 00:00:00 +0000</lastBuildDate>
        <atom:link href="https://cyberstoph.org/posts/index.xml" rel="self" type="application/rss+xml" />
        
        <item>
            <title>Detecting shadow credentials</title>
            <link>https://cyberstoph.org/posts/2022/03/detecting-shadow-credentials/</link>
            <pubDate>Mon, 21 Mar 2022 00:00:00 +0000</pubDate>
            
            <guid>https://cyberstoph.org/posts/2022/03/detecting-shadow-credentials/</guid>
            <description>A defenders perspective on msDS-KeyCredentialLink
TL;DR;
This article is about my journey into tracing changes to the msDS-KeyCredentialLink attribute to verify if their origin is legitimate or a potential attack (aka. Shadow Credentials). If you just want to know the &amp;ldquo;gist&amp;rdquo; of it, scroll down to the bottom and you&amp;rsquo;ll find a mindmap.
What&amp;rsquo;s msDS-KeyCredentialLink and why should I care? The msDS-KeyCredentialLink (aka. &amp;ldquo;kcl&amp;rdquo;) attribute can be used to link an RSA key pair with a computer or user object in order to authenticate with said key pair against the KDC to receive a Kerberos TGT.</description>
            <content type="html"><![CDATA[

<p><em>A defenders perspective on msDS-KeyCredentialLink</em></p>

<p><strong>TL;DR;</strong></p>

<p>This article is about my journey into tracing changes to the msDS-KeyCredentialLink attribute to verify if their origin is legitimate or a potential attack (aka. Shadow Credentials). If you just want to know the &ldquo;gist&rdquo; of it, scroll down to the bottom and you&rsquo;ll find a mindmap.</p>

<h2 id="what-s-msds-keycredentiallink-and-why-should-i-care">What&rsquo;s msDS-KeyCredentialLink and why should I care?</h2>

<p>The msDS-KeyCredentialLink (aka. &ldquo;kcl&rdquo;) attribute can be used to link an RSA key pair with a computer or user object in order to authenticate with said key pair against the KDC to receive a Kerberos TGT. So the kcl is in fact a set of alternate credentials that works alongside username/password. An excellent source of information around msDS-KeyCredentialLink is <a href="https://www.dsinternals.com/wp-content/uploads/eu-19-Grafnetter-Exploiting-Windows-Hello-for-Business.pdf" target="_blank">Michael Grafnetters talk at Black Hat 2019</a> and his famous powershell module <a href="https://github.com/MichaelGrafnetter/DSInternals" target="_blank">DSInternals</a>. I highly recommend you watch his talk since he also explains the relationship between msDS-KeyCredentialLink and Windows Hello for Business (WHfB).</p>

<p>Fast forward a couple of years, manipulating kcl has become a well-known attack technique known as &ldquo;Shadow Credentials&rdquo; and I especially recommend <a href="https://posts.specterops.io/shadow-credentials-abusing-key-trust-account-mapping-for-takeover-8ee1a53566ab" target="_blank">this article by Elad Shamir</a> and <a href="https://www.thehacker.recipes/ad/movement/kerberos/shadow-credentials" target="_blank">this documentation by Charlie Bromberg</a> for further details, if you are not familiar with the topic.
In a nutshell: if an attacker can write the kcl of an account, he/she will be able to impersonate that account either to gain access or for persistence. Write access to the kcl could be achieved through ACL-misconfigurations, control over another, high-privilged account or through relaying (NTLM) authentication. The NTLM-relay-scenario was in fact the one that made me look into this matter for a couple of reasons:</p>

<ul>
<li>It is available in a default setup if we focus on computer accounts. Microsoft closed PetitPotam but there are still other authentication triggers available like <a href="https://github.com/leechristensen/SpoolSample" target="_blank">good old spool sample</a> and also LDAP Signing is not enforced by default.</li>
<li>Tooling is publicly available. You can use the above mentioned original POC for coercing authentication or choose one of <a href="https://github.com/cube0x0/SharpSystemTriggers" target="_blank">these triggers</a>. Charlie Bromberg also pushed a <a href="https://github.com/SecureAuthCorp/impacket/pull/1249" target="_blank">customized version of ntlmrelayx</a> which supports shadow credentials.</li>
<li>And finally: it is not easy to reliably detect and that&rsquo;s what this whole post is about.</li>
</ul>

<h2 id="auditing-msds-keycredentiallink">Auditing msDS-KeyCredentialLink</h2>

<p>Manipulation of this attribute can be traced through the common &ldquo;Audit Directory Service Changes&rdquo; subcategory, resulting in an event <code>5136: A directory service object was modified</code>. Have a look at <a href="https://www.elastic.co/guide/en/security/7.17/prebuilt-rule-0-16-1-potential-shadow-credentials-added-to-ad-object.html" target="_blank">this post</a> by elastic on how to enable auditing and don&rsquo;t forget to set an appropriate SACL for user and computer objects.</p>

<p>Here&rsquo;s how such a malicious event looks like. The <code>Subject</code> refers to the actor and the <code>Object</code> is the account that was modified.</p>

<pre><code>A directory service object was modified.
	
Subject:
	Security ID:		NETCORP\evil
	Account Name:		evil
	Account Domain:	NETCORP
	Logon ID:		0xBCDAC

Directory Service:
	Name:	netcorp.at
	Type:	Active Directory Domain Services
	
Object:
	DN:	CN=pc1,OU=Client,OU=Computer,OU=company,DC=netcorp,DC=at
	GUID:	CN=pc1,OU=Client,OU=Computer,OU=company,DC=netcorp,DC=at
	Class:	computer
	
Attribute:
	LDAP Display Name:	msDS-KeyCredentialLink
	Syntax (OID):	2.5.5.7
	Value:	B:828:&lt;Binary&gt;:CN=adlab-01,OU=Client,OU=Computer,OU=company,DC=netcorp,DC=at
	
Operation:
	Type:	Value Added
	Correlation ID:	{5bff0e70-432c-4ae9-9081-06675dba7869}
	Application Correlation ID:	-
</code></pre>

<p>Now that we&rsquo;ve started collecting these events, we have to find ways to verify the legitimazy of a single event. For example, the subject and object are different in the above event, but is this always a useful indicator? It turns out the answer highly depends on your individual environment and varies if you refer to computer or user objects. Therefore, it&rsquo;s necessary to identify legitimate use-cases which invoke the modification of the kcl attribute. I will describe the two scenarios that seem the most commont to me in the following sections, however this is not a complete list. As Michael Grafnetter showed in his talk, there might be more (undocumented) use-cases.</p>

<p><img src="/img/9_whfb_grafnetter_1.png" alt="kclusage" /></p>

<h2 id="use-case-1-whfb-hybrid-azure-ad-joined-key-trust">Use-case 1 - WHfB Hybrid Azure AD Joined Key Trust</h2>

<p>If you search for information about kcl on the internet, you&rsquo;ll end up reading a lot about Windows Hello for Business (WHfB). There is a wealth of <a href="https://docs.microsoft.com/en-us/windows/security/identity-protection/hello-for-business/hello-how-it-works-provisioning" target="_blank">really good documentation</a> about WHfB available, which explains the details far more better than I ever could (including the talk by Michael Grafnetter mentioned earlier), so I won&rsquo;t cover it in this post.</p>

<p>The short story is: during WHfB enrollment, the user will generate a key pair and link the public key to the users object in AAD. During the next sync cycle, Azure AD Connect will sync this public key into the msDS-KeyCredentialLink attribute of the user object in on-prem AD, alongside a couple of other information. Note that this refers to a hybrid AAD join environment with WHfB enabled.</p>

<p>A modification event generated in such a scenario looks like this:</p>

<pre><code>A directory service object was modified.
	
Subject:
	Security ID:		netcorp\MSOL_8bee7c7b05af
	Account Name:		MSOL_8bee7c7b05af
	Account Domain:	netcorp
	Logon ID:		0xAFEC9F

Directory Service:
	Name:	netcorp.at
	Type:	Active Directory Domain Services
	
Object:
	DN:	CN=whfbuser,OU=WHFB,OU=DomainUser,OU=User,OU=company,DC=netcorp,DC=at
	GUID:	CN=whfbuser,OU=WHFB,OU=DomainUser,OU=User,OU=company,DC=netcorp,DC=at
	Class:	user
	
Attribute:
	LDAP Display Name:	msDS-KeyCredentialLink
	Syntax (OID):	2.5.5.7
	Value:	B:854:&lt;Binary&gt;:CN=whfbuser,OU=WHFB,OU=DomainUser,OU=User,OU=company,DC=netcorp,DC=at
	
Operation:
	Type:	Value Added
	Correlation ID:	{10148d86-8374-4197-84d6-586a201dfa4b}
	Application Correlation ID:	-
</code></pre>

<p>If you see an event like this in an environment without WHfB or even hybrid AAD join, then this is obviously a red flag. So for the following detection and verification workflow, we&rsquo;ll asume that we live in such an environment and want to make sure that it is in fact a legitimate event.</p>

<p>Let&rsquo;s try to go through the information we have. Focusing on the event data above, we see that subject/actor is the AAD Connect sync account. Usually, this should be the only account that modifies this attribute. Also, note that the object class is <code>user</code>. If a user enrolls for WHfB, the key is written to the user object and not to the computer object on which the user went through the enrollment.
The event also contains a Logon ID, which is a unique identifier to link the modification event 5136 to a logon event 4624. Here&rsquo;s the corresponding example.</p>

<pre><code>An account was successfully logged on.

Subject:
	Security ID:		NULL SID
	Account Name:		-
	Account Domain:		-
	Logon ID:		0x0

Logon Information:
	Logon Type:		3
	Restricted Admin Mode:	-
	Virtual Account:		No
	Elevated Token:		Yes

Impersonation Level:		Impersonation

New Logon:
	Security ID:		netcorp\MSOL_8bee7c7b05af
	Account Name:		MSOL_8bee7c7b05af
	Account Domain:		NETCORP.AT
	Logon ID:		0xAFEC9F
	Linked Logon ID:		0x0
	Network Account Name:	-
	Network Account Domain:	-
	Logon GUID:		{a095cd77-3ac7-c998-61d3-9995308dc76d}

Process Information:
	Process ID:		0x0
	Process Name:		-

Network Information:
	Workstation Name:	-
	Source Network Address:	fe80::2d5f:1c5a:ede5:89c8
	Source Port:		54856

Detailed Authentication Information:
	Logon Process:		Kerberos
	Authentication Package:	Kerberos
	Transited Services:	-
	Package Name (NTLM only):	-
	Key Length:		0
</code></pre>

<p>Keep an eye on the source network address in that event. This allows you to verify if the authentication actually came from the server running AAD Connect, which already gives you three indicators to verify:</p>

<ul>
<li>Is the subject the AAD Connect sync service account?</li>
<li>Is the object class &ldquo;user&rdquo;?</li>
<li>Is the corresponding authentication originating from the correct server?</li>
</ul>

<p>If you answer all three questions with &ldquo;yes&rdquo;, then that&rsquo;s already a strong argument I&rsquo;d say but we can go further. Let&rsquo;s have a look at the kcl attribute in AD using DSInternals.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-powershell" data-lang="powershell">Get-ADUser -Identity whfbuser -Properties * | select -expand msds-keycredentiallink | Get-ADKeyCredential</code></pre></div>
<p><img src="/img/9_whfb_kcl_1.png" alt="kclcontent" /></p>

<p>The user &ldquo;whfbuser&rdquo; got two credentials registered. Each credential is associated with a device ID, which maps to the device ID attribute of the computer object in AAD. At the time of this writing, public attack tools like <a href="https://github.com/eladshamir/Whisker" target="_blank">Whisker</a> just generate a random GUID since there is no real device to assoicate with. That&rsquo;s something we can check from a defensive point of view, using AzureAD powershell.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-powershell" data-lang="powershell">Get-AzureADDevice | ? {$_.deviceid <span style="color:#f92672">-eq</span> <span style="color:#e6db74">&#34;&lt;device-id&gt;&#34;</span>}</code></pre></div>
<p><img src="/img/9_whfb_kcl_2.png" alt="kclcontent" /></p>

<p>We can see that both credentials map to an existing device and we could now use information from a third-party database like a CMDB to check if these devices truely belong to the user. Again, this is not bulletproof depending on the access the attacker already has but still not that bad.
As a final verification step, we could reach out to the client to grab the generated public key and verify if this is really the same public key stored in the kcl attribute. Stephan Waelde describes how to follow a key from the device to Azure AD and back to on-prem AD in <a href="https://stephanwaelde.com/2020/02/24/azure-ad-join-single-sign-on-follow-the-key/" target="_blank">his blog post</a>, so I&rsquo;ll refer you to his guide.</p>

<p>Finally, we can put everything we&rsquo;ve learned up until now in a nice mindmap.</p>

<p><img src="/img/9_whfb_mindmap.png" alt="whfb-chart" /></p>

<h2 id="use-case-2-credential-guard">Use-case 2 - Credential Guard</h2>

<p>Usage of Credential Guard is one of the lesser known (at least as far as I know) triggers for kcl population. It is just briefly mentioned in <a href="https://docs.microsoft.com/en-us/windows-server/security/kerberos/domain-joined-device-public-key-authentication" target="_blank">this article</a> from Microsoft docs.</p>

<p><img src="/img/9_credguard_kcl_1.png" alt="credguard1" /></p>

<p>The corresponding event 5136 for this action looks like this.</p>

<pre><code>A directory service object was modified.
	
Subject:
	Security ID:		NETCORP\PC1$
	Account Name:		PC1$
	Account Domain:		NETCORP
	Logon ID:		0xA170D

Directory Service:
	Name:	netcorp.at
	Type:	Active Directory Domain Services
	
Object:
	DN:	CN=pc1,OU=Client,OU=Computer,OU=company,DC=netcorp,DC=at
	GUID:	CN=pc1,OU=Client,OU=Computer,OU=company,DC=netcorp,DC=at
	Class:	computer
	
Attribute:
	LDAP Display Name:	msDS-KeyCredentialLink
	Syntax (OID):	2.5.5.7
	Value:	B:754:&lt;Binary&gt;:CN=pc1,OU=Client,OU=Computer,OU=company,DC=netcorp,DC=at
	
Operation:
	Type:	Value Added
	Correlation ID:	{cb1839a0-32c4-4843-bf57-a5b5308dbd73}
	Application Correlation ID:	-
</code></pre>

<p>You can see that the subject and the object are the same, which makes it harder for us to draw a useful conclusion just from the event data. This becomes a bigger problem if we think about a malicious change that was introduced through NTLM-relay, as mentioned in the beginning.
Here&rsquo;s how this event looks after an NTLM-relay attack using ntlmrelayx.</p>

<pre><code>A directory service object was modified.
	
Subject:
	Security ID:		netcorp\PC1$
	Account Name:		PC1$
	Account Domain:		netcorp
	Logon ID:		0x125BAF

Directory Service:
	Name:	netcorp.at
	Type:	Active Directory Domain Services
	
Object:
	DN:	CN=pc1,OU=Client,OU=Computer,OU=company,DC=netcorp,DC=at
	GUID:	CN=pc1,OU=Client,OU=Computer,OU=company,DC=netcorp,DC=at
	Class:	computer
	
Attribute:
	LDAP Display Name:	msDS-KeyCredentialLink
	Syntax (OID):	2.5.5.7
	Value:	B:828:&lt;Binary&gt;:CN=pc1,OU=Client,OU=Computer,OU=company,DC=netcorp,DC=at
	
Operation:
	Type:	Value Added
	Correlation ID:	{971bae70-6821-4b8c-bdbf-dbb14101b21c}
	Application Correlation ID:	-
</code></pre>

<p>You don&rsquo;t see much difference? Me neither. You could go for the corresponding event 4624 again and check IP addresses but this is usually a less reliable source of information for clients and would also imply that you have things like DHCP logs. So let&rsquo;s have a look at msDS-KeyCredentialLink itself again. Note, that we&rsquo;re analysing the legitimate credential and not the one added by ntlmrelayx.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-powershell" data-lang="powershell">Get-ADComputer -Identity pc1 -Properties * | select -expand msds-keycredentiallink | Get-ADKeyCredential</code></pre></div>
<p><img src="/img/9_credguard_kcl_2.png" alt="kclcontent" /></p>

<p>If you compare this key-credential with the one from the previous use-case, you can see two of differences.</p>

<ul>
<li>The key source is <strong>AD</strong> instead of <strong>AzureAD</strong>.</li>
<li>There is no device ID since the key is already stored in the kcl of a device so that wouldn&rsquo;t make sense.</li>
</ul>

<p>Remember that tools like whisker and also ntlmrelayx automatically set a device ID by default, so they mimic the WHfB use-case discussed previously but actually raise a red-flag when it comes to the credentialguard use-case. That&rsquo;s good for starters, however you could obviously change the tools without much effort and then we&rsquo;re back at the beginning.</p>

<p>So why don&rsquo;t we compare the key on the device with the key in AD? It turns out, that the location and the structure of this key is not publicly documented by Microsoft. However, there&rsquo;s one man who already got us covered and it shouldn&rsquo;t be a surprise ;)</p>

<p><img src="/img/9_credguard_kcl_3.png" alt="kcl-mimikatz" /></p>

<p>Microsoft calls the structure this key is stored in a &ldquo;machine-bound certificate&rdquo; and Benjamin Delpy not only knows <a href="https://github.com/gentilkiwi/mimikatz/blob/e10bde5b16b747dc09ca5146f93f2beaf74dd17a/mimikatz/modules/kuhl_m_lsadump.c" target="_blank">where to find it</a> but also how to extract it. Nice.
Unfortunately, defenders can&rsquo;t usually just go around and randomly execute Mimikatz for various reasons, so I chose a less elegant way to &ldquo;reimplement&rdquo; the functionality. <a href="https://gist.github.com/cfalta/ad6a19656c84752b409c3d6e5fc9d0a2" target="_blank">This script</a> uses PSRemoting to grab the content of the <code>machineboundcertificate</code> registry value of the host and runs a byte-wise comparison with the content of the public key from the kcl attribute in AD (very quick and dirty - I know ^^).</p>

<p>Here&rsquo;s how the output of this script looks like.</p>

<p><img src="/img/9_credguard_kcl_4.png" alt="kcl-compare" /></p>

<p>A very opsec-concerned attacker could still work around this by also setting the content of the registry value correctly, but I think it&rsquo;s still an indicator worth looking at. Finally, it&rsquo;s mindmap time again.</p>

<p><img src="/img/9_credguard_mindmap.png" alt="whfb-chart" /></p>

<h2 id="conclusion">Conclusion</h2>

<p>Auditing msDS-KeyCredentialLink changes is easy, verifying a change is not and heavily depends on a solid knowledge of what&rsquo;s &ldquo;normal&rdquo; in your environment. I hope this post allows you to save some time during the process. It took me quite a bit to get this sorted out so far, but I still have the strong feeling that I&rsquo;m missing something (or a lot). So if you read this and know more than I do, I&rsquo;d happy if you could let me know.
That said, here&rsquo;s another mindmap because #MindMapsAreFun :)</p>

<p><img src="/img/9_final_mindmap.png" alt="finalmindmap" /></p>
]]></content>
        </item>
        
        <item>
            <title>After the storm - how to move on with NTLM</title>
            <link>https://cyberstoph.org/posts/2021/09/after-the-storm-how-to-move-on-with-ntlm/</link>
            <pubDate>Fri, 24 Sep 2021 00:00:00 +0000</pubDate>
            
            <guid>https://cyberstoph.org/posts/2021/09/after-the-storm-how-to-move-on-with-ntlm/</guid>
            <description>I remember that, about 15 years ago, we already flagged the absence of SMB signing as a vulnerability in reports. Though at that time, we circled more around the theoretical risk of someone tampering SMB traffic due to the lack of integrity protection. None of us really had an idea how to make use of that vulnerability. The later obviously changed.
July 2021 came and brought with it a storm of various Print Spooler RCEs (PrintNightmare), one of the simplest LPE&amp;rsquo;s Windows has seen (HiveNightmare,seriousSAM) and a little hippo (PetitPotam) who anchored the &amp;ldquo;NTLM problem&amp;rdquo; in the center of our attention.</description>
            <content type="html"><![CDATA[

<p>I remember that, about 15 years ago, we already flagged the absence of SMB signing as a vulnerability in reports. Though at that time, we circled more around the theoretical risk of someone tampering SMB traffic due to the lack of integrity protection. None of us really had an idea how to make use of that vulnerability. The later obviously changed.</p>

<p>July 2021 came and brought with it a storm of various Print Spooler RCEs (PrintNightmare), one of the simplest LPE&rsquo;s Windows has seen (HiveNightmare,seriousSAM) and a little hippo (PetitPotam) who anchored the &ldquo;NTLM problem&rdquo; in the center of our attention. Now as the storm has passed, we&rsquo;re confronted with a familiar question: &ldquo;how to get rid of NTLM?&rdquo;. And the unhappy truth is, we won&rsquo;t - at least not in the near future.</p>

<p>NTLM as a technology is backed in so deep in the Windows operating system that the only realistic move away from NTLM would be during the transition to a new operating system version (like Windows 11) cause that&rsquo;s how IT departments can handle these kinds of changes. However, it seems that this train has already passed. Windows 11 will bring us a centered start menu and rounded corners but probably nothing new with regards to NTLM. How to move on then?</p>

<h2 id="short-term-strategies">Short-term strategies</h2>

<p>The attack-vector at hand relies on the combination of coercing an NTLM authentication through either <a href="https://github.com/leechristensen/SpoolSample" target="_blank">SpoolSample/Printerbug</a> or <a href="https://github.com/topotam/PetitPotam" target="_blank">PetitPotam</a> and then forwarding that to a useful target, like the LDAP service of the DC. Why Microsoft tries to <a href="https://msrc.microsoft.com/update-guide/vulnerability/ADV210003" target="_blank">center this issue around Active Directory Certificate Services (ESC8)</a>, though this is just one possible avenue of attack is beyond my imagination. That information misguides customers into thinking that they are not at risk if they don&rsquo;t have an ACDS web interface running, which is dangerously wrong.</p>

<p>Anyway, the graphic below outlines two possible ways how this attack can play out from start to end.</p>

<p><img src="/img/8_ntlmrelay1.png" alt="ntlmrelay1" /></p>

<p>The path above uses the <code>msDS-KeyCredential</code> attribute to add a certificat to the account which in turn allows to request a TGT via PKINIT. The path below sets the <code>msDS-AllowedToActOnBehalfOfOtherIdentity</code> attribute, which configures resource-based constrained delegation. This gives an account of your choosing the right to delegate against the victim, so you can use S4U2Self/S4U2Proxy to get a service ticket in the name of a domain admin and on we go.</p>

<p>If the last two sentences do not make any sense to you, then I recommend <a href="https://www.harmj0y.net/blog/activedirectory/a-case-study-in-wagging-the-dog-computer-takeover/" target="_blank">this article</a> on RBCD by Will Schroeder and <a href="https://posts.specterops.io/shadow-credentials-abusing-key-trust-account-mapping-for-takeover-8ee1a53566ab" target="_blank">this article</a> on Shadow Credentials by Elad Shamir.</p>

<p>As you can see, regardless of the attack path, there are always a couple of different steps necessary. If you take a closer look at each step of the attack, you&rsquo;ll notice that you can put specific mitigations in place for every step. In fact, defenders have various possibilities to break this attack throughout the way. Let&rsquo;s visualice that and have a look at the graphic again.</p>

<p><img src="/img/8_ntlmrelay2.png" alt="ntlmrelay2" /></p>

<p>The most effective way to break these attacks in the current situation is to prevent coercion of authentication, so you stop the attack at step one. Effective in this case means with regards to the current situation. To quote my history teacher: &ldquo;there&rsquo;s a difference between the trigger and the source of a problem&rdquo;.</p>

<p>If you remove PetitPotam/SpoolSample from the attack, you just kill the trigger but not the source. The source is the weakness of NTLM against relay attacks and if another PetitPotam is discovered next months, we&rsquo;ll start all over again.</p>

<p>Therefore, the most sustainable measure would be to remove NTLM from the game, but let&rsquo;s discuss this in the next section. Focusing at the first path in the graphic above, you could also break the attack at the last step through disabling RC4 for Kerberos. Since you can only create RC4 silver tickets with an NTLM hash, this would thwart the whole attack path and is also relatively (sigh&hellip;) easy to implement if you focus on computer accounts and ignore user-based service accounts for the moment.</p>

<p>The point I want to make here is: if you draw these graphics for all attack paths you can identify in your environment, you can find the choke points that are the easiest for you to implement in short time. This will likely not result in the best solution, but in a solution that works in your indiviudal environment.</p>

<h2 id="long-term-strategies">Long-term strategies</h2>

<p>As mentioned earlier, removing NTLM from the equation entirely is something only Microsoft can initiate, and it seems to me that they have chosen another path. That leaves us with two options to prevent NTLM relay sustainably:
1. enforce signing on all relevant protocols (at least SMB, LDAP, HTTP)
2. disable NTLM for network authentication</p>

<p>Going for signing will probably be easier to achieve if you live in a relatively homogeneous Microsoft environment, but leaves the risk of a future, yet to be discovered, NTLM based attack to break your neck again. Disabling NTLM is better from a long-term perspective but could result in any number of applications breaking. You might also notice that some very common Microsoft applications rely heavily on NTLM by default (talking about you, Exchange!).</p>

<p>My recommendation would be to set this up as an internal project or whatever the best formal definition in your environment is to get a hand on manpower and do two things:</p>

<p>first, build awareness that NTLM needs to die (probably find better wording). This is our stretch goal. It won&rsquo;t happen any time soon but it&rsquo;s good to know where we&rsquo;re heading. Make sure that any new application works without NTLM e.g., by <a href="https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/network-security-restrict-ntlm-outgoing-ntlm-traffic-to-remote-servers" target="_blank">disabling NTLM via GPO</a> on all new servers you bring to production.</p>

<p>Second, enforce signing step-by-step. Start with LDAP, since this is the most relevant vector for the attacker.
If you can remove LDAP from the equation, you remove the attacks that are possible by design like RBCD (see previous section), which should tremendously reduce the attack surface. This buys you time to implement SMB signing and you&rsquo;ll need that time since SMB signing almost certainly breaks stuff.</p>

<p>Regardeless of what you do though, the most important thing is to start now. It&rsquo;s time to get rid of that evil called NTLM who is whipping our assess since Hernan Ochoa released WCE 10 years ago. Yes - TEN YEARS AGO! The storm is over&hellip;let&rsquo;s rebuild :-)</p>
]]></content>
        </item>
        
        <item>
            <title>Abusing Kerberos S4U2self for local privilege escalation</title>
            <link>https://cyberstoph.org/posts/2021/06/abusing-kerberos-s4u2self-for-local-privilege-escalation/</link>
            <pubDate>Sat, 26 Jun 2021 00:00:00 +0000</pubDate>
            
            <guid>https://cyberstoph.org/posts/2021/06/abusing-kerberos-s4u2self-for-local-privilege-escalation/</guid>
            <description>TL;DR;
S4U2self can be abused for local privilege escalation (think: Network Service to Local Admin). This is not something new, it&amp;rsquo;s just the first time I actually ran through the steps myself so why not write a post about it. The attack is covered briefly in the Rubeus manual and in more detail in this post by Charlie Clark, which I recommend you read. I won&amp;rsquo;t explain S4U in this post so if you are not familiar with the topic, read this post on constrained delegation first.</description>
            <content type="html"><![CDATA[

<p><strong>TL;DR;</strong></p>

<p>S4U2self can be abused for local privilege escalation (think: Network Service to Local Admin). This is not something new, it&rsquo;s just the first time I actually ran through the steps myself so why not write a post about it. The attack is covered briefly in the <a href="https://github.com/GhostPack/Rubeus#constrained-delegation-abuse" target="_blank">Rubeus manual</a> and in more detail in <a href="https://exploit.ph/revisiting-delegate-2-thyself.html" target="_blank">this post</a> by Charlie Clark, which I recommend you read.
I won&rsquo;t explain S4U in this post so if you are not familiar with the topic, read <a href="http://www.harmj0y.net/blog/activedirectory/S4U2pwnage/" target="_blank">this post</a> on constrained delegation first.</p>

<h2 id="s4u2self-and-service-accounts">S4U2self and service accounts</h2>

<p>Though constrained delegation needs to be specifically enabled on an account to &ldquo;make it work&rdquo; across systems in terms of S4U2proxy, S4U2self can be invoked by any principal with an SPN. From a conceptual perspective it does not seem like much at first, since you can&rsquo;t use the ticket to invoke S4U2proxy, which means that you end up with a ticket for yourself. And you already are you, so no problem here right?</p>

<p>It depends. If you already have administrative privileges on a computer, then the ticket really is of no use for you. But if you think about a common local privilege escalation scenario in which you managed to compromise a restriced service like IIS (running as AppPool user) or MSSQL (running as network service by default), that ticket can be quite valuable.</p>

<p>The &ldquo;Network Service&rdquo; 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:</p>

<ul>
<li>we need a TGT or the computer accounts credentials to invoke S4U2self and we start with neither of both</li>
<li>the SPN in the ticket returned by S4U2self is set to &ldquo;Computername$&rdquo; by default</li>
</ul>

<h2 id="getting-the-tgt">Getting the TGT</h2>

<p>A usable TGT for the computer account can be acquired using <a href="https://twitter.com/gentilkiwi" target="_blank">@gentilkiwi</a>&rsquo;s <code>tgt::deleg</code> trick, explained <a href="https://github.com/GhostPack/Rubeus#tgtdeleg" target="_blank">here</a> in the Rubeus manual.</p>

<pre><code>Invoke-Rubeus -Command &quot;tgtdeleg /nowrap&quot;
</code></pre>

<p><img src="/img/7_tgtdeleg.png" alt="tgtdeleg" /></p>

<h2 id="fixing-the-spn">Fixing the SPN</h2>

<p>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.</p>

<pre><code>Invoke-Rubeus -Command &quot;s4u /self /nowrap /impersonateuser:cnorris /ticket:base64blobhere...&quot;
</code></pre>

<p><img src="/img/7_s4u2self.png" alt="tgtdeleg" /></p>

<p>Here&rsquo;s how the resulting ticket looks like. As you can see, it is issued to &ldquo;ADSEC-00$&rdquo; which is the name of the computer we are running on.</p>

<p><img src="/img/7_describe.png" alt="tgtdeleg" /></p>

<p>We cannot use this ticket from another host since it is not issued to a valid SPN for our usecase. Luckily, the SPN is not part of the protected information inside the ticket and we can simply change it. Rubeus offers a command called <code>tgssub</code> to do just that, which is also explained in the <a href="https://github.com/GhostPack/Rubeus#tgssub" target="_blank">manual</a>. Use it together with the <code>/altservice</code> switch to provide a different SPN.</p>

<pre><code>Invoke-Rubeus -Command &quot;tgssub /altservice:http/adsec-00.contoso.com /ticket:base64blobhere... &quot;
</code></pre>

<p><img src="/img/7_tgssub.png" alt="tgtdeleg" /></p>

<p>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.</p>

<p><img src="/img/7_tgssub_ptt.png" alt="tgtdeleg" /></p>

<p>In the screenshot below we are using PSRemoting (hence the HTTP/.. SPN).</p>

<p><img src="/img/7_tgssub_ptt_2.png" alt="tgtdeleg" /></p>

<h2 id="conclusion">Conclusion</h2>

<p>I think this is a very stable alternative to the various potatoe vectors. If you previously considered processes running as <code>LOCAL SYSTEM</code> as your main target for local privilege escalation, you can now safely increase your scope. As long as you have access to another computer in the domain, chances are very high that this will work.</p>
]]></content>
        </item>
        
        <item>
            <title>Fun with processes - Suspend and Resume</title>
            <link>https://cyberstoph.org/posts/2021/05/fun-with-processes-suspend-and-resume/</link>
            <pubDate>Mon, 03 May 2021 00:00:00 +0000</pubDate>
            
            <guid>https://cyberstoph.org/posts/2021/05/fun-with-processes-suspend-and-resume/</guid>
            <description>Did you ever wonder how process suspension in Windows works? Nevermind, I&amp;rsquo;m writing this anyway.
Since you&amp;rsquo;re reading this blog you&amp;rsquo;re either totatlly lost or into Windows anyway. So I assume you alread tried suspending and resuming a process with process explorer for example. There are actually different ways to suspend a process and we&amp;rsquo;ll go with the one that&amp;rsquo;s officially undocumented (more fun).
NTSuspendProcess The API we&amp;rsquo;re using is called NTSuspendProcess and lives inside NTDLL.</description>
            <content type="html"><![CDATA[

<p>Did you ever wonder how process suspension in Windows works? Nevermind, I&rsquo;m writing this anyway.</p>

<p>Since you&rsquo;re reading this blog you&rsquo;re either totatlly lost or into Windows anyway. So I assume you alread tried suspending and resuming a process with process explorer for example. There are actually different ways to suspend a process and we&rsquo;ll go with the one that&rsquo;s officially undocumented (more fun).</p>

<h2 id="ntsuspendprocess">NTSuspendProcess</h2>

<p>The API we&rsquo;re using is called <strong>NTSuspendProcess</strong> and lives inside NTDLL. It is not documented officially as mentioned above, however it is already well known for years and you find a lot of information about it on the internet. It looks like this:</p>

<pre><code>[DllImport(&quot;ntdll.dll&quot;, PreserveSig = false)]
public static extern void NtSuspendProcess(IntPtr processHandle);
</code></pre>

<p>Quite simple, the only thing we need is a process handle with the appropriate (= ALL) permissions. And you might already guessed it, resuming the process works the same way.</p>

<pre><code>[DllImport(&quot;ntdll.dll&quot;, PreserveSig = false, SetLastError = true)]
public static extern void NtResumeProcess(IntPtr processHandle);
</code></pre>

<p>To make things work, we also need <strong>OpenProcess</strong> and <strong>CloseHandle</strong> from kernel32 to acquire and release the process handle.</p>

<pre><code>[DllImport(&quot;kernel32.dll&quot;, SetLastError = true)]
public static extern IntPtr OpenProcess(ProcessAccessFlags processAccess,bool bInheritHandle,int processId);
[DllImport(&quot;kernel32.dll&quot;, SetLastError=true)]
public static extern bool CloseHandle(IntPtr hObject)
</code></pre>

<p>And that&rsquo;s it. Nothing fancy here today ;-)</p>

<p>If you&rsquo;re interested, <a href="https://github.com/cfalta/PoshRandom/blob/master/ProcessSuspendResume.ps1" target="_blank">here&rsquo;s a Powershell function</a> to play with.</p>

<p><img src="/img/6_processsuspendresume_1.png" alt="suspendresume" /></p>
]]></content>
        </item>
        
        <item>
            <title>ConvertTo-Powershell - wrapping applications with PS</title>
            <link>https://cyberstoph.org/posts/2020/09/convertto-powershell-wrapping-applications-with-ps/</link>
            <pubDate>Sun, 06 Sep 2020 00:00:00 +0000</pubDate>
            
            <guid>https://cyberstoph.org/posts/2020/09/convertto-powershell-wrapping-applications-with-ps/</guid>
            <description>TL;DR; The newest addition to PSArmoury is a small utility script called ConvertTo-Powershell. It allows to &amp;ldquo;convert&amp;rdquo; a C# console application into a powershell script or in other words it creates a .ps1 file from a .exe file. This can be useful for bypassing AWL or AV software and if you are a similar PS-lunatic like myself, it&amp;rsquo;s also just fun :-)
From exe to ps1 If you read one of my previous posts, you might already know that I prefer to do stuff in Powershell.</description>
            <content type="html"><![CDATA[

<h2 id="tl-dr">TL;DR;</h2>

<p>The newest addition to PSArmoury is a small utility script called <a href="https://github.com/cfalta/PowerShellArmoury/blob/master/ConvertTo-Powershell.ps1" target="_blank">ConvertTo-Powershell</a>. It allows to &ldquo;convert&rdquo; a C# console application into a powershell script or in other words it creates a .ps1 file from a .exe file.
This can be useful for bypassing AWL or AV software and if you are a similar PS-lunatic like myself, it&rsquo;s also just fun :-)</p>

<h2 id="from-exe-to-ps1">From exe to ps1</h2>

<p>If you read one of my previous posts, you might already know that I prefer to do stuff in Powershell. One of my pet projects is the PowerShellArmoury, which allows you to store other PowerShell code in a single, encrypted .ps1-file called a &ldquo;loader&rdquo;. The loader, when invoked, tries to bypass the Windows Anti-Malware-Scan-Interface (AMSI) and then decrypts and loads the original Powershell code in the current session.</p>

<p>That works pretty well for Powershell but since pure .NET is the popular kid in town right now, more and more fancy tools are written in C# and no longer in PS. Therefore, I was looking for a way to integrate things like <a href="https://github.com/GhostPack/" target="_blank">Ghostpack</a> into my existing armoury and found the solution pretty much at the end of the <a href="https://github.com/GhostPack/Rubeus#sidenote-running-rubeus-through-powershell" target="_blank">Rubeus wiki</a>.</p>

<pre><code>$RubeusAssembly = [System.Reflection.Assembly]::Load([Convert]::FromBase64String(&quot;aa...&quot;))
</code></pre>

<p>The command above uses the <code>System.Reflection</code> namespace to load a compiled C# console application into your active Powershell session. You can then execute the methods within directly from Powershell. Pretty cool I&rsquo;d say but how does it work?</p>

<h2 id="a-quick-peak-into-reflection">A quick peak into reflection</h2>

<p>First of all: I am not a software developer and I never learned software engineering. So if you find any conceptual mistakes or other nonsense in this post, please let me know so I can learn :)
That said, let&rsquo;s take a quick look at the concept of &ldquo;reflection&rdquo; in the .NET framework.</p>

<p>Reflection allows you to programmatically obtain information about .NET assemblies (.exe and .dll files written in .NET). In other words: you can write a .NET application that dynamically interacts with other, already compiled, .NET applications on your system. But the classes in the <code>Reflection.Assembly</code> namespace not only allow to query classes, methods and attributes from assemblies but also to instantiate new objects from these classes (=run them).</p>

<p>To get started, you need the <code>[System.Reflection.Assembly]::Load</code>-class. If you have a look at the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly.load?view=netframework-4.8" target="_blank">docs</a>, you&rsquo;ll see that we can load an assembly by handing a base64 encoded blob of the assembly to the <code>Load</code>-function.</p>

<p><img src="/img/5_assemblyload.png" alt="assemblyload" /></p>

<p>That&rsquo;s espescially useful since converting stuff into base64 means we can embed it into a PS script</p>

<p><code>$file = [Convert]::ToBase64String([IO.File]::ReadAllBytes(&quot;.\Rubeus.exe&quot;))</code></p>

<p>Next, we create an object of type <a href="https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly?view=netframework-4.8" target="_blank">assembly</a></p>

<p><code>$Assembly = [System.Reflection.Assembly]::Load([Convert]::FromBase64String($file))</code></p>

<p>Now we are able to enumerate the available types. The screenshot below is an excerpt of Rubeus.</p>

<p><code>$Assembly.GetTypes()</code></p>

<p><img src="/img/5_availabletypes.png" alt="availabletypes" /></p>

<p>Also of interest to our specific usecase is the entrypoint.</p>

<p><code>$Assembly.EntryPoint | select Name,ReflectedType,Module</code></p>

<p><img src="/img/5_entrypoint.png" alt="entrypoint" /></p>

<p>The image above tells us that the operating system would start execution of <code>Rubeus.exe</code> in the function <code>Main</code> of the namespace/class <code>Rubeus.Program</code>. If we want to run Rubeus manually, that&rsquo;s the information we need.</p>

<h2 id="convertto-powershell">ConvertTo-Powershell</h2>

<p>With the knowledge about the entrypoint, we&rsquo;ve got all we need to automatically create a .ps1 wrapper for a given .NET assembly.</p>

<p><strong>Step 1 - Load the assembly and get the entrypoint</strong></p>

<pre><code>function Get-EntryPoint
{
    [CmdletBinding()]
    Param (
    [Parameter(Mandatory = $true)]
    [ValidateScript({Test-Path $_})]
    [String]
    $Path)

    $item = Get-Item -Path $Path
    $file = [Convert]::ToBase64String([IO.File]::ReadAllBytes($item.FullName))
    $Assembly = [System.Reflection.Assembly]::Load([Convert]::FromBase64String($file))
    $Assembly.EntryPoint
}
</code></pre>

<p><strong>Step 2 - Build the command that will execute the entrypoint in the wrapper script</strong></p>

<pre><code>$ep = Get-EntryPoint -Path C:\path\yourfile.exe
$ldrcommand = &quot;[&quot; + $ep.reflectedtype.namespace + &quot;.&quot; + $ep.reflectedtype.name + &quot;]::&quot; + $ep.name + '($Command.Split(&quot; &quot;))'
</code></pre>

<p>Note that we&rsquo;ll also pass commandline parameters to <code>$ep.name</code> through the use of the <code>$Command</code> parameter. The later will be available in the wrapper script.</p>

<p><strong>Step 3 - combine</strong></p>

<p>Finally, we&rsquo;ll put these two things together in addition to some standard PSArmoury routines for encryption/decryption and AV bypass as needed. The result will be a .ps1 file, which contains the base64-encoded (and encrypted) assembly as well as the information on how to invoke it directly from PowerShell as described above. Have a look at the last two lines in the screenshot below.</p>

<p><img src="/img/5_finalexample1.png" alt="finalexample1" /></p>

<p>And that&rsquo;s it. Feel free to try and let me know what I missed (pretty sure I missed something ;-) ). Here&rsquo;s an example for how to use it.</p>

<p><img src="/img/5_finalexample2.png" alt="finalexample1" /></p>

<p>One last note: if you get an error message like the one below when running ConvertTo-Powershell, then that&rsquo;s probably AMSI complaining about the file you want to convert. In my example, thats Rubeus.exe.</p>

<p><img src="/img/5_finalexample3.png" alt="finalexample1" /></p>

<p>So don&rsquo;t forget to disable or bypass AMSI on the machine you use to convert. The AMSI bypass that comes with ConvertTo-Powershell is only executed in the .ps1 files you create but not in the builder function. You can find a standalone version of that one <a href="https://github.com/cfalta/PoshRandom/blob/master/Disable-AMSI.ps1" target="_blank">over here</a></p>
]]></content>
        </item>
        
        <item>
            <title>PSArmoury 1.4 - now with even more armour</title>
            <link>https://cyberstoph.org/posts/2020/02/psarmoury-1.4-now-with-even-more-armour/</link>
            <pubDate>Fri, 28 Feb 2020 00:00:00 +0000</pubDate>
            
            <guid>https://cyberstoph.org/posts/2020/02/psarmoury-1.4-now-with-even-more-armour/</guid>
            <description>TL;DR; I recently added some improvements to PSArmoury, which I like to share with you in this post
 Support for BlockDLL process mitigation to protect your armoury New config parameter that lets you choose the branch in github Simple way to create an armoury from a local file Automatic inventory function  Still reading? Great, let&amp;rsquo;s go.
Introducing BlockDLL process mitigation Thanks to the great C# port of @_RastaMouse it was very easy to implement a process mitigation, that was actually meant to protect processes from malicious injections.</description>
            <content type="html"><![CDATA[

<h2 id="tl-dr">TL;DR;</h2>

<p>I recently added some improvements to <a href="https://github.com/cfalta/PowerShellArmoury" target="_blank">PSArmoury</a>, which I like to share with you in this post</p>

<ul>
<li>Support for BlockDLL process mitigation to protect your armoury</li>
<li>New config parameter that lets you choose the branch in github</li>
<li>Simple way to create an armoury from a local file</li>
<li>Automatic inventory function</li>
</ul>

<p>Still reading? Great, let&rsquo;s go.</p>

<h2 id="introducing-blockdll-process-mitigation">Introducing BlockDLL process mitigation</h2>

<p>Thanks to the great <a href="https://gist.github.com/rasta-mouse/af009f49229c856dc26e3a243db185ec" target="_blank">C# port of @_RastaMouse</a> it was very easy to implement a process mitigation, that was actually meant to protect processes from malicious injections. By setting a special <a href="https://docs.microsoft.com/en-gb/windows/win32/api/winnt/ns-winnt-process_mitigation_binary_signature_policy" target="_blank">flag</a> in the extended startupinfo of a new process, we can prevent any non-microsoft DLL from loading into that process. This can prevent certain EDR solutions from detecting well-known tools inside powershell.</p>

<p>To use this with PSArmoury, just create your armoury with the <code>-EnhancedArmour</code> switch like shown below.</p>

<p><img src="/img/4_blockdll_1.PNG" alt="blockdll1" /></p>

<p>Note that this will change your user experience a bit. If you try to load an enhanced Armoury it will not decrypt it&rsquo;s content but start a new, protected powershell process and ask you to run it in there manually again. This might seem a bit cumbersome at first but the reasons are simple:</p>

<ul>
<li>We could also apply the process mitigation policy to the first powershell process we run in (just use Set-ProcessMitigation) but at that point, the process already started and any EDR/AV DLL already runs in that process. Therefore, we need to create a new, clean process.</li>
<li>There are various ways to automatically run your armoury in the second powershell process, but then again this might raise a red flag itself so I went for the manual approach.</li>
</ul>

<p>So to use it, just run your armoury as usual and it will guide you through the rest of the process as shown below.</p>

<p><img src="/img/4_blockdll_2.PNG" alt="blockdll1" /></p>

<h2 id="choose-github-branch">Choose github branch</h2>

<p>Every item of type &ldquo;GitHubRepo&rdquo; in your configuration file can now contain an attribute called &ldquo;Branch&rdquo;. If it exists, PSArmoury will try to use the branch name supplied in this attribute. If it does not exist, it will use the default branch as before. In the sample config you find on github, we use this attribute to download the dev branch of PowerSploit instead of the master.</p>

<pre><code>    {
        &quot;Name&quot;:  &quot;PowerSploit&quot;,
        &quot;Type&quot;:  &quot;GitHubRepo&quot;,
        &quot;URL&quot;:  &quot;https://api.github.com/repos/PowerShellMafia/PowerSploit&quot;,
        &quot;Branch&quot;: &quot;dev&quot;,
        &quot;FileInclusionFilter&quot;:	&quot;*.ps1&quot;,
        &quot;FileExclusionFilter&quot;:	[&quot;*.tests.ps1&quot;]
    }
</code></pre>

<h2 id="create-armoury-from-file">Create armoury from file</h2>

<p>PSArmoury now offers a simple way to create an armoury from a local file. This comes in handy if you just want to quickly protect one (or many) powershell scripts you have on your disk without the need to create a config file.
Just run PSArmoury with the <code>-FromFile</code> switch and pass it the path to a file or folder containing powershell scripts. You can omit the <code>-Config</code>-switch but note that only files with an extension of <code>*.ps1</code> will be included.</p>

<p><img src="/img/4_fromfile.PNG" alt="fromfile" /></p>

<h2 id="inventory">Inventory</h2>

<p>I occassionally find myself in the situation where I don&rsquo;t remember what scripts I put inside an armoury, espescially when it&rsquo;s been some time since I created it. Since everything of relevance is encrypted in the file on disk, it is not so easy to get that information.
Therefore every armoury now contains an inventory function called <code>Get-PSArmoury</code>, which will print the names of all files included to stdout. This function is built dynamically during creation of the armoury.</p>

<p><img src="/img/4_inventory.PNG" alt="fromfile" /></p>

<p>That&rsquo;s it for now. If you are using PSArmoury and experience any issues or have ideas for new features, I would be happy to hear from you. Just send me a mail or open an issue on github.</p>

<p>Have a nice weekend!</p>
]]></content>
        </item>
        
        <item>
            <title>An introduction to Golden Certificates</title>
            <link>https://cyberstoph.org/posts/2019/12/an-introduction-to-golden-certificates/</link>
            <pubDate>Sat, 07 Dec 2019 00:00:00 +0000</pubDate>
            
            <guid>https://cyberstoph.org/posts/2019/12/an-introduction-to-golden-certificates/</guid>
            <description>TL;DR I wrote in one of my previous posts about how control over a certificate template of any kind can be abused to get a Smartcard certificate for a domain admin. In this post, I want to write a little bit more about the persistence capabilities this approach has to offer, as well as how you can detect it. I call this approach a &amp;ldquo;golden certificate&amp;rdquo; as a tribute to Benjamin Delpys famous &amp;ldquo;golden ticket&amp;rdquo;.</description>
            <content type="html"><![CDATA[

<h2 id="tl-dr">TL;DR</h2>

<p>I wrote in <a href="https://cyberstoph.org/posts/2019/11/introducing-poshadcs/" target="_blank">one of my previous posts</a> about how control over a certificate template of any kind can be abused to get a Smartcard certificate for a domain admin. In this post, I want to write a little bit more about the persistence capabilities this approach has to offer, as well as how you can detect it.
I call this approach a &ldquo;golden certificate&rdquo; as a tribute to Benjamin Delpys famous &ldquo;golden ticket&rdquo;. The lifetime will not be as long as the one of a golden ticket since certificate lifetime is subject to some boundaries as described below, However it will usually be at least a year - so pretty much time for the attacker anyway.</p>

<p><img src="/img/3_willywonkacertmeme.jpg" alt="wonka" /></p>

<p>Credits go to the folks at <a href="https://www.sysadmins.lv/blog-en/" target="_blank">sysadmins.lv</a>, which is an excellent source on PKI related stuff and (as always) Will Schroeder for gifting us with <a href="https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1" target="_blank">PowerView</a>.</p>

<h2 id="recap">Recap</h2>

<p>Certificate templates are objects in Active Directory that are used as a form of decentralized configuration by Active Directory integrated Certificate Authorities (Active Directory Certificate Services - ADCS). Certificate templates are normally used for a certain purpose (e.g. computer certificates, S/MIME certificates,&hellip;) but that&rsquo;s just how it looks for the Administrator. They are all the same kind of object and if you have write access on the object itself, you can just reconfigure a computer template or any other template to be a smartcard template that accepts arbitrary user names :-). How do we get there?</p>

<h2 id="finding-vulnerable-templates">Finding vulnerable templates</h2>

<p>You can find target accounts with PoshADCS. Just download it from <a href="https://github.com/cfalta/PoshADCS" target="_blank">Github</a> and also don&rsquo;t forget <a href="https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/PowerView.ps1" target="_blank">PowerView</a>, since we rely on that. First import both into your current PowerShell session.</p>

<pre><code>cat -raw PowerView.ps1 | iex
cat -raw ADCS.ps1 | iex
</code></pre>

<p>Then run Get-ADCSTemplateACL to query the ACLs of all certificate templates in the current domain. You can use one of the predefined filters to reduce the results since all templates have a couple of default ACEs that allow access for default groups (e.g. Domain Admins).</p>

<ul>
<li><strong>-Filter AdminACEs</strong> will remove the ACEs of default administrative groups from the output.</li>
<li><strong>-Filter DefaultACEs</strong> will remove administrative ACEs like above, but will also hide other default groups (e.g. Domain Computers on a computer template).</li>
</ul>

<p>This is useful if you are looking for permissions that have been set explicitly in your environment and grant access to custom users or groups.</p>

<pre><code>Get-ADCSTemplateACL -Filter DefaultACEs
</code></pre>

<p>In our example below, we see that the user &ldquo;John&rdquo; has been granted explicit write permissions on the computer template.</p>

<p><img src="/img/3_templatewritepermissions.PNG" alt="TemplatePermissions" /></p>

<p>If we can get hold of this users credentials, we can use these to get a smartcard certificate for a domain admin or basically any other user you would like to impersonate. The <code>Get-SmartCardCertificate</code> function inside PoshADCS allows us to do just that. But more on that later.</p>

<h2 id="lifetime-of-a-golden-certificate">Lifetime of a Golden Certificate</h2>

<p>The maximum certificate lifetime will be the shortest of the following:</p>

<ul>
<li><p>the validity time configured in the certificate template.</p></li>

<li><p>the remaining validity period of the signing CA certificate. Simply put, a certificate issued by a CA cannot be valid longer than the CA certificate itself.</p></li>

<li><p>the timerange defined in the CA configuration file (CAPolicy.inf) during installation. If not defined, this is the default value of 2 years, which means that if the CA is deployed with all default values, the Golden Certificate can usually not last longer than 2 years maximum. You can check the CA configuration using certutil on the CA server.</p>

<pre><code>certutil -getreg CA\ValidityPeriod
certutil -getreg CA\ValidityPeriodUnits
</code></pre></li>
</ul>

<h2 id="getting-a-golden-certificate">Getting a Golden Certificate</h2>

<pre><code>man Get-SmartcardCertificate
</code></pre>

<p><img src="/img/3_manGetSmartcardCertificate.JPG" alt="Parameters" /></p>

<ul>
<li><strong>Identity</strong> is the samAccountName of the target user</li>
<li><strong>TemplateName</strong> is the CN of the template we will abuse (= the one you have write permissions on)</li>
<li><strong>NoSmartCard</strong> instructs the script not to use the Smartcard CSP and make the certificate exportable. The resulting certificate will be stored in the normal user certificate store. This is useful if you have no ability to get a Smartcard on the host you request the certificate on. Just export it from the store and import it back on a smartcard on a host you control. It&rsquo;s also useful if you just want to prove that the attack would succeed without messing around with Smartcards.</li>
</ul>

<p>We will run Get-SmartcardCertificate mit the <code>NoSmartCard</code> switch to get an exportable certificate for the user &ldquo;Chuck Norris&rdquo; (who obviously is a domain admin).</p>

<pre><code>Get-SmartcardCertificate -Identity norris -Template CorpComputer -NoSmartcard
</code></pre>

<p><img src="/img/3_getcertfordomadm.PNG" alt="POC" /></p>

<h2 id="defending-against-golden-certificates">Defending against Golden Certificates</h2>

<p>Like Golden Tickets, you can&rsquo;t really prevent these things once an attacker has the appropriate permissions to do so. But you can detect and respond as soon as it happens.</p>

<ul>
<li>First, be aware that your CA Admins (or any other user who can change a certificate template) are equivilant to Domain Admins. Therefore monitor and protect these accounts as you do with your Domain Admins.</li>
<li>Second, you should monitor issued certificates and changes to certificate templates closely.</li>
</ul>

<p>I will sum up quickly how to configure auditing on the CA but you should definitely have a look at Microsofts <a href="https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/dn786432(v%3Dws.11)" target="_blank">PKI Monitoring Guide</a> for more details.</p>

<p>We start with enabling success/failure logging for &ldquo;Object Access\Audit Certificate Services&rdquo;. You can do this with group policy (Configuration\Windows Settings\Security Settings\Advanced Audit Policy) or locally by running</p>

<pre><code>auditpol /set /subcategory:&quot;Certification Services&quot; /success:enable /failure:enable
</code></pre>

<p>After that you need to enable auditing in the &ldquo;Auditing&rdquo; tab of your CA. I would recommend to enable all categories but you need at least &ldquo;Change CA configuration&rdquo; and &ldquo;Issue and manage certificate requests&rdquo; to detect this attack.</p>

<p><img src="/img/3_ca_auditing_properties.png" alt="CA Audit config" /></p>

<p>In addition, you have to run the following certutil command to activate logging of template changes.</p>

<pre><code>certutil –setreg policy\EditFlags +EDITF_AUDITCERTTEMPLATELOAD
</code></pre>

<p>Now that everything is set, you should find events of the task category <code>Certification Services</code> trickling into the default Security log of your CA. Rebooting the CA server once might speed this process up if you are missing events.</p>

<p>The event most interesting for us is <code>A Certificate Services template was updated (4899)</code>. 4899 will be logged when a certificate template changes and contains the old as well as the new configuration. You can use this to match template updates where the new configuration contains a <code>pKIExtendedKeyUsage</code> attribute that matches the string <code>1.3.6.1.4.1.311.20.2.2 Smart Card Logon</code>.</p>

<p><img src="/img/3_event4899_1.PNG" alt="4899" /></p>

<p>We will also find a <code>Certificate Services approved a certificate request and issued a certificate (4887)</code> for our Golden Certificate, however this event unfortunately does not hold much information for us. You can see in the screenshot below that we do not find the identity to whom the certificate was issued in the event nor the certificate template it refers to :-( :-( :-(. Therefore we cant use this event to alert on but it is still useful from a forensics perspective.</p>

<p><img src="/img/3_event4887_1.PNG" alt="4887" /></p>

<p>That&rsquo;s it for now. Give it a try and let me know what you think!</p>
]]></content>
        </item>
        
        <item>
            <title>Evading anti-virus with Powershell Armoury</title>
            <link>https://cyberstoph.org/posts/2019/12/evading-anti-virus-with-powershell-armoury/</link>
            <pubDate>Mon, 02 Dec 2019 00:00:00 +0000</pubDate>
            
            <guid>https://cyberstoph.org/posts/2019/12/evading-anti-virus-with-powershell-armoury/</guid>
            <description>TL;DR; PSArmoury is a PowerShell script that allows you to easily get the newest versions of all your favourite offensive PowerShell craft and automatically put it together in a single, encrypted .ps1-file. Think of it like a &amp;ldquo;yum update&amp;rdquo; that pipes the result in an encrypted container to take it with you. AMSI and EDR bypass included :-)
PSArmoury I wrote my &amp;ldquo;Powershell Armoury&amp;rdquo; script a while ago to tackle two issues I often encountered during engagements:</description>
            <content type="html"><![CDATA[

<h2 id="tl-dr">TL;DR;</h2>

<p><a href="https://github.com/cfalta/PowerShellArmoury" target="_blank">PSArmoury</a> is a PowerShell script that allows you to easily get the newest versions of all your favourite offensive PowerShell craft and automatically put it together in a single, encrypted .ps1-file. Think of it like a &ldquo;yum update&rdquo; that pipes the result in an encrypted container to take it with you. AMSI and EDR bypass included :-)</p>

<h2 id="psarmoury">PSArmoury</h2>

<p>I wrote my &ldquo;Powershell Armoury&rdquo; script a while ago to tackle two issues I often encountered during engagements:</p>

<ul>
<li>First, I&rsquo;m a huge fan of PowerShell and if possible, I do everything in PowerShell. So after some time I got a pretty big list of already existing tools and self-made scripts that I want to take with me when doing a Windows or Active Directory assessment. However all these different scripts (even my own ;-)) get updated frequently and I usually ended up with some out-dated software in the field.</li>
<li>Second, most of the existing well-known PowerShell tools like PowerView or Inveigh will be detected instantly by any anti-virus solution - at least on disk.</li>
</ul>

<p><img src="/img/braveheart.png" alt="braveheart" /></p>

<p>So I created PSArmoury, which allows me to do the following:</p>

<ul>
<li>Create a simple json config file containing links to all my favourite tools on the internet. You only have to do this once.</li>
<li>Then, everytime before an engagement you just run New-PSArmoury and it will automatically fetch the newest version of all those PowerShell scripts and put them together in a single, encrypted ps1-file. This is your Armoury.</li>
</ul>

<p>Let&rsquo;s have a look at that. You can find PSArmoury on <a href="https://github.com/cfalta/PowerShellArmoury" target="_blank">Github</a>. Just download or clone and you&rsquo;re ready to go.
First, let&rsquo;s have a look at the config. PSArmoury comes with a sample configuration file called PSArmoury.json that already references some well-known tools like PowerSploit or Inveigh. You can use this for inspiration. The configuration file is just a JSON array containing the different script files you want to include. An array member looks like this.</p>

<p><img src="/img/psarmoury1.PNG" alt="psarmoury1" /></p>

<p>Every config item consists of a name, an URL, a type and optional inclusion/exclusion filter. The major difference here is the type and there are three differen types available.</p>

<ul>
<li><strong>GitHubRepo</strong>: this instructs PSArmoury to automatically include all files in the Github Repo (that matches the Inclusion/Exclusion filter). It will ask for a Github username and personal access token since we use the Github API here.</li>
<li><strong>GitHubItem</strong>: this instructs PSArmoury to download a single file from Github. It will ask for a Github username and personal access token since we use the Github API here.</li>
<li><strong>WebDownloadSimple</strong>: this instructs PSArmoury to download a single file from an arbitrary webserver. No credentials needed.</li>
</ul>

<p>So in the example above, the configuration instructs PSArmoury to download all files from Kevin Robertsons repostory &ldquo;Invoke-TheHash&rdquo; that match the inclusion filter &ldquo;*.ps1&rdquo;.</p>

<p>Once you have created your configuration, you can simply run</p>

<pre><code>. .\New-PSArmoury.ps1
New-PSArmoury -Path .\MyShinyNewArmoury.ps1 -Config .\PSArmoury.json
</code></pre>

<p>Note that it will require you to enter credentials to use the GitHub API. You have to enter your username and a personal access token.</p>

<p>Here&rsquo;s a screenshot using the sample config that comes with PSArmoury.</p>

<p><img src="/img/psarmoury2.PNG" alt="psarmoury1" /></p>

<p>The output above mentions a password. This has been generated randomly and is included <strong>in cleartext</strong> in the resulting armoury file. This is not a problem since we use encryption only as a means of obfuscation here and not for confidentiality. Still, if you want to remove the password from your armoury you can use the <code>-OmitPassword</code> switch to do so. If you want to use a custom password or salt you can do this too by using the <code>-Password</code> and <code>-Salt</code> parameters.</p>

<p>Now, how do you use your new and shiny armoury? It&rsquo;s actually very simple, just open powershell on the host of your choice and load the .ps1 file like this.</p>

<pre><code>cat -raw .\MyShinyNewArmoury.ps1 | iex
</code></pre>

<p>And that&rsquo;s it. This will disable AMSI, load all encrypted blobs into powershell and then decrypt and load them in memory. Happy Hacking :-)</p>
]]></content>
        </item>
        
        <item>
            <title>Introducing PoshADCS</title>
            <link>https://cyberstoph.org/posts/2019/11/introducing-poshadcs/</link>
            <pubDate>Sat, 09 Nov 2019 00:00:00 +0000</pubDate>
            
            <guid>https://cyberstoph.org/posts/2019/11/introducing-poshadcs/</guid>
            <description>TL;DR;TL;DR; The script from this article leverages certificate templates to craft arbitrary smartcard logon certificates so you can impersonate any user. Use this to gain long-term stealthy persistence inside an Active Directory Domain or escalate your privileges to any user. Requirements: control over a user with write access on any kind of certificate template. The heavy lifting in the script is done with PowerView by Will Schroeder, so the kudos go to him.</description>
            <content type="html"><![CDATA[

<h2 id="tl-dr-tl-dr">TL;DR;TL;DR;</h2>

<p>The script from this article leverages certificate templates to craft arbitrary smartcard logon certificates so you can impersonate any user. Use this to gain long-term stealthy persistence inside an Active Directory Domain or escalate your privileges to any user. Requirements: control over a user with write access on any kind of certificate template.
The heavy lifting in the script is done with <a href="https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1" target="_blank">PowerView</a> by Will Schroeder, so the kudos go to him.</p>

<h2 id="tl-dr">TL;DR;</h2>

<p>Active Directory integrated Certificate Authorities (Enterprise CAs) store a part of their configuration in Active Directory. Espescially of interest are the so called &ldquo;Certificate Templates&rdquo;.
Certificate templates are used by clients als well as by the CA to determine how to populate the fields in a certificate request as well as the resulting certificate. Usually there are a couple of published certificate templates in any organization that uses an AD integrated CA.
If an attacker gains write access (Write and Enroll or WriteDACL) on any of these templates (e.g. through a service account) it is possible to &ldquo;rewrite&rdquo; any template so the attacker can enroll a smart card certificate for arbitrary users (e.g. domain admin) and then impersonate that user.
This can be used as an ACL-based backdoor as well as an offensive attack vector.</p>

<h2 id="what-s-adcs">What&rsquo;s ADCS?</h2>

<p>Active Directory Service Certificates is a server-role for Windows server that allows you to run a PKI (Public Key Infrastructure) on Windows. Upon installation, you can decide if you want to install a standalone or an enterprise CA. Simply put: a standalone CA is just a certificate authority running on Windows, whereas an enterprise CA integrates with Active Directory.
You typically use the standalone CA for your root CA (because in can be offline or disconnected) and the enterprise CA for the issuing CA.
So what does &ldquo;enterprise&rdquo; and &ldquo;integrated&rdquo; mean specifically?</p>

<p>I tried to show the relevant interconnections in a picture. Though it looks like my little daughter drew it, I hope you get the point ;-)</p>

<p><img src="/img/ADCS-for-a-three-year-old.png" alt="ADCS-intro" /></p>

<p>An enterprise CA not only stores its configuration in a local database but also in the configuration partition of Active Directory under the following key:</p>

<p><code>CN=Public Key Services, CN=Services, CN=Configuration, DC=domain, dc=com</code></p>

<p>The data is split in different containers like &ldquo;AIA&rdquo; or &ldquo;Certificate Templates&rdquo;. We&rsquo;ll focus on those relevant to our attack scenario for now.</p>

<p><img src="/img/publickey-container.PNG" alt="ADCS Container" /></p>

<ul>
<li><strong>Certificate Templates:</strong> stores the configuration for all certifcate templates. A certificate template basically is a blueprint for a certificate request (e.g. for an SMIME certificate). However not all certificate templates in this container are necessarily available for enrollment.</li>
<li><strong>Enrollment Services:</strong> Stores CA&rsquo;s available for certificate enrollment. Windows hosts use this container to automatically find CA&rsquo;s that can issue certificates to them. The respective CA object in this container has a member attribute called &ldquo;certificate Templates&rdquo;. This attribute contains a list of all certificate templates (see above) that are available for enrollment on this CA. This is usually only a subset of all existing templates.</li>
<li><strong>NtAuthCertificates:</strong> Stores CA&rsquo;s that are permitted to issue smartcard logon certificates. If you try to log on with a smartcard certificate issued by a CA not in this list, authentication will fail. Every Enterprise CA is automatically added here.</li>
</ul>

<h2 id="what-is-a-certificate-template">What is a certificate template?</h2>

<p>As mentioned earlier, a certificate template is like a blueprint to populate a certificate request. Here&rsquo;s an example: a certificate template for a &ldquo;Computer Certificate&rdquo; (e.g. for authentication using 802.1x) contains certain attributes relevant to that usage scenario. This template will typically be configured to use the requesting hosts DNS name as the Common Name in the certificate.
The computer requesting the certificate will therefore populate the certificate request in accordance with the settings in the template. The CA too uses the configuration in the template for validation, so even if the client submits a wrong common name, the CA would change it to the one defined in the template before issung the certificate.</p>

<p><img src="/img/certificate-template.PNG" alt="CN configuration in a computer template" /></p>

<p>As you can see in the screenshot above, it is however also possible to allow the enrollment client to submit an arbitrary common name. This poses a certain risk because the CA has to trust the client to provide a correct CN. The CA administrator can limit the acces to a certificate template through the ACL of the template object in Active Directory. The ACL of the template not only defines who can modify the template but also who can enroll a template.
Certificate enrollment can either happen automatically (Permission = Auto Enrollment) or manually (Permission = Enroll). Auto enrollment is configured via group policy and enforced throuh the group policy client during processing of the policy. If auto enrollment is enabled, the group policy client will look for and enroll all available certificate templates where the auto enrollment permission is set.</p>

<h2 id="attacking-certificate-templates">Attacking certificate templates</h2>

<p>From a sysadmins perspective, certificate templates seem quite different. Every Enterprise CA ships with a couple of default templates and it is common practice that, if you want to use a certain template, you create a copy of one of the default templates and work with that.
If you want to give a Windows client a certificate so it can participate in 802.1x, you would use a &ldquo;Computer&rdquo; template. If you want to issue SMIME certificates to your users, you&rsquo;ll use a copy of the &ldquo;User&rdquo; template.
Every template is named after its intended cause and this strengthens the idea, that you can only issue computer certificates from a &ldquo;computer&rdquo;-template. However, there is no fundamental difference between two different templates. Every template can issue every kind of certficate, if populated with the right parameters.
If an attacker gains access (Write/Enroll or WriteDACL) to any template, it is possible to reconfigure that template to issue certificates for Smartcard Logon. The attacker can even enroll these certificate for any given user, since the setting that defines the CN of the certificate is controlled in the template.</p>

<p>Long story short, the attacker can impersonate any user by enrolling a smartcard logon certificate for that user. If the domain already uses smartcards for authentication, all requirements are already met and the attack should work out of the box.
If smartcards are currently not in use in the target environment, the attack will still work as long as the following is true:</p>

<ul>
<li>The certificate of the Enterprise CA issuing the smartcard certificate needs to be present under &ldquo;CN=NtAuthCertificates, CN=Public Key Services, CN=Services, CN=Configuration, DC=domain, dc=com&rdquo;. This is done automatically during setup of the CA, so it shouldn&rsquo;t be a problem.</li>
<li>You obviously need a smartcard. This can be a physical smartcard, however bringing a real smartcard implies the need of physical access, which can be a challenge. Luckily, there&rsquo;s a solution called &ldquo;virtual smartcard&rdquo;. More on that later.</li>
<li>The domain controller(s) need&rsquo;s a certificate issued from one of the following templates: Domain Controller, Domain Controller Authentication, Kerberos Authentication. This is probably the only crucial requirement that might not be met. However if there is an enterprise CA and auto enrollment enabled, from my experience it is very likely that the domain controllers already got the certificate automatically.</li>
</ul>

<h2 id="virtual-smartcards-to-the-rescue">Virtual smartcards to the rescue</h2>

<p>Since bringing a physical smartcard to a host you might have only remote access to can pose a challenge, there is a solution called virtual smartcard. Virtual smartcards where implemented in Windows 8 and allow you to use a TPM chip to create a virtual smartcard device.
Since most modern business clients ship with a TPM chip, this shouldn&rsquo; be a problem. In fact, virtual smartcards are much more usable for the attack than real smartcards because they work out of the box on Windows clients and servers without the need of any special drivers and they work even over RDP.
So you can use the virtual smartcard on a compromised client to log in to a server without TPM just as you would with username/password.
Creating a virtual smartcard is simple as Windows provides a management tool called tpmvscmgr.exe Just run the command below to generate a smartcard with the default pin (12345678).</p>

<p><code>tpmvscmgr.exe /create /name VSC01 /pin default /adminkey random /generate</code></p>

<p><img src="/img/create-vsc.PNG" alt="Creating a virtual smartcard" /></p>

<h2 id="proof-of-concept">Proof of concept</h2>

<p>I wrote a proof of concept script that implements the attack described above. It takes the samaccountname of a domain user to impersonate and the name of a certificate template you have access to.
The script will rewrite the template to allow for smartcard enrollment, get the certificate and then reset the template to its original configuration :-)</p>

<p><img src="/img/poshadcs-poc.PNG" alt="POC" /></p>
]]></content>
        </item>
        
        <item>
            <title>Hello World</title>
            <link>https://cyberstoph.org/posts/2019/10/hello-world/</link>
            <pubDate>Mon, 21 Oct 2019 00:00:00 +0000</pubDate>
            
            <guid>https://cyberstoph.org/posts/2019/10/hello-world/</guid>
            <description>Hello World! Yet another blog unravels in the depths of the internet. Let&amp;rsquo;s see if anyone will find it at all :-)
If you however do so, you&amp;rsquo;ll probably read a lot about Windows security, Powershell, AD, privesc and general infosec stuff.
Hope you like it stranger!</description>
            <content type="html"><![CDATA[<p>Hello World! Yet another blog unravels in the depths of the internet. Let&rsquo;s see if anyone will find it at all :-)</p>

<p>If you however do so, you&rsquo;ll probably read a lot about Windows security, Powershell, AD, privesc and general infosec stuff.</p>

<p>Hope you like it stranger!</p>
]]></content>
        </item>
        
    </channel>
</rss>
