<?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 Evan McBroom on Medium]]></title>
        <description><![CDATA[Stories by Evan McBroom on Medium]]></description>
        <link>https://medium.com/@evanmcbroom?source=rss-19644b9f54e3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Q3utKGmbLhFBPUEOCnvrUg.jpeg</url>
            <title>Stories by Evan McBroom on Medium</title>
            <link>https://medium.com/@evanmcbroom?source=rss-19644b9f54e3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:41:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@evanmcbroom/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[LSA Whisperer]]></title>
            <link>https://medium.com/specter-ops-posts/lsa-whisperer-20874277ea3b?source=rss-19644b9f54e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/20874277ea3b</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[infosec]]></category>
            <category><![CDATA[specterops]]></category>
            <category><![CDATA[red-teaming]]></category>
            <dc:creator><![CDATA[Evan McBroom]]></dc:creator>
            <pubDate>Wed, 17 Apr 2024 15:46:49 GMT</pubDate>
            <atom:updated>2024-04-19T14:15:14.600Z</atom:updated>
            <content:encoded><![CDATA[<p>Thank you to <a href="https://specterops.io/">SpecterOps</a> for supporting this research, to <a href="https://twitter.com/elad_shamir">Elad</a> for helping draft this blog, and to <a href="https://www.linkedin.com/in/sarah-miles-81ab6a41/">Sarah</a>, <a href="https://twitter.com/hotnops">Daniel</a>, and <a href="https://twitter.com/_xpn_">Adam</a> for proofreading and editing! Crossposted <a href="https://gist.github.com/EvanMcBroom/dceb1c7070ee3278eaedd04b42aed279">on GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/0*5wRLRXl5TgT53pc6" /></figure><p>What follows is the culmination of two years of research with funding by SpecterOps and contributions from many of my coworkers.</p><p>Special thanks are needed to <a href="https://twitter.com/elad_shamir">Elad</a>, <a href="https://twitter.com/tifkin_">Lee</a>, <a href="https://twitter.com/harmj0y">Will</a>, <a href="https://twitter.com/hotnops">Daniel</a>, and <a href="https://twitter.com/mhskai2017">Kai</a>. Elad, Lee, and Will have contributed several ideas to the project, which are documented here, and have each spent multiple days testing the tool. Daniel has answered all of my inevitable questions about AzureAD (whoops, now Entra ID! It was AzureAD when I started 🙂) and OAuth 2.0. Kai helped both research LSA’s cloudap authentication package (AP) and add kerberos package support to the tool. To each, thank you!</p><p>The LSA Whisperer project focuses on interacting with “Authentication Packages’’ using their individual message protocols. APs are Security Support Provider (SSP) DLLs that LSA loads to implement a specific authentication logic design (e.g., local logons). An SSP may also be called a Security Package (SP) if it implements a security protocol (e.g., NTLM), but any use of the word “package” in this blog will only be referring to the AP functionality of an SSP.</p><h3>Diary of a Developer</h3><p>The project that is about to be described has been a journey to completion, so please allow me to explain how it all began.</p><h4>Summer, 2022</h4><p>SpecterOps does a series of internal technical talks presented by coworkers and hosted by <a href="https://twitter.com/its_a_feature_">Cody Thomas</a>. During one of these talks, <a href="https://twitter.com/tifkin_">Lee Chagolla-Christensen</a> showed some work he did to trace how browsers requested SSO cookies from an LSA package named cloudap. He was interested in making the same request programmatically, but he had not had an opportunity yet to investigate how.</p><p>The idea of requesting an SSO cookie directly was enticing, so I offered to help. During the break times while teaching <a href="https://specterops.io/training/tradecraft-analysis/">SpecterOps’s Tradecraft Analysis course</a>, we managed to get some interaction occurring with cloudap via the LsaCallAuthenticationPackage Win32 API. We had figured out how to request cloudap to refresh a primary refresh token (PRT) for a user, but we had not yet figured out how to recover a user’s SSO cookie. The successful interaction was exciting nonetheless. Auditing cloudap in Ghidra also allowed us to stumble on a wealth of functionality, known as “calls”, that we could use to interact with the package in other ways.</p><p>After that, I started working on a command-line interface (CLI) utility to interact with the cloudap calls we found interesting. There was no consideration of the potential offensive use case for a tool at that time. I was simply interested in what calls cloudap offered and being able to call the useful ones myself. Daniel Heinsen was extremely helpful during this process, answering my many questions regarding all things Entra ID and OAuth 2.0.</p><h4>Fall, 2022</h4><p>Soon after Elad Shamir rejoined SpecterOps. He had heard I was doing some work with LSA, so we talked about an authentication flow he was investigating with the kerberos package. Specifically, when the kerberos package recovers an NT OWF hash from a decrypted PAC, kerberos will store the hash in a logon session managed by the msv1_0 package using msv1_0’s internal CacheLogon call. He was interested to see if we could make the same CacheLogon call ourselves to Pass-the-Hash (PtH) with on-host tooling. The only alternative with on-host tooling is to use Mimikatz or a similar tool to modify LSASS’s memory.</p><p>The idea was fantastic and I began auditing CacheLogon to see how to make the call. We found that the approach is indeed possible, but we ultimately encountered the roadblock in that msv1_0 restricts the CacheLogon call to only clients that are the LSASS process itself. We noticed several other msv1_0 calls that seemed intriguing, though, and I started working on an equivalent msv1_0 CLI utility for interacting with the calls we were interested in.</p><p>During this time we discovered the fact that the GetCredentialKey call for msv1_0 would return a subset of the primary credentials for an msv1_0 managed logon session. These are derivations of a user’s plaintext password (such as an NT hash) that msv1_0 stores to allow it to later perform various actions for the user. We did not fully understand the implication of these credentials at the time, but we knew they were used in some way with the <a href="https://en.wikipedia.org/wiki/Data_Protection_API">Data Protection API (DPAPI)</a>. We also could not find <em>anyone</em> documenting this same call which was surprising and encouraged us to keep going and investigate other packages as well.</p><p>NOTE: “Credential Keys” is Microsoft’s term for a one-way function (OWF) hash or a secure credential hash of a user’s password. The appropriate key may be used to decrypt a DPAPI master key. Will Schroeder has added cred key support to <a href="https://github.com/GhostPack/SharpDPAPI">SharpDPAPI</a> to weaponize this output. Thank you, Will!</p><p>Around this time Lee joked:</p><p>“Why don’t you make a CLI utility for kerberos? Actually, why not make one for all the packages?”</p><p>The idea did not seem too far-fetched to implement, so the utilities got merged and additional work began on making kerberos calls. Elad came up with a name that everyone liked, and thus LSA Whisperer was born.</p><h4>Spring, 2023</h4><p>The whole company met for our yearly retreat in early 2023. By this time, I had reversed the names of all the calls for all packages that currently ship with Windows. I had identified that cloudap loaded plugins, that these plugins supported calls as well, and had reversed the names of each of those calls. I had also reversed the Security Package Manager (SPM), which manages LSA packages overall, identified that it too supported calls, and identified their names.</p><p>The full list of available calls was overwhelming. I sat down with Elad, Lee, and Will during the retreat to prioritize it into a smaller list of calls we wanted to learn more about. Kai Huang also joined the project around this time to help research calls in the larger packages, namely cloudap and kerberos. The prioritized list and extra help made the project much more manageable.</p><h4>Fall, 2023</h4><p>In Q4 of 2023, SpecterOps funded me to work the entire quarter on developing LSA Whisperer. Although it’s common for SpecterOps to give employees work time and other resources for their personal projects, I understand this is uncommon for the industry and I am grateful to SpecterOps for your support.</p><p>By the start of Q4, the project was well organized. The tool could already make many calls to several packages, all research was documented in a project wiki, and the work plan and milestones for the quarter were outlined in a formal research plan. Progress accelerated during this time, and the tool gained partial or full support for 12 cloudap calls, 10 cloudap AzureAD plugin calls (Microsoft uses Entra ID’s previous name for the plugin), 21 kerberos calls, 1 livessp call, 1 msv1_0 call (many were previously implemented), 4 negoexts calls, 2 pku2u calls, 2 schannel calls, and 2 spm calls. Lee and Will graciously spent many days at the end of the quarter testing each of these new calls to confirm or disprove our ideas for their potential use cases.</p><p>Three bugs were also identified during this time, which were all responsibly disclosed to the Microsoft Security Response Center (MSRC). Two were arbitrary pointer dereference issues with the LSASS process for NT 6.4 and higher. These require the SeTcbPrivilege privilege, which reduces the potential for abuse, and MSRC ultimately considered both to be by design. The third was a memory leak in LSASS triggerable by any logged-on user for at least NT 5.1 and higher. The third bug was assigned <a href="https://msrc.microsoft.com/update-guide/en-US/vulnerability/CVE-2024-26209">CVE-2024–26209</a>, was fixed on April 9th, 2024, and is now available via security updates to all end users. MSRC was quick to respond and pleasant to work with for all of these issues which I appreciate. For those interested, a description and proof of concept (POC) for each of these issues may be found <a href="https://github.com/EvanMcBroom/pocs">on a GitHub project where I share various POCs that I author</a>.</p><h4>Spring, 2024</h4><p>I had the opportunity <a href="https://github.com/SpecterOps/presentations/tree/master/SO-CON%202024/Evan%20McBroom%20-%20LSA%20Whisper">to present LSA Whisperer</a> at the annual <a href="https://specterops.io/so-con/">SpecterOps Conference (SOCON)</a> in Arlington, VA. There was a large attendance and the feedback afterwards made us feel that everything went well! Thank you to everyone who was able to attend the talk. Your presence and interest made presenting a joy!</p><p>I would like to thank my colleagues for all of the support leading up to and during the presentation. The talk would not have gone as smooth without it. Lastly, the presentation was a combination of my own ideas and those of many of my colleagues including Elad, Lee, and Will. It was an honor to be able to present the culmination of everyone’s work, thank you!</p><p>Now that brings us to the present: April, 2024. The security update has been released and with that, we may release our tooling.</p><h3>Project Overview</h3><p>If you would like, you are welcome to skip this guide and go directly to <a href="https://github.com/EvanMcBroom/lsa-whisperer">the main page for the project</a>. The main page describes how to build our tooling — LSA Whisperer, while the project wiki describes <a href="https://github.com/EvanMcBroom/lsa-whisperer/wiki/Usage">how to use the tool</a>, <a href="https://github.com/EvanMcBroom/lsa-whisperer/wiki">how it works</a>, and what authentication package functionality it supports. The wiki is large so here we provide a more gentle introduction to these same topics.</p><h4>Security Support Providers</h4><p>As described in the blog’s introduction, SSPs are DLLs loaded by LSA that implement a specific authentication logic design (e.g., local logons) or security protocol (e.g., NTLM). The below table provides a summary of the SSPs that have been released by Microsoft over the years. LSA Whisperer supports interacting with a subset of shown SSPs that are marked as being an authentication package (AP). Many of these SSPs implement a security protocol and, as such, may also be referred to as a security package (SP) but for the purposes of this blog we will only be focusing on the AP functionality of these SSPs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*GSEdXGxjUFtgN09w" /></figure><h4>Package Calls</h4><p>Each AP has the option to support receiving, processing, and responding to arbitrary requests from other software. These requests are referred to as “package calls.” Making a package call is officially supported for both user mode and device driver software through the use of the LsaCallAuthenticationPackage API.</p><p>Aside from wdigest, all APs that currently ship with Windows support handling package calls. APs use this feature to support custom functionality that is not otherwise available through the standard SSP function table that an AP must implement. For years, red teams and threat actors have abused some of this custom functionality (e.g., to recover Kerberos tickets).</p><p>Despite a few of these package calls being well known, we noticed that the overwhelming majority of them have not been documented. Our interest is in identifying <em>all </em>of the custom functionality that each AP supports through making package calls because we theorized that more would be abusable during an offensive operation. If that has piqued your interest, read on!</p><h3>Techniques</h3><p>During our research, we documented the package calls that are available for all APs that currently ship with Windows. We narrowed these down to a subset which we believe to be useful and implemented support for the majority of this subset into LSA Whisperer.</p><p>Here are the highlights of the package calls that may be made on a given host. All package calls not mentioned in these highlights may be found on the project wiki. If you are interested in a package call that is not implemented or you see an area of the wiki that can be improved, please submit an issue on GitHub or consider making a pull request (PR) for the project.</p><h4>Kerberos</h4><p>We will begin with the kerberos package as its package calls are more well-known in the industry. The first thing of note, as with many APs, is the ability to use package calls to gather host enumeration data. With the kerberos package you can show currently cached Kerberos tickets, domain extended policies (e.g., “Is FAST Armouring enabled?”), and how Kerberos is configured on that host.</p><p>Of most interest to people is likely the package’s ability to recover Kerberos tickets for active logon sessions or possibly its ability to cache a given Kerberos ticket to use on the host: a technique known as <a href="https://attack.mitre.org/techniques/T1550/003/">“Passing the Ticket’’ (PTT)</a>. Of less importance, but still of interest to offensive operations, is the package’s ability to purge tickets, bind a domain name, and a pin domain name.</p><p>Ticket purging is helpful if you have done the PTT technique, the ticket you used is no longer operationally useful, and you need to remove it from your cache. Although most red team tools only support purging all tickets in your cache, we identified that the package allows you to selectively purge tickets, which provides the potential for a significant quality of life improvement for these red team tools. Domain name binding can help with performing the Golden Ticket technique as identified by <a href="https://twitter.com/mpgn_x64/status/1241688547037532161">Martial Puygrenier</a> while domain name pinning has been shown by <a href="https://www.youtube.com/watch?v=GM1PxZPiLMk">James Forshaw and Nick Landers</a> to allow for logical abuses of Kerberos. In their case, they showed a local privilege escalation (LPE) to SYSTEM but people should look for other potential abuses of domain pinning as well 🙂</p><p>All kerberos package calls are documented <a href="https://github.com/EvanMcBroom/lsa-whisperer/wiki/kerberos">on the kerberos page of the wiki</a>. The relevant calls for the techniques presented in this section include:</p><ul><li>AddBindingCacheEntry</li><li>PinKdc / UnpinAllKdc</li><li>PrintCloudKerberosDebug</li><li>Query/Purge BindingCache</li><li>Query/Purge KdcProxyCache</li><li>Query/Purge TicketCache[Ex|Ex2|Ex3]</li><li>QueryDomainExtendedPolicies</li><li>QueryS4U2ProxyCache</li><li>Retrieve[Encoded]Ticket</li><li>SubmitTicket</li></ul><h4>Cloud AP</h4><p>Next up is cloudap which manages Entra ID, AD FS, and Microsoft account logons. As with kerberos, cloudap offers functionality for gathering basic information about the host and logon sessions managed by cloudap, such as if a partial TGT, also known as the “cloud to on-premises TGT”, is present in a local cache.</p><p>While this information is helpful for troubleshooting logon issues, what is more interesting are the individual plugins that cloudap loads. Cloudap currently has two plugins. The first, known as AzureAD or AAD, manages Entra ID and AD FS logons. The second, known as Windows Live ID or MSA, manages Microsoft Account logins.</p><p>The main thing of interest with these plugins is that they can be used to request a single sign-on (SSO) cookie to authenticate to an identity provider (IDP) as a target user. The AAD plugin allows you to request an SSO cookie for Entra, AD FS, and an SSO cookie for your current device itself. Although we have not made a successful request yet to MSA, we are confident we will be able to request an SSO cookie for Microsoft Accounts from it as well because we have successfully done so with the legacy livessp AP that it is based on.</p><p>Of less immediate impact but still of importance are the additional host enumeration options that the AAD plugin specifically offers. Red team tools typically gather cloud information using the NetGetAadJoinInformation Win32 API but this function notably lacks SSO information that can be gathered from other CLI tools such as dsregcmd. The missing SSO information from this API may be gathered using the AAD plugin.</p><p>All calls for cloudap and the AAD plugin are documented <a href="https://github.com/EvanMcBroom/lsa-whisperer/wiki/kerberos">on the cloudap page of the wiki</a>. The relevant calls for the techniques presented in this section include:</p><ul><li>GetAuthenticatingProvider</li><li>GetDpApiCredKeyDecryptStatus</li><li>GetPwdExpiryInfo</li><li>GetUnlockKeyType</li><li>IsCloudToOnPremTgtPresentInCache</li><li>AAD -&gt; CreateSSOCookie</li><li>AAD -&gt; CreateDeviceSSOCookie</li><li>AAD -&gt; CreateEnterpriseSSOCookie (Enterprise refers to AD FS)</li><li>AAD -&gt; DeviceValidityCheck</li></ul><h4>Microsoft Authentication Package V1.0</h4><p>The last package that we will cover in this post is the msv1_0 but more are covered <a href="https://github.com/EvanMcBroom/lsa-whisperer/wiki">on the wiki</a>! Msv1_0’s main purpose as an AP is to facilitate local machine logons. Being the oldest of the APs, it has gathered other responsibilities such as managing DPAPI credentials, sending Netlogon requests, and generating data for NTLM messages to support its 2nd role as the security package for NTLM.</p><p>Due to these additional responsibilities, msv1_0 was as fruitful in our findings as cloudap was in recovering credential material. The first thing we identified is that msv1_0 allows you to recover the DPAPI “credential key” of a logged-on user. The term credential key <a href="https://github.com/EvanMcBroom/lsa-whisperer/wiki/msv1_0#credential-key">is described on the wiki</a> and we plan to cover it further in a future blog, but if you recover a user’s credential key you can decrypt their DPAPI master key file. <strong>This process works even when Credential Guard is enabled.</strong></p><p>The next thing we identified is that msv1_0 allows you to generate an NTLMv1 response with a chosen server challenge value. That works regardless of NTLMv1 being disabled using the LmCompatibilityLevel key in the registry (as needed by similar attacks such as <a href="https://github.com/eladshamir/Internal-Monologue">Internal Monologue</a>) but we believe it to not work if Credential Guard is enabled. The importance of being able to acquire an NTLMv1 response, especially with a chosen server challenge, is that it is trivial to crack to a usable NT hash for pass the hash (PtH) techniques and other tradecraft. Some online resources such as <a href="https://crack.sh/">crack.sh</a> will even <a href="https://crack.sh/netntlm/">crack these responses for free if the response has a specific server challenge</a> which we can guarantee. The cracking process will also be instant for crack.sh due to its use of a rainbow table for these free requests.</p><p>All calls for msv1_0 plugin are documented <a href="https://github.com/EvanMcBroom/lsa-whisperer/wiki/kerberos">on the msv1_0 page of the wiki</a>. The relevant calls for the techniques presented in this section include:</p><ul><li>GetCredentialKey</li><li>GetStrongCredentialKey</li><li>Lm20GetChallengeResponse</li></ul><h3>Dead Ends</h3><p>Security researchers often celebrate their successes and hide the setbacks. I thought that, for a change, it would be good to share what didn’t work out as we had hoped. Most research efforts are unsuccessful and if we start sharing those as well, maybe it will encourage more people to try, and maybe others will be able to build on our unfinished work and ideas to overcome the obstacles that hindered our progress.</p><h4>Transferring Credentials as an Alternative to Token Theft</h4><p>Several packages have a TransferCreds call, which, as the name suggests, either transfers or duplicates the credential material from one logon session managed by the package into another one. Our idea for these calls was to use them as a new, alternative technique for <a href="https://attack.mitre.org/techniques/T1134/001/">Access Token Theft</a>.</p><p>Token theft was introduced back in 2008 by <a href="https://twitter.com/jukelennings">Luke Jennings</a> with the <a href="https://www.exploit-db.com/docs/english/13054-security-implications-of-windows-access-tokens.pdf">release of Incognito</a>. It was a game-changing technique that allowed attackers to use the credentials of other logged-on users without targeting LSASS. Nowadays, many EDRs can detect this technique and its variants, but more importantly Windows will purge any credential material that is no longer being used by a process or thread after a user logs off, limiting the window of opportunity for this attack. In 2022, <a href="https://twitter.com/harmj0y">Will Schroeder</a> released <a href="https://posts.specterops.io/koh-the-token-stealer-41ca07a40ed6">Koh</a>, a tool that can force Windows in some circumstances to maintain credentials past when a user logs off to extend this window of opportunity.</p><p>We believed that the TransferCreds call had a similar potential for abuse. Our idea was for an attacker to either create a new logon session or use an existing “sacrificial” logon session they controlled, then transfer the credentials of a logon session for a target user into the attacker controlled session. That would allow an attacker to use a user’s credentials well after they logged off and without generating token duplication and impersonation activity which may be viewed as suspicious.</p><p>This call is available in the msv1_0, kerberos, cloudap, and in negotiate APs. The msv1_0 package prevents any process other than LSASS itself from making the call. Supporting this is outside the scope of the project because if you can execute code inside LSASS to make this call, then you already have the ability to directly recover credentials from LSASS’s memory and makes this call unnecessary.</p><p>The kerberos package allows other processes to make this call but it will remove all Kerberos tickets and Kerberos keys from the source logon session. That should not disrupt the user’s experience when accessing services that use Negotiate to authenticate because their logon session will fallback to using NTLM, but it would disrupt their ability to use services that only use Kerberos to authenticate. Once you transfer tickets to another session, you <em>can</em> transfer them back. So it may still offer value to attackers by allowing them to temporarily transfer tickets to a controlled logon session to use, possibly bypassing any token stealing, ticket dumping, or PTT tradecraft telemetry that would normally occur when stealing a user’s Kerberos tickets. If you have other ideas on how this call may be used, we would love to hear it!</p><p>We did not have time to investigate the behavior of cloudap’s implementation, but we believe it will have the same effect as the kerberos package. Lastly, the negotiate package’s implementation will simply forward the TransferCreds call to whichever package was used for a negotiated logon session making the previously mentioned issues all issues for the negotiate package as well.</p><h4>Passing the Hash</h4><p>NTLM is a built-in challenge-response authentication protocol on Windows. In the protocol, a client will prove their possession of a password by using a derivation of it, the NT hash, to either encrypt or generate an HMAC of a challenge given by the server they are attempting to connect to. The NT hash’s use as a key exposes the authentication flow to Pass-the-Hash (PtH) attacks in which an attacker may craft a valid response to a server challenge by knowing a user’s NT hash without knowing their cleartext password.</p><p>With the exception of Mimikatz, all the tools that implement the PtH attack do so by implementing an NTLM client to allow for client responses to be generated using an NT hash instead of a user’s password. Mimikatz offers the only alternative solution. Mimikatz’s approach is to create a new logon session on a Windows host, identify the location of that session’s NT hash in LSASS’s memory, then overwrite it with a specified NT hash. That forces any process that uses that new session to use the specified NT hash when authenticating to another host using NTLM. Mimikatz takes this approach because there are no Windows APIs that allow a logon session to be created using a specified NT hash. The approach may make LSASS unstable because it is modifying its memory but is the only on-target option when a networked based tool cannot be proxied on.</p><p>The msv1_0 package offers the CacheLogon call that allows a user to cache a specified NT hash into an active logon session. If a logon session has a cached NT hash, it will be used for NTLM authentication instead of the actual NT hash for the session’s user account. The kerberos package, as an example, uses this call in passwordless authentication scenarios. During these scenarios, such as smartcard logons or Windows Hello for Business, the PKINIT authentication scheme will be used and the domain controller (DC) will send an encrypted copy of the user’s NT hash to the kerberos package. The kerberos package will decrypt the user’s NT hash then use msv1_0’s CacheLogon call to store it for the newly created logon session to use.</p><p>We wanted to use the CacheLogon call in the same way the kerberos package does to have a logon session use a known NT hash for NTLM authentication. Doing so should provide a more stable solution than Mimikatz to do a PtH attack with on-host or non-proxied tooling because it does not require overwriting LSASS memory. There are also complementary calls that you can pair with CacheLogon, such as CacheLookup, which can inspect the current msv1_0 cache for a logon session, and ClearCachedCredentials, which you can use to remove a cached NT hash for a logon session when you are done using it. Unfortunately, just like the TransferCreds call, msv1_0 only allows the CacheLogon call to be made from the LSASS process itself. We are still interested in supporting these features for hosts where LSASS does not run as a PPL, such as a user-controlled VM that is proxied into a target network for a red team assessment, but we have not implemented them yet.</p><h4>Bypassing “LSA Only” Checks with Passthrough Calls</h4><p>We have mentioned three calls so far that can only be made by the LSASS process itself; namely the CacheLogon, CacheLookup, and TransferCred calls for msv1_0. When any of these calls are made, they will check whether the information for the client request is zero, which will only happen if the client is LSASS itself and, if the information is not zero, return with an error code of “access denied.”</p><p>We can implement a solution when LSASS is not running as a PPL by injecting code into LSASS that will make these calls from within the process, but we wanted to know if there was an alternative solution that would not require code injection. Indeed, there almost was!</p><p>In our investigation, we looked at an msv1_0 package call named GenericPassthrough. The GenericPassthrough call takes an arbitrary AP request and sends it using Netlogon to a DC for processing. The kerberos package, as an example, supports a VerifyPac call and domain joined hosts will send VerifyPac requests to a DC using a GenericPassthrough call to have the DC verify a Kerberos ticket’s PAC information.</p><p>An interesting thing we noticed is that when a host is not domain joined, msv1_0 will reissue any AP request it receives via GenericPassthrough back to the local LSA instance itself. That is done to support certain workgroup activities, but the important thing is that msv1_0 will view the final reissued AP request as coming from the LSASS process. We also believe msv1_0 can be tricked into believing the host is not domain-joined to reissue an AP request for us by temporarily stopping the Netlogon service and unsetting a specific named event that is set when the service is started.</p><p>Unfortunately, we found that even if we implemented the code to trick msv1_0 into reissuing an AP request for us to bypass the “LSA only” check that some calls make (e.g., msv1_0’s CacheLogon), we found that the final request would be considered a “passthrough request.” APs typically restrict passthrough requests from clients to only a small subset of the full list of AP requests a client could normally make. As an example, kerberos only allows VerifyPac as a passthrough request and msv1_0 only allows the SubAuth request to facilitate its “sub-authentication package” concept.</p><p>The key takeaway is that although it may be possible to trick msv1_0 into reissuing an AP request to bypass an “LSA only” check, we would not be able to use this approach to make any of the calls we are interested in: msv1_0’s CacheLogon, CacheLookup, and TransferCred calls. We still like to support these calls but currently plan on implementing a solution that requires injecting code into LSASS to do so.</p><h4>Dumping NT Hashes</h4><p>The GetCredentialKey and GetStrongCredentialKey calls for msv1_0 return a DPAPI “credential key” for a logon session. As mentioned in the technique section on msv1_0, we plan to cover credential keys more in a future blog. What is important to know, though, is that in some not-so-common situations the credential key is actually just the user’s NT hash!</p><p>When we first implemented these calls, we actually ran into this situation pretty reliably and kept getting the NT hash for our target user. We had no clue what a credential key was, that it had anything to do with DPAPI, and that it is uncommon for these calls to give a user’s NT hash. Instead, we thought we had found the ideal way to dump credential material from LSASS and we were excited.</p><p>Our initial understanding turned out too good to be true, but with more investigation these calls became exciting to us in a different way. We soon found that these calls instead produce the DPAPI credential key, which in those not-so-common edge cases happens to be the NT hash, but in all cases will be key material that you can use to decrypt the user’s DPAPI master key file. When this key is also the NT hash, one of the requirements for this edge case is that the account is local. That makes its recovery less important due to many alternative methods of extracting the same value from the local SAM.</p><p>Either way, we decided to take the recovery of a DPAPI credential key as a win and later, almost by happenstance, we identified msv1_0’s ability to generate NTLMv1 responses with a chosen server challenge value which, as described in the msv1_0 tradecraft section, is trivially crackable to an NT hash for the user. So with more work we eventually got to our goal, but it was not as straightforward as we originally thought.</p><h4>Dumping Kerberos Keytabs</h4><p>A keytab file stores Kerberos authentication keys for an account and they are typically used to automate user authentication without requiring user interaction. When we were investigating the kerberos package, we noticed it supported the RetrieveKeytab call.</p><p>We were hopeful we could use this call to generate a keytab file with Kerberos authentication keys for an account similar to Mimikatz’s sekurlsa::ekeys command. However, this call requires the caller to supply a password. The resultant keytab file will be populated with keys that are derived from that password instead of a password for an existing user account, making the call not too valuable to an attacker from our perspective.</p><h4>Solving the Double Hop Problem</h4><p>When a user logs on to a remote host (the first hop) and then from that remote host attempts to log on to yet another remote host (the second hop), authentication to the second hop normally fails. That is the Double Hop Problem.</p><p>The Double Hop Problem results from how authentication in Windows environments works, and it affects not only offensive operations but also legitimate system administration. The logon session to the first remote host (the first hop) is a “network logon” established using Kerberos or NTLM rather than with reusable credential material, such as a password or smartcard data. Therefore, the first hop host is not able to authenticate the user to the second hop. The first hop simply does not have reusable credential material to perform that action.</p><p>There are several legitimate solutions to this problem, including Kerberos Delegation, Credential Delegation (supported by CredSSP), and Remote Credential Guard. Although not originally designed to solve the Double Hop Problem, the two approaches that are typically used in red teams include the <a href="https://attack.mitre.org/techniques/T1550/003/">Kerberos Pass the Ticket</a> (PTT) technique and <a href="https://attack.mitre.org/techniques/T1134/003/">creating a new logon session with explicit credentials</a>. The first approach is already achieved through an AP package call, specifically the SubmitTicket call for kerberos. The second is not. Instead, it is achieved by using one of the LogonUser Win32 APIs which is what the Cobalt Strike’s make_token command and its derivatives use.</p><p>When investigating the package calls we could make, we noticed the ChangeCachedPassword call for msv1_0 and the AddExtraCredentials call for kerberos. We thought that either could potentially allow us to apply a known password to an existing logon session. Doing so would solve the Double Hop Problem when using known passwords without requiring the LogonUser APIs to be called. That would allow us to use a known password on a host without generating an event for a new logon session being created. But that, too, turned out to be unviable. From testing, ChangeCachedPassword appeared not to apply to network logons and the AddExtraCredentials package did not appear to affect subsequent authentication attempts.</p><p>Eventually we found msv1_0’s CacheLogon call, which may still achieve the same goal for us; namely, solving the Double Hop Problem when using a known password without generating a new logon session. That call is described further in the “Passing the Hash” section, but we believe that on a host without LSASS running as a PPL we can pre-convert a known password to an NT hash and pass it to a CacheLogon call to use in an existing logon session. The downside to this approach is that we would need to execute code in LSASS, which would likely create more telemetry than a single event for a new logon session.</p><h4>Making Remote Calls</h4><p>The SSP Interface (SSPI) RPC server that facilitates everything that LSA Whisperer does was designed to be used locally. The server itself only registers an ALPC port to listen on for its endpoint which is only locally accessible. A core design of RPC, though, is that the RPC runtime allows you to send RPC requests for any RPC interface registered by a process to any RPC endpoint the process is currently listening on and the runtime will fulfill that request.</p><p>Although the SSPI RPC server only registers a single ALPC port for an RPC endpoint, the LSASS process itself listens to many RPC endpoints, some of which are remotely accessible. We wanted to make these SSPI RPC requests to one of these endpoints on a remote host. Doing so would allow LSA Whisperer to do things such as dump Kerberos tickets, DPAPI credential keys, and SSO cookies on a remote host.</p><p>Wouldn’t that be nice? Well, (un)fortunately the SSPI RPC interface is registered with the RPC_IF_ALLOW_LOCAL_ONLY flag which forces the RPC runtime to only allow local RPC clients to interact with the interface. So, if you have ever wondered if you can dump Kerberos tickets on a remote host, as far as we know it is not possible–but we would be happy to be proven wrong! 🙂</p><h3>Mitigations</h3><p>There are almost no built-in options for an administrator to prevent the package calls that LSA Whisperer makes. LSA Whisperer only uses intended functionality for Windows, and blocking its package calls from succeeding would prevent normal Windows authentication processes from succeeding. That being said, enabling Credential Guard does block some of the DPAPI credential recovery commands and we believe also prevents NTLMv1 response generation using the primary credentials of an active logon session. One DPAPI credential recovery command is still available with Credential Guard enabled, but blocking the NTLMv1 response generation prevents attackers from easily recovering a usable NT hash for the user. Credential Guard may affect commands that we did not observe during testing. If you observe Credential Guard affecting a command which we missed please consider making <a href="https://github.com/EvanMcBroom/lsa-whisperer/wiki/Usage#known-limitations">a PR to the wiki</a>.</p><p>There are also almost no built-in options for administrators to monitor for LSA Whisperer and similar tools. The largest potential is with monitoring via Event Tracing for Windows (ETW) which is used throughout all packages but not in a consistent or documented way. Additional assistance from Microsoft with guidance on which ETW providers to monitor for and with publishing the message schemas for each would go a long way toward enabling Administrators to monitor these calls.</p><p>Package calls are now facilitated by the SSPI RPC server, so we also investigated using RPC features as a method to monitor for or prevent specific package calls. There is an ETW provider named “RPC Events” that gives some insight into all RPC activity, including activity facilitating a package call, but in our opinion it does not provide enough insight to effectively monitor this activity. We investigated using Windows’s built-in RPC filters mechanism but it does not provide the granularity needed for effective monitoring or prevention of package calls. Lastly, we investigated using <a href="https://github.com/zeronetworks/rpcfirewall">the RPC firewall</a>, a popular FOSS third-party solution maintained by <a href="https://zeronetworks.com/">Zero Networks</a>. Although the solution appears to be a promising solution for administrative needs, it does not prevent local RPC traffic and it is not compatible with LSA running as a PPL. The SSPI RPC server only allows local RPC traffic so the RPC firewall is not applicable for this need. Even if it did, allowing LSA to not run as a PPL would offer attackers the ability to use Mimikatz and related tools to directly recover credentials from LSASS’s memory, making the alternative approach that LSA Whisperer takes debatably unneeded.</p><p>Ultimately, our recommendations for administrators include:</p><ol><li>Enable LSASS to run as a PPL</li><li>Enabling Credential Guard</li><li>Log off machines when you are through using them</li><li>Use <a href="https://learn.microsoft.com/en-us/security/privileged-access-workstations/privileged-access-devices">Privileged Access Workstations/Devices</a> and follow the <a href="https://learn.microsoft.com/en-us/security/privileged-access-workstations/privileged-access-success-criteria#clean-source-principle">Clean Source Principle</a></li></ol><p>Enabling LSASS to run as a PPL does not affect LSA Whisperer but does make it more difficult for attackers to use other tools that directly recover credentials from LSASS’s memory. Credential Guard largely unaffected LSA Whisperer but we believe it will block LSA Whisperer’s ability to generate an NTLMv1 response with a primary credential for an active logon session. That prevents attackers from easily gaining a usable NT hash for a user. Lastly, a large portion of LSA Whisperer’s functionality is only usable when there is an active logon session in the first place for it to request credentials from. By fully logging off machines that you are done with, you will remove the resource that a large part of LSA Whisperer’s functionality uses. The last recommendation is a general architectural best practice for securing access to end user devices in the first place.</p><p>This summarizes our recommendations to administrators for what we believe directly affects LSA Whisperer but there are settings you may enable to further strengthen Credential Guard. These settings are documented on <a href="https://learn.microsoft.com/en-us/windows/security/identity-protection/credential-guard/additional-mitigations">a dedicated page on Microsoft’s learning portal</a>. Not all of these settings may be feasible for your organization to enable but we do recommend the ones that are.</p><h3>EDR Recommendations</h3><p>Endpoint Detection and Response (EDR) vendors, including Microsoft themselves, are likely in the best position to monitor for and prevent the use of LSA Whisperer and similar tools. These are what we recommend EDRs monitor for:</p><ol><li>Calls to the LsaCallAuthenticationPackage Win32 API</li><li>Interaction with ALPC port lsasspirpc</li></ol><p>Our belief is that most EDR vendors already monitor calls to LsaCallAuthenticationPackage but only for detecting Keberos ticket recovery and PTT techniques. Vendors should instead view this as an API that facilitates all of the functionality LSA Whisperer offers. Some attackers may choose to circumvent this API by interacting with the SSPI RPC server directly. The intended RPC endpoint for the SSPI RPC server is the lsasspirpc ALPC port. So we recommend that EDRs monitor for processes that interact directly with that endpoint instead of using the Win32 API. LSA Whisperer itself may be used to test this as it will interact with the ALPC directly by default.</p><p>Lastly, we recommend that EDRs prevent the following activity:</p><ol><li>Calls to LSASS RPC endpoints <em>other than</em> lsasspirpc for interface 4f32adc8–6052–4a04–8701–293ccf2096f0 (SSPI)</li></ol><p>A well known technique to circumvent the monitoring of a specific RPC endpoint is to send the same RPC requests to any other endpoint hosted by the process running the RPC server. That works because the RPC runtime allows you to send RPC requests for any RPC interface registered by a process to any RPC endpoint the process is currently listening on and the runtime will fulfill that request. Attackers may use this approach to bypass additional monitoring of the lsasspirpc ALPC port but legitimate software will never do this. Instead, legitimate software will only interact with the lsasspirpc ALPC port using the documented Win32 API. So preventing all SSPI RPC requests to any RPC endpoint other than the lsasspirpc ALPC port should be safe to do and provide a true positive detection.</p><h3>Conclusion</h3><p>We touched on several topics in this post, but what I want you to take away is that most (and possibly all) of the credentials an attacker needs to accomplish their objectives on a Windows operation can be achieved without accessing LSASS’s memory. You do not even need to open a handle to LSASS. In the right situation, you can get what you want if you ask LSA nicely.</p><p>Do you need Kerberos tickets? Wait for the target user to login, impersonate the user or SYSTEM, and then ask LSA to give them to you using normal “ticket dumping” tradecraft. Do you instead need an NT hash for PtH tradecraft? Assuming Credential Guard is disabled, impersonate SYSTEM, request an NTLMv1 response for a logon session of the target user with a chosen server challenge, then crack it to a usable NT hash for the user. Do you instead need access to the plethora of user data encrypted with DPAPI? Impersonate SYSTEM, request the DPAPI credential key for a logon session of the target user, then use it with <a href="https://github.com/GhostPack/SharpDPAPI">SharpDPAPI</a> to decrypt their DPAPI master key file. Do your red team assessments now include cloud-based objectives? Impersonate a cloud-based user logon session then request LSA to give you a SSO cookie for that account.</p><p>If you like this work, please checkout the <a href="https://github.com/EvanMcBroom/lsa-whisperer">LSA Whisperer project on GitHub</a>! The project also includes <a href="https://github.com/EvanMcBroom/lsa-whisperer/wiki">an extensive wiki</a> for all of the research that was done. You can use the <a href="https://github.com/EvanMcBroom/lsa-whisperer?tab=readme-ov-file#building">building guide</a> in the project’s readme file and the <a href="https://github.com/EvanMcBroom/lsa-whisperer/wiki/Usage">usage guide</a> on the project’s wiki to get started. For the SOCON presentation, <a href="https://github.com/SpecterOps/presentations/tree/master/SO-CON%202024/Evan%20McBroom%20-%20LSA%20Whisper">the slides are available on Github</a> and video will be available for free on <a href="https://www.youtube.com/@specterops">SpecterOps’s YouTube channel</a> once it is released. If you have a question, you can reach out to me in the <a href="https://ghst.ly/BHSlack">BloodHoundGang Slack team</a> or by <a href="https://github.com/EvanMcBroom/lsa-whisperer/discussions">starting a discussion on GitHub</a>. I will do my best to respond to questions as I am able to. If you see an area where the project or wiki can be improved, please submit an issue on GitHub or consider making a pull request for the project. Your contributions are appreciated!</p><p>Lastly, thank you — the reader — for taking time to check out this work. It was a pleasure to do and I hope you enjoyed reading it.</p><h3>Updates</h3><ul><li>Apr 19, 2024: Our original understanding for the purpose of the CacheLogon call was incorrect which <a href="https://twitter.com/alexsho71327477">Alex Short</a> reached out to help clarify. Kerberos does not decrypt data before caching it. The data is only stored in the registry under HKLM\Security\Cache for later recovery by using the CacheLookup call. This is the same cache used by LsaApLogonUserEx2 to store user data for future logon attempts when Netlogon is unavailable. Lastly, the cached data is not used for NTLM authentication which removes these calls as a possibility for performing Pass the Hash. Thank you Alex for the help understanding these calls!</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20874277ea3b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/specter-ops-posts/lsa-whisperer-20874277ea3b">LSA Whisperer</a> was originally published in <a href="https://medium.com/specter-ops-posts">Posts By SpecterOps Team Members</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sleepy — Python Tooling for Sleep]]></title>
            <link>https://medium.com/specter-ops-posts/sleepy-python-tooling-for-sleep-7a96d9d650ee?source=rss-19644b9f54e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a96d9d650ee</guid>
            <category><![CDATA[specterops]]></category>
            <category><![CDATA[infosec]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[red-teaming]]></category>
            <dc:creator><![CDATA[Evan McBroom]]></dc:creator>
            <pubDate>Thu, 14 Dec 2023 16:05:56 GMT</pubDate>
            <atom:updated>2023-12-22T13:33:46.827Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sleepy — Python Tooling for Sleep</h3><p><em>Thank you to </em><a href="https://specterops.io/"><em>SpecterOps</em></a><em> for supporting this research and to </em><a href="https://www.linkedin.com/in/sarah-miles-81ab6a41/"><em>Sarah</em></a><em>, </em><a href="https://twitter.com/its_a_feature_"><em>Cody</em></a><em>, and </em><a href="https://twitter.com/hotnops"><em>Daniel</em></a><em> for proofreading and editing! Crossposted on </em><a href="https://gist.github.com/EvanMcBroom/3020e8d2d2dfc3de292e3b68b8b01014"><em>GitHub</em></a><em>.</em></p><p>TL;DR: <em>You can use </em><a href="https://github.com/EvanMcBroom/sleepy"><em>sleepy</em></a><em> to automate common tasks when working with Sleep code.</em></p><p><a href="https://www.hick.org/~raffi/">Raphael Mudge</a> created the embeddable scripting language, <a href="http://sleep.dashnine.org/">Sleep</a>, in April 2002. Sleep was designed to extend Java applications and has been used in few projects; most notably <a href="https://www.fortra.com/product-lines/cobalt-strike">Cobalt Strike</a>.</p><p>Cobalt Strike’s reliance on a relatively unpopular language with a small developer community has resulted in a need for language tooling and a lack of community support to build it. In this article, I will present a brief primer on Cobalt Strike’s usage of Sleep, an issue that <a href="https://specterops.io/">SpecterOps</a> and I have experienced due to Sleep’s lack of tooling, and the solution we developed to overcome this issue.</p><h3>Aggressor Scripts</h3><p>Using Sleep scripts is the officially supported method for users to modify, extend, and automate Cobalt Strike. The distribution of Sleep that comes with Cobalt Strike is heavily modified to support these use cases. First, the distribution is extended with snippets of Java code (i.e., “bridges”) that allow Sleep code to interact with features of Cobalt Strike. Second, the distribution ships with an additional library of premade functions to simplify working with the product. These modifications are significant enough that code written for Cobalt Strike’s distribution of Sleep is referred to using a new term (i.e., “aggressor scripts”), but the underlying language is the same.</p><p>Many users have written aggressor scripts for Cobalt Strike, of which the free and open-source software (FOSS) ones are tracked by the product’s parent company (i.e., <a href="https://www.fortra.com/">Fortra</a>) on their <a href="https://cobalt-strike.github.io/community_kit/">Community Kit</a> page. A subset of these scripts are designed to provide front end user information for another type of product extension known as a Beacon object file (BOF). We use many community provided BOFs at <a href="https://specterops.io/">SpecterOps</a> and internally manage their updates using Git, a CI/CD pipeline, and an artifact store.</p><h3>Proprietary Systems Integration</h3><p>These systems have allowed us to automate the majority of the process of managing BOF updates but they introduce an overhead problem. Our systems will push compiled BOFs to an artifact store and their associated aggressor scripts will need to be updated to pull from that store instead of the file system. Due to the lack of Sleep tooling, we are required to manually inspect these aggressor scripts after each update to check if they have meaningfully changed from our modified copies (e.g., by adding user documentation for a new BOF argument). If they have, we then need to manually update our internal copies appropriately.</p><p>Our systems are automated enough that they do not need a dedicated employee to tend to them each day, but the manual component requires an employee to shepherd each new update we do. We would ideally automate the process of modifying public aggressor scripts to pull from our artifact store; however, such a task would require Sleep tooling — specifically, a lexer, parser, and code generator for the language.</p><h3>Sleep’s [Lack of] Tooling</h3><p>Technically, the official language distribution comes with tools, but they do not support our use case. The distribution provides a standalone read-eval-print loop (REPL) command-line interface (CLI) tool for executing Sleep code and an embeddable parser written in Java. The REPL tool does not help with our specific problem and the parser does not produce a modifiable abstract syntax tree (AST) that may we use to generate new Sleep code.</p><p>Updating the existing parser to support our needed features would be too problematic. The parser conflates lexing and parsing tasks in its class design to where updating one class would break other classes. In design terms, they have <a href="https://en.wikipedia.org/wiki/Coupling_(computer_programming)">high coupling</a> and <a href="https://en.wikipedia.org/wiki/Cohesion_(computer_science)">low cohesion</a>. Even if the parser supported our needed features, it would need updates regardless because it does not conform to its own language documentation. As an example, the parser allows for missing semicolons after statements and missing commas between list items; both issues should be caught as syntax errors.</p><h3>Our Solution</h3><p>Presented with these issues, we decided to write our own lexer and parser for Sleep. Each may be used as standalone tools and the parser will generate a modifiable AST that may be used to generate new Sleep code. Both tools were written as a Python library named <a href="https://github.com/EvanMcBroom/sleepy">sleepy</a> because it is a common language for all of our coworkers to develop in. The tools support all but one language feature, so-called Java object expressions (a.k.a, “Haphazard Object Extensions for Sleep”), which is enough support for our use cases and hopefully any use case you may have as well. You may access the project <a href="https://github.com/EvanMcBroom/sleepy">here</a> and the project examples <a href="https://github.com/EvanMcBroom/sleepy/tree/master/examples">here</a>.</p><p>With these tools, we are now able to fully automate our internal systems for managing BOF updates. When a community BOF is updated in our internal Git repositories, our CI/CD pipeline may use our parser to convert an associated aggressor script to an AST, modify any code in the AST that reads a BOF from the file system to instead read it from our artifact store, then generate a new aggressor script from the modified AST that our operators may use.</p><p>Let me show you an example of how we may do this. We will use <a href="https://trustedsec.com/">TrustedSec’s</a> <a href="https://github.com/trustedsec/CS-Situational-Awareness-BOF">“Situational Awareness”</a> project to demonstrate because we have it integrated with our internal update management workflow. The project includes C code for several BOFs but we will focus the project’s <a href="https://github.com/trustedsec/CS-Situational-Awareness-BOF/blob/master/SA/SA.cna">aggressor script</a>. The main goal of the script is to register a new beacon command for every BOF the project defines. The script defines a utility function named <a href="https://github.com/trustedsec/CS-Situational-Awareness-BOF/blob/9a813b8f31cd397d7b05211e1d5b378c07fd1b8b/SA/SA.cna#L80">readbof</a> for reading the project’s BOFs from the filesystem. For our use case, we would prefer the readbof function to read a BOF from our artifact store. Sleepy makes it simple to automate that change.</p><p>First, we will create an aggressor script that defines our new readbof function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FIcJdBe0cspZbRFwT2HV8A.png" /></figure><p>Then, we will use sleepy’s parser to convert the script into an AST.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xdTatTQILRZDno0xS9HR1A.png" /></figure><p>Finally, we will use sleepy’s parser to enumerate each statement in the original script, replace its readbof function with our patch, and output a new script that works with our artifact store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yjLkwMv6sVWbrtjPoy9Eag.png" /></figure><p>This was a simple example because only one patch was needed, but sleepy is flexible enough to automate complicated patches and other use cases as well.</p><p>To show some of these use cases, the project includes <a href="https://github.com/EvanMcBroom/sleepy/blob/master/examples/summarize_bofs.py">a longer example</a> that converts an aggressor script to a JSON file that summarizes all of the BOFs it defines a Beacon command for, if any. Such a script is useful for integrating BOF updates with other systems such as an internal documentation server or another C2 platform. A similar script could also be used to notify operators when the documentation for a Beacon command has changed so that they may review it. These are only a few examples and I am sure readers will have more ideas for how the project can help with their own internal workflows.</p><h3>Conclusion</h3><p>Managing updates for third-party Sleep code can cause management overhead that is difficult to automate due to a lack of tools for the language. We specifically encountered this problem at <a href="https://specterops.io/">SpecterOps</a> when updating aggressor scripts for open-source BOFs to integrate with our internal systems.</p><p>The solution we developed was to build a lexer, parser, and code generator for Sleep which we are releasing for others to use as well. The project includes example ways to use the tools including a syntax checker, code formatter, and code minimizer. We hope you enjoyed this work and find the tools helpful for your own internal workflows!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a96d9d650ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/specter-ops-posts/sleepy-python-tooling-for-sleep-7a96d9d650ee">Sleepy — Python Tooling for Sleep</a> was originally published in <a href="https://medium.com/specter-ops-posts">Posts By SpecterOps Team Members</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Perfect Loader Implementations]]></title>
            <link>https://medium.com/specter-ops-posts/perfect-loader-implementations-7d785f4e1fa?source=rss-19644b9f54e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d785f4e1fa</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[red-teaming]]></category>
            <category><![CDATA[specterops]]></category>
            <category><![CDATA[infosec]]></category>
            <dc:creator><![CDATA[Evan McBroom]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 17:28:18 GMT</pubDate>
            <atom:updated>2023-10-09T17:28:18.468Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Thank you to<a href="https://specterops.io/"> SpecterOps</a> for supporting this research and to <a href="https://twitter.com/tifkin_">Lee </a>and <a href="https://www.linkedin.com/in/sarah-miles-81ab6a41/">Sarah</a> for proofreading and editing! Crossposted on <a href="https://gist.github.com/EvanMcBroom/0f45c1bdb55b4d5f43c7bcf336e0663e">GitHub</a>.</blockquote><p>TLDR: <em>You may use</em><a href="https://github.com/EvanMcBroom/fuse-loader"><em> fuse-loader</em></a><em> or</em><a href="https://github.com/EvanMcBroom/perfect-loader"><em> perfect-loader</em></a><em> as examples for extending an OS’s native loader to support in-memory libraries.</em></p><p>Some software applications require the ability to load dynamic libraries from the memory of the application’s own process. The majority of desktop OSes do not support this use case, so a number of developers have reimplemented the process of loading a library to overcome this limitation.</p><p>The quality of these reimplementations may be judged by comparing the feature set of these custom loaders against what the OS’s native loader supports. As such, the native OS loader may be considered a “perfect loader,” but it should not be considered the <em>only </em>perfect loader.</p><p>An OS’s loader can be modified or used with other native OS facilities to support in-memory libraries. Extending a native loader in such a manner will result in a new loader which supports both in-memory libraries <em>and</em> the entirety of the native loader’s original feature set (i.e., a new perfect loader). These approaches are explored in the following sections.</p><h3>Native Loader Modifications</h3><p><a href="https://twitter.com/epakskape">Matt Miller</a> and <a href="http://www.klake.org/~jt">Jarkko Turkulainen</a> authored the seminal work on modifying native loaders with their publication of<a href="http://www.hick.org/code/skape/papers/remote-library-injection.pdf"> “Remote Library Injection”</a> in April, 2004. In the section titled “In-Memory,” they described placing hooks on relevant system routines an OS’s loader used (e.g., <strong>mmap</strong> and <strong>NtMapViewOfSection</strong>). Those hooks allowed them to use a native loader as intended while modifying the behavior of its underlying routines to have a library’s data be supplied from memory instead of the filesystem.</p><p>Although this technique was excellent, in 2011, <a href="https://twitter.com/stephenfewer">Stephen Fewer</a>’s<a href="https://github.com/stephenfewer/ReflectiveDLLInjection"> ReflectiveDLLInjection</a> project (which reimplemented <strong>LoadLibrary</strong>) overshadowed it. What Stephen developed was useful, but <strong>LoadLibrary</strong> reimplementations are incomplete by nature and their feature gaps will only grow with time.</p><p>Matt and Jarkko’s approach for modifying the native Windows loader required manually parsing a library’s file format to map its sections into appropriately protected memory regions. Although this was required at the time, overwriting an open file in an uncommitted NTFS transaction and using it to create a section object can bypass this step. The native loader can then be redirected to use the section object with the updated file data instead of a section object with the original file data.</p><p>The original approach of using a section object created from an updated file in an uncommitted NTFS transaction was documented by <a href="https://twitter.com/Tal_Liberman">Tal Liberman</a> and <a href="https://twitter.com/eukogan">Eugene Kogan</a> in their work titled <a href="https://www.blackhat.com/docs/eu-17/materials/eu-17-Liberman-Lost-In-Transaction-Process-Doppelganging.pdf">“Process Doppelgänging.”</a> While their work only described using the section object to create a new process or thread, you can use it to extend <strong>LoadLibrary</strong> as described above. To my knowledge, this is a novel approach to using transactions and I personally refer to it as Module Doppelgänging to acknowledge Tal and Eugene’s prior work.</p><h3>Combining Native Facilities</h3><p>A native loader may also be extended by combining it with other native facilities. Such an approach is arguably more stable because it does not require hooking the native loader’s internal implementation, which will change over time.</p><p>The most straightforward example of this is certainly the use of <strong>memfd_create</strong><a href="https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=9183df25fe7b194563db3fec6dc3202a5855839c"> in Linux 3.17 and newer</a> to create a memory backed file descriptor whose full path may be provided to <strong>dlopen</strong>. Another simple approach used by developers supporting older versions of Linux and other POSIX platforms is to place libraries in <strong>tmpfs</strong> mounts (e.g., <strong>/dev/shm</strong>). While lesser known, POSIX developers have the additional option of hosting their libraries in a<a href="https://www.kernel.org/doc/html/next/filesystems/fuse.html"> Filesystem in Userspace (FUSE)</a> mount to use with <strong>dlopen</strong> as shown in<a href="https://github.com/EvanMcBroom/fuse-loader"> fuse-loader</a>.</p><p>Windows provides less approaches for combining a native loader with other native facilities to achieve in-memory loading, but there are solutions. The oldest available approach is to have your process host a WebDAV server, use <strong>LoadLibrary</strong> to load a path that resolves to your server, and have the server respond with the bytes of an in-memory library when that path is requested. <a href="https://twitter.com/jonasLyk">Jonas Lyk</a> created <a href="https://twitter.com/jonasLyk/status/1464977543468093447">this approach</a> and<a href="https://github.com/jonaslyk/temp/blob/main/dav.cpp"> implemented it as a proof of concept (POC)</a> for creating a new process from an in-memory executable, but WebDAV servers may also be used to load a library.<a href="https://twitter.com/alexsotirov"> Alexander Sotirov</a> showed this use case in 2006 with his work titled <a href="http://www.phreedom.org/research/tinype/">“Tiny PE”</a>, albeit it did not use a WebDAV server that the application’s own process hosted.</p><p>Newer versions of Windows with Windows Subsystem for Linux (WSL) come with a Plan9 multiple UNC provider (MUP) which allows users to access Linux files from their host using the <strong>\\wsl$</strong> UNC prefix. Such an ability allows developers to now use some of the above described POSIX approaches on Windows.</p><p>Some readers who learn this may be tempted to try loading an in-memory library by writing it to a named pipe and passing its path to <strong>LoadLibrary</strong>. Unfortunately, the underlying driver for SMB does not support creating section objects from a pipe and <strong>LoadLibrary</strong> will encounter the error <strong>STATUS_INVALID_FILE_FOR_SECTION</strong> when it internally calls <strong>NtCreateSection</strong>.</p><p>This summarizes the Windows approaches that I am aware of. Although few were listed, I am sure others will identify approaches I missed and newer approaches will become possible as Windows adds support for more technologies.</p><h3>Conclusion</h3><p>Although developers more commonly reimplement the process of loading a library to overcome the limitations of an OS’s native loader in regards to loading in-memory library data, such approaches are inherently incomplete. Further, reimplementing some native loader features can obligate developers to painful update cycles. An example of such an issue is with providing full exception handling support on Windows without using symbol data. Some developers achieve this by maintaining byte signatures of pertinent unexported NTDLL functions for every version of Windows.</p><p>Developers who use a perfect loader approach do not have these issues. Their implementations typically also require less code, less maintenance overhead, and will support more library loading features by design.</p><p>Two companion repositories were made for this blog to assist developers who are new to perfect loader approaches and interested in their use. The first is<a href="https://github.com/EvanMcBroom/fuse-loader"> fuse-loader</a>, which implements the FUSE mount approach for POSIX platforms. The second, <a href="https://github.com/EvanMcBroom/perfect-loader">perfect-loader</a>, implements various approaches for modifying the native Windows loader. If either sound interesting to you, I encourage you to check them out and hope you find them useful!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d785f4e1fa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/specter-ops-posts/perfect-loader-implementations-7d785f4e1fa">Perfect Loader Implementations</a> was originally published in <a href="https://medium.com/specter-ops-posts">Posts By SpecterOps Team Members</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Encrypting Strings at Compile Time]]></title>
            <link>https://medium.com/specter-ops-posts/encrypting-strings-at-compile-time-4141dafe5b41?source=rss-19644b9f54e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4141dafe5b41</guid>
            <category><![CDATA[red-teaming]]></category>
            <category><![CDATA[specterops]]></category>
            <category><![CDATA[infosec]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Evan McBroom]]></dc:creator>
            <pubDate>Wed, 20 Jul 2022 14:03:42 GMT</pubDate>
            <atom:updated>2022-07-20T14:03:42.198Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Thank you to </em><a href="https://specterops.io/"><em>SpecterOps</em></a><em> for supporting this research and to </em><a href="https://twitter.com/subat0mik"><em>Duane</em></a><em> and </em><a href="https://twitter.com/matterpreter"><em>Matt</em></a><em> for proofreading and editing! Crossposted on </em><a href="https://gist.github.com/EvanMcBroom/ace2a9af19fb5e7b2451b1cd4c07bf96"><em>GitHub</em></a><em>.</em></blockquote><p>TLDR: <em>You may use </em><a href="https://gist.github.com/EvanMcBroom/ad683e394f84b623da63c2b95f6fb547"><em>this header file</em></a><em> for reliable compile time string encryption without needing any additional dependencies.</em></p><p>Programmers of DRM software, security products, or other sensitive code bases are commonly required to minimize the amount of human readable strings in binary output files. The goal of the minimization is to hinder others from reverse engineering their proprietary technology.</p><p>Common approaches that are taken to meet this requirement often add an additional maintenance burden to the developer and are prone to error. These approaches will be presented along with their drawbacks. An alternative solution will also be presented which targets the following goals:</p><ul><li>A minimalistic implementation to ease integration into projects</li><li>A simple usage design to avoid programmer error</li><li>Builtin randomization to hinder automated string recovery</li></ul><h3>Common Approaches</h3><p>Separate utilities are commonly built to precompute obfuscated strings for use in source code. Such tools will generate a header file or other output that must be manually added to and referenced in projects. The use of these tools may be automated with a toolchain but they will not integrate well with IDEs and they are tedious to maintain as more strings are added. They also tend to obfuscate strings in a uniform way that can be easily identified and reversed in an automated fashion.</p><p>In a similar manner, utilities are also commonly built to precompute string hashes for use in comparisons. One of the earliest examples of this is documented in “Win32 Assembly Components.”¹ These tools are also tedious to maintain as more strings are added but they can now be completely eliminated by hashing strings at compile time <a href="https://gist.github.com/EvanMcBroom/2a9bed888c2755153a9616aa7ae1f79a">as described in a previous post</a>.</p><p>Lastly, some development teams attempt to remove the use of strings entirely. Needless to say this is an impossible standard to maintain for any large or long lasting project with any amount of developer turnover.</p><h3>An Alternative Solution</h3><p>Modern C++ features may be used to encrypt strings at compile time which can greatly reduce the maintenance overhead for developers. There are several libraries that claim to support this use case. Unfortunately, they rarely work in practice. The few that do require <a href="https://www.boost.org/">BOOST</a> libraries which may not be an option due to development constraints.² So we will build our own!</p><p>We will first make a basic function for compile time string encryption which we can later improve upon. The below crypt function will convert a string literal into an encrypted blob and the make_string macro wraps crypt to ensure that it is used correctly to be evaluated at compile time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*m8KrRNdISrhF8x-zY57N3Q.png" /></figure><p>The make_string macro will also expand to a single lambda expression which can be used for any variable assignment and argument passing operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*dp_FJJOIW_vK6B7Hr4RtIA.png" /></figure><h3>Improving the Solution</h3><p>The previous solution would be easy to integrate and use in projects but it would also be easy for a reverse engineer to undo. It is essentially a XOR cipher with a static key. Once the key is identified the entire program can be XORed with it and then the original strings can be recovered using the humble strings utility.</p><p>Replacing the static key with a random bit stream would prevent this issue. We will now make a set of functions for generating such a stream at compile time. We will use Park-Miller’s “Multiplicative Linear Congruential Generator” due to its simplicity to implement.³</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*4-3Qlfk64GSO9TxHA8-MGw.png" /></figure><p>We will also need a pseudorandom value to use as the initial input to prng. Admittedly, it is not easy to generate such a value at compile time but it can be accomplished using standard predefined macros such as __FILE__ and __LINE__. The below seed function can take these macros as input and reduce them to a single pseudorandom value to use with prng.</p><blockquote><em>Note: These macros are defined by the ANSI C standard and are supported by all compilers. If you use a non-standard macro for entropy your mileage may vary.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*yDCtiYIwenFoR-nYyXYOcw.png" /></figure><p>The last thing that is required is to update our original crypt and make_string functions to use our random bit stream generator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*tD_X1Wma6UGAEsCsiOtZQw.png" /></figure><blockquote><em>Note: If you are using Visual Studio, you will need to disable the “Edit and Continue” feature; otherwise, </em><a href="https://developercommunity.visualstudio.com/t/-line-cannot-be-used-as-an-argument-for-constexpr/195665#T-N197532"><em>the </em></a><a href="https://developercommunity.visualstudio.com/t/-line-cannot-be-used-as-an-argument-for-constexpr/195665#T-N197532"><em>__LINE__ macro will not need be usable in a constant expression</em></a><em>.</em></blockquote><h3>Incident Response</h3><p>If you are investigating a potentially malicious executable, it may also contain strings encrypted in such a manner. The provided code will protect strings against any cursory inspection, but they may all be recovered using <a href="https://github.com/mandiant/flare-floss">FLARE’s Obfuscated String Solver</a> (FLOSS).</p><p>Additional small improvements may be made to prevent automated string recovery using FLOSS as well. One example would be to include an exception based control flow to the decryption routine. In the interest of incident responders though, these improvements will not be presented and are left as an exercise to the reader.</p><h3>Conclusion</h3><p>We now have a solution for encrypting strings at compile time that meets all of our original goals and will work with any mainstream compiler. The full source for which can be found <a href="https://gist.github.com/EvanMcBroom/ad683e394f84b623da63c2b95f6fb547">here</a>. Enjoy! 😄</p><p>If you enjoyed reading this work, you may enjoy some of my older posts as well. The first covers compile time hashing functions and the second gives a more user friendly alternative to the programming idiom for declaring strings in position independent code.</p><ul><li><a href="https://gist.github.com/EvanMcBroom/2a9bed888c2755153a9616aa7ae1f79a">Switch Statements with Full Strings</a></li><li>PIC and String Literals <a href="https://gist.github.com/EvanMcBroom/f5b1bc53977865773802d795ade67273">Part 1</a> and <a href="https://gist.github.com/EvanMcBroom/d7f6a8fe3b4d8f511b132518b9cf80d7">Part 2</a></li></ul><h3>References</h3><ol><li>The Last Stage of Delirium Research Group. <em>Win32 Assembly Components</em>, 2002.http://www.lsd-pl.net/documents/winasm-1.0.1.pdf</li><li>Sebastien Andrivet. <em>C++11 Metaprogramming Applied to Software Obfuscation</em>, 2014.https://www.blackhat.com/docs/eu-14/materials/eu-14-Andrivet-C-plus-plus11-Metaprogramming-Applied-To-software-Obfuscation-wp.pdf</li><li>Stephen Park and Keith Miller. <em>Random Number Generators</em>, 1988.https://www.firstpr.com.au/dsp/rand31/p1192-park.pdf</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4141dafe5b41" width="1" height="1" alt=""><hr><p><a href="https://medium.com/specter-ops-posts/encrypting-strings-at-compile-time-4141dafe5b41">Encrypting Strings at Compile Time</a> was originally published in <a href="https://medium.com/specter-ops-posts">Posts By SpecterOps Team Members</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>