<?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 Ryan Cobb on Medium]]></title>
        <description><![CDATA[Stories by Ryan Cobb on Medium]]></description>
        <link>https://medium.com/@cobbr?source=rss-d248a36145f8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BVBDVaNXHyoA59MUSLGP4A.png</url>
            <title>Stories by Ryan Cobb on Medium</title>
            <link>https://medium.com/@cobbr?source=rss-d248a36145f8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 09:04:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cobbr/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[Covenant v0.6]]></title>
            <link>https://medium.com/specter-ops-posts/covenant-v0-6-134c5054505f?source=rss-d248a36145f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/134c5054505f</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[infosec]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Ryan Cobb]]></dc:creator>
            <pubDate>Tue, 04 Aug 2020 18:32:31 GMT</pubDate>
            <atom:updated>2020-08-04T18:32:31.154Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yNOShb9ZeNRpJAvR9Gpq3w.png" /></figure><h3>Intro</h3><p><a href="https://github.com/cobbr/Covenant">Covenant v0.6</a> is being released today and includes a set of new features and lots of bug fixes.</p><p>This will be a short post documenting some of the major feature updates.</p><h3>Streaming Output</h3><p>Covenant now supports a model that allows Tasks to stream output back to the Covenant server periodically throughout execution. This enables long-running Tasks, such as a Keylogger, and Tasks that could have large amounts of output, such as a Download Task.</p><p>Before now, the Keylogger task would need to be configured to run for a pre-determined amount of time, and output would only be received once the pre-determined amount of time had passed. With streaming output, the Keylogger can be told to run indefinitely and output streams back to the server as new keys are logged.</p><p>Likewise, the Download task used to struggle with large files that tested the limits of the size of an HTTP request. With streaming output, large files can be split into many chunks, which makes it much easier to download arbitrarily large files.</p><p>To utilize the new streaming output model, Tasks can declare a Stream called OutputStream. When a Task writes data to the OutputStream, it’ll make its way back to the Covenant server as output for the Task.</p><p>For example, here’s a sample of what the new Download Task looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6d5dd7664bdb8673556f3db6807d8fc/href">https://medium.com/media/e6d5dd7664bdb8673556f3db6807d8fc/href</a></iframe><p>Covenant sets up the OutputSteam for the Task using <a href="https://docs.microsoft.com/en-us/windows/win32/ipc/anonymous-pipes">anonymous pipes</a>. You can think of anonymous pipes as one-way, unnamed versions of <a href="https://docs.microsoft.com/en-us/windows/win32/ipc/named-pipes">named pipes</a>, which you may be more familiar with. The OutputStream writes data over the anonymous pipe back to the Grunt implant, which queues messages that will be delivered as a part of the implant’s regular C2 channel, determined by the Profile and Delay values.</p><p>For example, here’s a (simplified) example of how the Grunt implant sets up the anonymous pipes and queues up tasking messages received from the OutputStream:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6e0e8127e28eb3be56b05eb7a145ff4/href">https://medium.com/media/a6e0e8127e28eb3be56b05eb7a145ff4/href</a></iframe><p>Tasks can choose to support the streaming model or not, so existing Tasks do not need to be altered to adapt to this model. The original model of returning output at the end of the Task still works for output that can afford to wait until the Task has completed.</p><p>Many of the Tasks that could benefit most from the streaming model have already been converted to use the new paradigm, including: Keylogger, Download, and all of the GhostPack tasks.</p><h3>UI Themes</h3><p>A long requested and heavily debated feature, UI themes have made their way into Covenant. Themes allow operators to completely customize the look and feel of their Covenant interface. By default, Covenant comes with the standard Classic Theme, and also supports a, questionable at best, Heathen Mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sXwqBnHgtfQiS5p-14TVog.png" /><figcaption>Available Themes</figcaption></figure><p>Themes are applied per operator, so every operator can use their own preference of Theme. Operators that have poor taste when it comes to UI design may choose to utilize the new Heathen Mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZDtnEebJujfOdwnLd6yt_g.png" /><figcaption>Heathen Mode Theme</figcaption></figure><p>But operators are not limited to the default themes, as custom Themes can be built directly in the interface.</p><p>Now that this feature has made its way into Covenant, everyone can please stop bothering us about it. Thanks.</p><h3>Tabbed Terminal View</h3><p>Finally, Covenant now includes a “tabbed terminal” view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RpE92SdquFuGM9u9hfYTHg.png" /></figure><p>The tabbed terminal view makes it easy to operate when quickly switching between multiple implants. Clicking the small terminal icon next to the entry in the Grunt table activates the Grunt into the tabbed terminal view below.</p><p>Of course, you can still always click on the hyperlinked name of a Grunt to get the typical, full-screen Grunt view you may be used to.</p><p>The tabbed terminal view is a great example of a UI feature that has been enabled by Covenant’s recent rebuild on Blazor. Blazor enables Covenant to re-use UI components, such as terminal views, that just wouldn’t have been maintainable without Blazor.</p><h3>Bug Fixes</h3><p>This version of Covenant came with a major focus on big fixes as well, as will the next version of Covenant. Since Covenant received a rather large overhaul in v0.5, there’s likely still some outstanding Github issues to address.</p><p>A number of bugs have been fixed for v0.6, check out the <a href="https://github.com/cobbr/Covenant/blob/master/CHANGELOG.md">changelog</a> for details.</p><h3>Conclusion</h3><p>Covenant adds a number of new features in v0.6, including: streaming output, UI themes, and a tabbed terminal view.</p><p>As always feel free to join the conversation about Covenant in the #covenant channel on the BloodHoundGang Slack, just message <a href="https://twitter.com/cobbr_io">@cobbr_io</a> on Twitter if you’d like an invitation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=134c5054505f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/specter-ops-posts/covenant-v0-6-134c5054505f">Covenant v0.6</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[Covenant v0.5]]></title>
            <link>https://medium.com/specter-ops-posts/covenant-v0-5-eee0507b85ba?source=rss-d248a36145f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/eee0507b85ba</guid>
            <category><![CDATA[blazor]]></category>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[hacking]]></category>
            <dc:creator><![CDATA[Ryan Cobb]]></dc:creator>
            <pubDate>Thu, 04 Jun 2020 18:04:51 GMT</pubDate>
            <atom:updated>2020-06-04T19:27:30.962Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yNOShb9ZeNRpJAvR9Gpq3w.png" /></figure><h3>Intro</h3><p><a href="https://github.com/cobbr/Covenant">Covenant v0.5</a> is being released today and includes a set of new features, a major UI update, and lots of bug fixes.</p><p>This will be a short post documenting some of the major feature updates.</p><h3>Blazor: Front-End C#</h3><p>The largest update in v0.5 is migrating the interface over to the <a href="https://docs.microsoft.com/en-us/aspnet/core/blazor/?view=aspnetcore-3.1">Blazor</a> framework. Blazor is a framework for writing client-side web interfaces in C#.</p><p>Prior to Blazor, Covenant didn’t utilize any real client-side framework like React, Angular, etc. The client-side of the Web UI was written with some one-off JavaScript functions that utilized only JQuery. This made UI components difficult to scale and maintain. Since Covenant is already built on .NET Core, it made a lot of sense to use Microsoft’s new client-side framework, Blazor.</p><p>I’m not particularly fond of writing JavaScript anyways, so that fact that client-side code in Blazor is written in C# made the transition even better. Beyond language preference, this allows the client-side of the application to take full advantage of the .NET Core ecosystem and libraries. We also hope that this makes the UI much more approachable to those that might be interested in making UI contributions to the project.</p><p>Additionally, Blazor transforms Covenant into a true SPA, or Single Page Application. What exactly does this mean? As a Covenant user, the first time you visit the Covenant site an HTTP request is made to pull down the initial application, and that’s it, no more HTTP requests! The rest of your interaction with the server is accomplished over real-time WebSockets.</p><p>The main difference you’ll see as a user, is pages should load a little bit faster than before, and the entire interface should update in real-time as things change on the backend server. For example, no more need to refresh the page to check for a Grunt’s new LastCheckIn time! The interface has been overhauled to take advantage of the real-time features provided by Blazor.</p><h3>Brutes: The New .NET Core Implant</h3><p>Covenant has a brand new built-in, cross-platform implant: Brutes! Operators are no longer limited to Grunt implants or to Windows targets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GPwfQNeTwmf5xUXwEu4fhg.png" /><figcaption>Active Brutes on Windows, Linux, and MacOS Targets</figcaption></figure><p>Covenant has slowly been moving towards the goal of being truly implant-agnostic, and the introduction of the Brute implant is a major step towards that goal. The concept of an implant-agnostic C2 framework has been talked about over the last few years, and was really pioneered by the <a href="https://github.com/FactionC2/Faction">Faction</a> and <a href="https://github.com/its-a-feature/Apfell">Apfell</a> frameworks. The idea is that many different implants can communicate over a common protocol dictated by the framework, and easily plug into the framework. Covenant has technically supported the implant-agnostic model for quite awhile.</p><p>The introduction of ImplantTemplates in v0.4 allowed operators to easily modify and create new C# implants and was an initial step towards making implant creation more accessible to developers. With the introduction of Brutes, Covenant now has an implant that is written in C#, but <strong>not</strong> based on the .NET Framework at all. The implant is fully supported and built-in to the platform.</p><p>As Covenant continues to make steps towards the implant-agnostic model, I’d encourage operators and developers to try their hand at modifying existing implants for their needs, or creating their own personal implant!</p><p>The Brute implant itself is fairly simple, there isn’t a huge library of available tasks quite yet, but some of the most important tasks are available: shell, ps, ls, assembly, and a handful of others. The Brute implant shares a large percentage of it’s codebase with Grunts, with some minor changes to port the code over to .NET Core, but there’s not many libraries to borrow tasks from available in .NET Core like there is for the .NET Framework, such as SharpSploit and GhostPack.</p><p>There’s a lot to say about the potential of .NET Core implants, and I plan to release a follow-up post on .NET Core malware in the near future. I’ll leave most of those details for that post. For now, it’s enough to say that Brutes are cross-platform .NET Core implants with a limited set of base functionality.</p><h3>Shareable Tasks</h3><p>Tasks can now be easily imported and exported to or from a running Covenant instance as YAML files. This makes it much easier to share your Covenant tasks with others that may be interested in your work.</p><p>It also makes it much easier to contribute built-in Tasks to the project. Before this change, built-in Tasks were described programmatically in Covenant’s source code, and required source code changes to add new built-in Tasks. Now, YAML files included under the Data\Tasks directory will automatically be parsed and imported when Covenant first starts up. Additional tasks that you would like to use can be imported within the interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FLTqOWURkT_XjLlqxMijSg.png" /><figcaption>Import Tasks through the UI</figcaption></figure><p>Hopefully, this makes it much easier to share custom Tasks or to maintain your own libraries of custom Tasks.</p><h3>Other Minor Updates</h3><p>There are many more updates and fixes in this release than we are able to mention here, but here’s a few other minor updates you’ll find in v0.5:</p><ul><li><strong>Author Information</strong> — Author information is included in GruntTasks, so you’ll get credit for the Tasks you contribute to Covenant.</li><li><strong>Hide and Unhide Grunts</strong> — The ability to hide and unhide Grunts has been reworked, so you can easily hide and unhide old Grunts that are no longer in use from the UI.</li><li><strong>Manual Data Creation</strong> — Credentials and Indicators can be manually added to the schema now, instead of just relying on Covenant’s automatic detection of new data.</li><li><strong>Updated ReferenceSourceLibraries</strong> — ReferenceSourceLibraries such as SharpSploit and GhostPack have been brought up to date with the public versions.</li></ul><h3>Conclusion</h3><p>Hopefully this has given you a brief summary of some of the major updates in the new v0.5 Covenant update. This has been the first major Covenant update in nearly 7 months, as the UI conversion over to Blazor took much more work than anticipated. Hopefully it’s been worth the wait!</p><p>In the future, we hope that Covenant updates will be much more frequent and incremental, to decrease the waiting time between updates. In the near term future, Covenant has developed quite a backlog of issues and pull requests that need to be addressed, and we likely will be focused on those and any new issues that arise from the new release. Also be on the lookout for an upcoming post on .NET Core malware for additional information related to the Brute implant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eee0507b85ba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/specter-ops-posts/covenant-v0-5-eee0507b85ba">Covenant v0.5</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[Covenant: Developing Custom C2 Communication Protocols]]></title>
            <link>https://medium.com/specter-ops-posts/covenant-developing-custom-c2-communication-protocols-895587e7f325?source=rss-d248a36145f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/895587e7f325</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[infosec]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Ryan Cobb]]></dc:creator>
            <pubDate>Wed, 30 Oct 2019 14:03:36 GMT</pubDate>
            <atom:updated>2019-10-30T14:03:36.264Z</atom:updated>
            <content:encoded><![CDATA[<p>As of <a href="https://github.com/cobbr/Covenant">Covenant v0.4</a>, Covenant provides options that allow developers to integrate custom C2 communication protocols into an operation within Covenant.</p><p>This post provides a guide for Listener development, introduces the new <a href="https://github.com/cobbr/C2Bridge">C2Bridge</a> project, and describes how C2Bridges can be used within Covenant.</p><h4>HTTP Protocol</h4><p>For C2 (Command and Control), we require some communication protocol with which implants can interact with an attacker-controlled server to receive taskings and report back the results of issued commands. There is nearly an infinite amount of protocols we could use to accomplish this communication, but not all of them are convenient or common enough to blend into target environments.</p><p>Covenant officially supports only a single communication protocol: <strong>HTTP</strong>.</p><p>There are many benefits to using HTTP for this implant to server communication. HTTP is a ubiquitous protocol that is likely to blend into many target environments. <a href="https://blog.cobaltstrike.com/2017/02/06/high-reputation-redirectors-and-domain-fronting/">Domain Fronting</a> can be utilized via HTTP, allowing us to utilize high trust domain names. HTTP is high-throughput and low latency, allowing us to quickly transfer large amounts of data between the server and an implant. For these reasons, many C2 frameworks make use of the HTTP protocol for its primary communication protocol.</p><p>But there are also drawbacks to using the HTTP protocol. For example, Covenant’s HTTP listener requires a Grunt implant to continuously poll the server to check for new taskings, even while there are none.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NvkpESebvGumMih48z_dcg.png" /><figcaption><strong>Empty HTTP Polling</strong></figcaption></figure><p>This consistent, unnecessary traffic is not always desirable. Many C2 frameworks have a similar drawback with their own HTTP implementation.</p><h4>Protocol Agnostic</h4><p>There really is no reason that Covenant should need to constrain us to this one communication protocol. As long as you are able to transfer data to and from an implant on a remote network, Covenant should ideally be agnostic to the communication protocol that accomplishes this data transfer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Ja00GAXGFJ3DzZ0KS-XYw.png" /><figcaption><strong>Protocol Agnostic</strong></figcaption></figure><p>So while Covenant only includes the one built-in protocol for now, it provides developers with the tools necessary to integrate custom communication protocols into the platform.</p><p>Covenant now supports two primary features for integrating new communication protocols:</p><ol><li><strong>Listeners</strong> — Listeners can be created from within the Covenant interface and are built-in to Covenant directly. You may already be familiar with Listeners if you have used the Covenant platform before.</li><li><strong>C2Bridges</strong> — C2Bridges are a new feature that are developed outside of the Covenant platform entirely.</li></ol><h3>Creating New Listeners</h3><p>If a developer would like to create a new first-class listener that integrates with the Covenant interface or if they would like to contribute a communication protocol to the Covenant project as a built-in listener, they should choose to create a Listener rather than a C2Bridge.</p><p>Creating a Listener requires that the developer write their communication protocol logic in C# within the Covenant project, and that they write a class that inherits from the Listener class within Covenant. The developer will have to make some minor edits to the Covenant backend code to accomplish this. The developer will also need to make some changes to Covenant’s front-end code so that users can visually interact with and create new Listeners that use the new communication protocol.</p><p>When developing a new communication protocol, a developer needs to handle:</p><ol><li><strong>Listener-side development</strong></li><li><strong>Implant-side development</strong></li></ol><p>This is true for both Listeners and C2Bridges. Each side of the protocol needs to know how to “speak” the new protocol.</p><h4>Listener-Side Development</h4><p>As of Covenant v0.4, the development of new listeners is much easier than before. Listeners only need to implement a mechanism to read data from implants and write data back to implants. All of the details for interpreting the data returned from implants is handled by Covenant itself, listeners do not need to handle this.</p><p>For example, the existing relevant HTTP listener code is only a handful of lines of code (though it does make use of ASP.NET Core to offload development):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b749d93d253feb49ad599cd83da75b9/href">https://medium.com/media/8b749d93d253feb49ad599cd83da75b9/href</a></iframe><p>Let’s take a quick look at the Post() function in particular. This is the function that gets called each time an implant writes data to the HTTP listener. Whenever an implant writes data, the listener is responsible for:</p><ol><li>Determining which implant this data is from. The Listener determines which implant is posting data by using the GetGuid()helper function, which parses the HTTP request and locates the Grunt GUID value within the data by using the configured location within the HttpProfile.</li><li>Retrieving the actual data from within the larger message. Profiles determine where the data is placed within an HTTP message. This allows us to create benign looking HTTP messages that our data is hidden within. The Listener is responsible for extracting the data from within the message, using the Profile to parse out this information. This is done within the Post()method with the body.ParseExact() method.</li><li>Writing the extracted data to an InternalListener object. The InternalListener object will interpret messages from implants, so that the listener doesn’t have to. The Post() methods calls the InternalListener.Write() method to forward the extracted message to Covenant, which will handle everything that needs to happen when an implant returns data.</li><li>The Listener needs to craft a response to send to the implant. If there are any available tasks for the implant, this is where the Listener can inform the implant of these tasks. Listeners do not need to track available tasks, the InternalListener object again will handle this for us. Calling the InternalListener.Read() method will retrieve any data that is available for the implant.</li><li>Finally, the Listener needs to format this data into the format that the Profile requires. The HTTP Listener accomplishes this with the String.Format() method.</li></ol><p><strong>Front End Development</strong></p><p>In addition to the logic that powers the Listener, Covenant’s front-end should be modified so that the new Listener is easy to create and interact with.</p><p>Developers should follow the examples of the HttpListener and BridgeListener classes to get an understanding of the front-end code that needs to be added. Specifically, developers should add the listener to the list in the <a href="https://github.com/cobbr/Covenant/blob/master/Covenant/Views/Listener/Create.cshtml">Create.cshtml view</a>.</p><p>Once this is done correctly, your new Listener should appear in a new tab next to the HttpListener and BridgeListener:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W0uHlnyN_y3hlhKzMM-R-g.png" /><figcaption><strong>New Listener Tab</strong></figcaption></figure><h4>Implant-Side Development</h4><p>Secondly, a developer must write a new implant that utilizes the new communication protocol to receive new taskings. Developers can make use of the majority of the code from existing implants, but must replace the relevant code for an implant to utilize the new protocol.</p><p>To do so, a developer can create a new ImplantTemplate. It is relatively easy to create a new ImplantTemplate through the Covenant interface. Navigating to the “Templates” navigation page will display a table of the existing implants:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vKbbrSEspE6WktCbp9RA-Q.png" /><figcaption><strong>Templates Navigation Page</strong></figcaption></figure><p>The built-in templates are GruntHTTP and GruntSMB, which utilize the HTTP and SMB communication protocols respectively. When it comes to listeners, we are only concerned with <em>outbound</em> protocols (i.e. protocols that traverse the external edge of the network), not peer-to-peer protocols such as SMB.</p><p>To create a new ImplantTemplate, we can click the “Create” button underneath the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qzv2aXWIu3mOvIyThXdzSA.png" /><figcaption><strong>Create New Template</strong></figcaption></figure><p>Here, we can place the C# code of our new implant that utilizes our new communication protocol. We must specify the code for the stager as well as the full implant. Much of this code can be copied from existing implants, and we can simply replace the portion of the code that handles communication with the listener.</p><p>Once, we’ve created the new ImplantTemplate, we can see that it appears within the table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q1MZDojwk_BRhE03C_lmnw.png" /><figcaption><strong>New Template Created</strong></figcaption></figure><p>The benefit of creating a Listener is that you can provide users with an intuitive interface to provide options needed for the Listener to function and everything is tied into Covenant’s natural workflow. The drawback is the extra development work needed to edit Covenant’s backend and frontend codebase.</p><h3>Creating C2Bridges</h3><p>C2Bridges are a new feature introduced in Covenant v0.4. The C2Bridge feature is meant to allow a developer to quickly create new communication protocols without having to edit any Covenant code at all, and quickly make use of their creation within Covenant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L2Va3BlT9iedzwZxSaffOw.png" /><figcaption><strong>C2Bridge Architecture</strong></figcaption></figure><p>Again, just as with Listeners, a developer needs to handle both the implant-side of development as well as the listener-side.</p><h3>Listener-Side Development</h3><p>Covenant contains a built-in “Listener” called a BridgeListener that facilitates plugging a new protocol into the Covenant platform. A BridgeListener is a simple TCP listener that should be used as a means to transfer data between the new C2Bridge and Covenant.</p><p>Developers can use the new <a href="https://github.com/cobbr/C2Bridge">C2Bridge</a> project as a template for creating new C2Bridges. This is not a requirement, but the C2Bridge project provides helpful functionality to connect your new protocol to a BridgeListener without any additional work.</p><p>Within the C2Bridge project, there is an abstract C2Bridge class. A developer can inherit from this class and implement the needed functions to read and write from implants to the BridgeListener using the new chosen communication protocol.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a11eaf48ec7bdd0d271af1bdf00c837f/href">https://medium.com/media/a11eaf48ec7bdd0d271af1bdf00c837f/href</a></iframe><p>This abstract C2Bridge class is well-documented to make it as easy as possible for developers. The entire purpose of the C2Bridges project is to allow developers to focus on developing their new communication protocol, while focusing on Covenant integration as little as possible.</p><p>The C2Bridges project also provides an example TcpC2Bridge class that inherits from the C2Bridge class that demonstrates how to develop a C2Bridge. The TcpC2Bridge provides a new outbound communication protocol that utilizes TCP for C2. An outbound TCP C2 protocol probably has limited usefulness in a real offensive operation, but this is available primarily as an example of how to create a C2Bridge.</p><p>Examining the TcpC2Bridge shows how to construct a C2Bridge:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38cc0857844c6522a5b2b630f3b94418/href">https://medium.com/media/38cc0857844c6522a5b2b630f3b94418/href</a></iframe><p>In the RunAsync() function, we start our TcpListener and continually wait for new clients. For every client, we continually read data from the implant and write that data to Covenant using the WriteToConnector() helper function that handles this for us.</p><p>The OnReadBridge() function handles when Covenant is writing data back down to the implant. Whenever, we read data from the “bridge” (Covenant), this function gets called. When this happens, we determine which implant this data is for and write it down to the corresponding implant TcpClient.</p><p>To use this TcpC2Bridge within Covenant, we first need to create a BridgeListener within Covenant. To do so, we first navigate to the Listeners navigation page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aoBRz3_bUtKOVSJbFqa-aQ.png" /><figcaption><strong>Listeners Navigation Page</strong></figcaption></figure><p>We then click on the “Create” button and click on the BridgeListener tab at the top of the screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KUYCFmODIk9FXR8Zcc0CCA.png" /><figcaption><strong>Create a BridgeListener</strong></figcaption></figure><p>The following options will need to be configured when creating the BridgeListener:</p><ul><li><strong>Name</strong> — The Name of the listener that will be used throughout the interface. Pick something recognizable!</li><li><strong>BindAddress</strong> — The BindAddress is the local ip address that the listener will bind to. This can be helpful in cases where the Covenant host has multiple NICs. Usually, this value will be 0.0.0.0.</li><li><strong>BindPort</strong> — The BindPort is the local port that the listener will bind to. This is the port that the C2Bridge will connect to.</li><li><strong>ConnectPort</strong> — The ConnectPort is the <em>callback</em> port that Grunts will be directly connecting to. This is the port the C2Bridge should listen on. This may or may not be relevant depending upon the protocol used by the C2Bridge.</li><li><strong>ConnectAddress</strong> — The ConnectAddress is the <em>callback</em> address that Grunts will be directly connecting to. This should be the external address of the C2Bridge, or if you are using redirectors this should be the address that points to the external redirector.</li><li><strong>BridgeProfile</strong> — The BridgeProfile determines the behavior of Grunt and Listener communication. <strong>The profile must specify BridgeMessengerCode that is compatible with the C2Bridge you choose to use.</strong></li></ul><p>You’ll notice that a BridgeProfile is required to create a BridgeListener. A BridgeProfile is similar to the HttpProfile you may be familiar with already. It allows us to configure what our network traffic looks like on the wire, and specify where the data should be stored within the protocol.</p><h3>Implant-Side Development</h3><p>A BridgeProfile has one unique feature not found in the HttpProfile, it requires a BridgeMessengerCode property. This property allows us to specify the <em>implant code</em> used to communicate with our new C2Bridge. When we created the C2Bridge, we defined a “listener” that implants can communicate with for C2, but the implant must also know how to communicate over this new protocol.</p><p>Some C2 frameworks attempt to solve this problem with an intermediate agent that sits between the implant and the listener that translates messages to the new protocol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CFUWGy5aKHPRrXjlTqBnAg.png" /><figcaption><strong>Integrating New Protocols — Translation Agent Approach</strong></figcaption></figure><p>However, this solutions has its drawbacks. This requires us to run a secondary agent for each implant, and we aren’t able to utilize our new protocol between the implant and the translation agent.</p><p>Covenant solves this problem slightly differently. In Covenant, the new communication code gets embedded within the implant itself. This requires less overhead than the translation agent approach, and does not require an additional agent to be executed within the target network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q6pG3bVMWev5dMeRXYM9Jw.png" /><figcaption><strong>Integrating New Protocols — C2Bridge Approach</strong></figcaption></figure><p>This new communication code is what is specified in the BridgeMessengerCode property of the BridgeProfile. For example, the BridgeMessengerCode for the TcpBridgeProfile is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/801b40d7ba9a4eaed0f637beb2c229f4/href">https://medium.com/media/801b40d7ba9a4eaed0f637beb2c229f4/href</a></iframe><p>A BridgeProfile must include the unmodified IMessenger interface, as well as a BridgeMessenger class that inherits from this interface. The BridgeMessenger should implement all of the code to read and write data to and from the C2Bridge.</p><p>Once again, the TCP example here is meant to serve as a guide to developers wanting to develop their own protocol, not necessarily as something to use within an operation.</p><p>For more information, please reference the Covenant wiki pages for <a href="https://github.com/cobbr/Covenant/wiki/C2Bridges">C2Bridges</a> and <a href="https://github.com/cobbr/Covenant/wiki/Bridge-Listeners">BridgeListeners</a>.</p><h3>Conclusion</h3><p>As an operator, it’s easy to fall into a trap of always defaulting to a standard polling HTTP protocol. There’s nothing wrong with using an HTTP communication protocol, it can be highly effective, but there are many other options out there to consider.</p><p>Mixing up the protocols you use as an operator could be eye-opening and beneficial to your blue team. While Covenant does not provide many communication protocols out of the box, it provides the tools that enable the integration of any communication protocol you could want to use.</p><p>For example, you could implement a DNS C2Bridge, C2Bridges that integrate with 3rd party websites such as Twitter, Github, Slack, and Dropbox, or get more creative with Amazon SQS, Amazon S3 buckets, or Microsoft Outlook. The only limit is your imagination and a bit of development time!</p><h3>Additional Resources</h3><ul><li><strong>Flying a False Flag: Advanced C2, Trust Conflicts, and Domain Takeover — Nick Landers</strong> — I would highly recommend <a href="https://www.youtube.com/watch?v=2BEwqbCbQuM">this 2019 Blackhat talk</a> to anyone looking for some creative ideas for new communication protocols.</li><li><strong>C3 (Custom Command and Control)</strong> — <a href="https://github.com/FSecureLABS/C3">C3</a> is a platform-agnostic toolset that attempts to solve a similar problem.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=895587e7f325" width="1" height="1" alt=""><hr><p><a href="https://medium.com/specter-ops-posts/covenant-developing-custom-c2-communication-protocols-895587e7f325">Covenant: Developing Custom C2 Communication Protocols</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[Covenant: The Usability Update]]></title>
            <link>https://medium.com/specter-ops-posts/covenant-the-usability-update-9a7a596a4772?source=rss-d248a36145f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a7a596a4772</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[infosec]]></category>
            <dc:creator><![CDATA[Ryan Cobb]]></dc:creator>
            <pubDate>Fri, 02 Aug 2019 15:39:04 GMT</pubDate>
            <atom:updated>2019-08-02T15:39:04.611Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yNOShb9ZeNRpJAvR9Gpq3w.png" /></figure><h3>Intro</h3><p><a href="https://github.com/cobbr/Covenant">Covenant v0.3</a> is being released today and includes a brand new web-based interface. In this post, we will discuss Covenant’s new interface and other important usability features.</p><p>Covenant has been under development for over a year, and the <a href="https://posts.specterops.io/entering-a-covenant-net-command-and-control-e11038bcf462">initial public release</a> was over seven months ago. Development has been primarily focused on <a href="https://posts.specterops.io/designing-peer-to-peer-command-and-control-ad2c61740456">new features and functionality</a>. Until now, we’ve chosen to prioritize providing the features that an operator needs to succeed in modern red team engagements. But usability has not been a primary focus of the tool since its release. As it turns out, usability and documentation are actually <em>very</em> important features.</p><h3>Usability</h3><p>If a feature is not intuitive or well-documented, the feature will likely not be used. Usability is particularly important for a collaborative command and control framework. It should be assumed that multiple operators are working together simultaneously and that not all operators are equally as familiar with the tool. If only the tool developer or team lead can decipher how to use the tool effectively, then the tool itself is not effective, no matter how many bells and whistles are in the feature list.</p><p>For Covenant, <strong>usability will now be a primary focus</strong>. This doesn’t mean that every feature will immediately be intuitive, but that usability is now a primary focus of development. A feature will not be considered complete unless it is intuitive and well-documented.</p><h3>New Web-Based Interface</h3><p>The first step towards a more usable and intuitive Covenant is a new web-based interface. Covenant has been almost totally transformed by the new interface, and is much more intuitive overall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0CFULZ24lb2BVbuqaWVvg.png" /><figcaption><strong>Covenant Dashboard</strong></figcaption></figure><p>This post will showcase several of the most important upgrades in the new release and highlight some of the key features that have been enabled through the new web interface, primarily focusing on the usability benefits that the new features offer.</p><p>The interface is primarily driven through the sidebar, which includes the following navigation pages:</p><ul><li><strong>Dashboard</strong> — The home view and the first thing you see when you login. You can get a quick glimpse of the active grunts you have obtained, the listeners that are currently active, and a few of the most recent taskings that have been assigned to grunts.</li><li><strong>Listeners</strong> — Provides an interface for managing listeners and listener profiles.</li><li><strong>Launchers</strong> — Provides an interface for creating, hosting, and downloading launchers to use in launching new grunts.</li><li><strong>Grunts</strong> — Displays a table for viewing all active and inactive grunts, as well as interacting with Grunts and assigning them new tasks.</li><li><strong>Tasks</strong> — Provides an interface for editing and building new Tasks.</li><li><strong>Taskings</strong> — Displays a table for viewing all taskings that have been assigned to grunts.</li><li><strong>Graph</strong> — Provides a view for data that has been collected from grunts during operation, such as credentials, indicators, and downloaded files.</li><li><strong>Data</strong> — The Data page provides a view for data that has been collected from grunts during operation, such as credentials, indicators, and downloaded files.</li><li><strong>Users</strong> — Provides an interface for user management and creation.</li></ul><p>All of these components have been improved in the new interface, but this post will focus on a few of the primary areas of improvement:</p><ul><li>User Registration and Management</li><li>Listener and Profile Configuration</li><li>Grunt Interaction</li><li>Building Custom Tasks</li></ul><h3>User Registration and Management</h3><p>User registration has been streamlined in the new version and the web interface makes it much easier to create new users and modify existing users.</p><p>In previous versions, Covenant required an initial username and password to be passed on the command-line to kick things off. Now Covenant can be started without any parameters at all, and will allow you to register an initial user through the web interface. Once a user has been created, this option will no longer be available for security reasons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*1Bb0fU-X8FOMXIdLzV-ujw.png" /><figcaption><strong>Initial User Registration</strong></figcaption></figure><p>User management is also much improved by utilizing the new interface, and this update makes it much easier to set up users for collaboration. Registered users can be viewed and managed by navigating to the Users page on the sidebar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bZQZN-HWwyNqg9Ot8qPOSQ.png" /><figcaption><strong>Users Table</strong></figcaption></figure><p><a href="https://github.com/cobbr/Covenant/wiki/User-Management">User registration and management</a> is documented more thoroughly in Covenant’s new <a href="https://github.com/cobbr/Covenant/wiki/Home">Wiki</a>.</p><h3>Listeners and Profiles</h3><p>Listener creation and management is made much easier through the web interface and includes an entirely new profile building feature.</p><p>To create a new listener, navigate to the Listeners page on the sidebar, and click the “Create” button to start configuring the new listener.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTLWiibCSPBgpTqNEhKO3Q.png" /><figcaption><strong>Create HTTP Listener</strong></figcaption></figure><p>Configure the new listener as desired, and click the “Create” button again, and your new listener will be started. We highly recommend configuring custom profiles for your listener or modifying existing profiles, because Covenant’s default profiles could easily be signatured by defensive products.</p><p>In previous versions of Covenant, profiles needed to be developed prior to starting Covenant, but now profiles can easily be modified and created through the web interface.</p><p>To edit a pre-existing profile, navigate to the Listeners page on the sidebar, select the Profiles tab, and click on a pre-existing profile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3OPrlbcwi9VaPOY-mc5CLQ.png" /><figcaption><strong>Listener Profiles Table</strong></figcaption></figure><p>The profile editing page allows you to change any aspect of the profile, including request and response headers, callback urls, and request and response formats. The user must be an Administrator to edit the HttpMessageTransform property for security purposes, and profiles applied to active listeners cannot be edited, though we would like to enable that feature sometime in the future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*I5EKHNVwkJ48RDpqeedngw.png" /><figcaption><strong>Edit HTTP Listener Profile</strong></figcaption></figure><p>The ability to create and edit profiles through the interface is one of the more important new features, and should make it much easier to start customizing the way your network traffic communicates.</p><p><a href="https://github.com/cobbr/Covenant/wiki/Listener-Profiles">Listener profile management</a> and <a href="https://github.com/cobbr/Covenant/wiki/Listeners">listener management</a> is documented more thoroughly in Covenant’s new <a href="https://github.com/cobbr/Covenant/wiki/Home">Wiki</a>.</p><h3>Grunt Interaction</h3><p>Grunt interaction is probably the most essential aspect of the Covenant project. Most of an operation will be conducted from this view, and operators will spend most of their time interacting with grunts. For that reason, grunt interaction was a primary focus of the new interface, and needed to be as usable and intuitive as possible. The grunt interaction page includes realtime command updates via <a href="https://docs.microsoft.com/en-us/aspnet/signalr/overview/getting-started/introduction-to-signalr">SignalR</a>, tab-completable command suggestions via <a href="https://twitter.github.io/typeahead.js/">Twitter typeahead</a>, and multiple methods of interacting with grunts.</p><p>Navigating to the Grunts page in the sidebar will give you a list of active and inactive grunts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2_bwUbLBeHbEF1En6X2mcw.png" /><figcaption><strong>Grunts Table</strong></figcaption></figure><p>Selecting an active grunt brings you to the grunt interaction page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_8HKtOzwPR0DVEHG3AgtA.png" /><figcaption><strong>Grunt Information</strong></figcaption></figure><p>The first thing you see on the interaction page is the Info tab, which will display all the info about the selected Grunt. There are several fields that are editable, such as Delay, JitterPercent, ConnectAttempts, and Note properties. Editing these values will change the value for the Grunt and will also cause a task to be applied to the Grunt to change this value on the implant itself.</p><p>Navigating to the Interact tab brings you to a command-line like interface. Operators will likely spend most of their time in this interface, which makes the usability of this view particularly important. The new command interface is an upgrade over previous iterations and much more intuitive. The interface is scrollable and vertically resizable, command suggestions are tab-completable as you type, and you will see updates in realtime so that you can see what other operators are doing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3HhpaJLlRy5CVAiW5gEvfg.png" /><figcaption><strong>Grunt Interaction</strong></figcaption></figure><p>Covenant has a new command-line parser that makes specifying complicated parameters on the command-line easier. However, if a command is too confusing to specify on the command-line, it can be useful to be more specific.</p><p>Navigating to the Task tab reveals a dropdown dialog where you can select a specific task that you would like to execute and allows you to fill parameters into the dialog boxes to ensure that parsing will not get in your way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*skpHpPlsCzM313zjeDxo9w.png" /><figcaption><strong>Grunt Task Tab</strong></figcaption></figure><p>The Taskings tab shows the grunt’s command history in a searchable table view, which allows you to click on labels to get more detailed information for any specific tasking, task, or user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X-z0LUlx9lw-KTpYTawczw.png" /><figcaption><strong>Grunt Taskings Tab</strong></figcaption></figure><p><a href="https://github.com/cobbr/Covenant/wiki/Grunt-Interaction">Grunt interaction</a> is documented more thoroughly in Covenant’s new <a href="https://github.com/cobbr/Covenant/wiki/Home">Wiki</a>.</p><h3>Building Custom Tasks</h3><p>Building custom tasks has been another core focus for the new interface. In previous versions of Covenant, implementing custom tasks was not a simple process, but now operators can add new tasks or edit existing tasks at any time during the operation and begin using them immediately.</p><p>Covenant provides a rich object model for building new tasks. Navigating to the Tasks page on the sidebar reveals tables that show all Tasks, ReferenceSourceLibraries, ReferenceAssemblies, and EmbeddedResources.</p><p>A user can use any of these existing components to help building new tasks. For instance when creating a new task, a user could add the “SharpSploit” ReferenceSourceLibrary and begin using any SharpSploit namespace to help complete the given task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9hoU7tNtnjSE7GIDbhLYHQ.png" /><figcaption><strong>Tasks Table</strong></figcaption></figure><p>To create a new Task, click the Create button at the bottom of the Tasks tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P0KsTQKh95D4UJBbfGNFxA.png" /><figcaption><strong>Create New Task</strong></figcaption></figure><p>Then you can configure the Task as needed, click the Create button, and the Task should now be usable within any of your grunts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0P23hECJexs611rrmoxVxw.png" /><figcaption><strong>Using New Task</strong></figcaption></figure><p><a href="https://github.com/cobbr/Covenant/wiki/Building-Tasks">Building tasks</a> is documented more thoroughly in Covenant’s new <a href="https://github.com/cobbr/Covenant/wiki/Home">Wiki</a>.</p><h3>Goodbye for now, Elite</h3><p>The new interface also means that we have to say goodbye, at least for now, to Covenant’s client-side interface, <a href="https://github.com/cobbr/Elite">Elite</a>. It’s never fun to throw away large chunks of hard-earned, functioning code, but in making a move towards usability, we determined that a command-line interface was too limiting for our current purposes.</p><p>However, I do think there is value in having a command-line client and Elite may make a return at some point in the future. But for now, we’ve chosen to focus our development efforts on Covenant’s new interface.</p><p>Elite will continue to reside at <a href="https://github.com/cobbr/Elite">https://github.com/cobbr/Elite</a> for historical purposes, in case someone wants to use an older version of Covenant for some reason. Eventually the repository may be brought up to date in later versions of Covenant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*rTvrH8OmfPbYP707_sGbag.png" /><figcaption><strong>Moving on From Elite</strong></figcaption></figure><h3>Documentation</h3><p>In addition to the new interface, Covenant was in need of thorough documentation.</p><p>Covenant has a new, revamped <a href="https://github.com/cobbr/Covenant/wiki">Wiki</a> that documents Covenant’s features, many of which were not detailed in this blog post. The Wiki currently documents the majority of Covenant’s core features and will continue to be updated as the project evolves. Additionally, we will be recording a video walkthrough series that demonstrates Covenant’s features in the near future.</p><h3>Future Developments</h3><p>We are excited to be releasing Covenant’s new interface and are happy with its current state, but we are always thinking about the future additions and improvements we could make. In the near-term future, we will be continuing to polish Covenant’s documentation, interface, and usability features. We are hoping that user feedback will help us fill in the gaps and really get the interface right before moving on to new features.</p><p>We do have a few ideas about future UI improvement, such as improving the Graph view, possibly introducing Microsoft’s new <a href="https://docs.microsoft.com/en-us/aspnet/core/blazor/index?view=aspnetcore-3.0">Blazor</a> single-page application framework, and continuing to enhance the implementation of Microsoft’s <a href="https://docs.microsoft.com/en-us/aspnet/signalr/overview/getting-started/introduction-to-signalr">SignalR</a> framework.</p><p>But we are hoping that most of the future UI improvements come from user feedback! If you are a regular Covenant user or haven’t tried out Covenant in a while, we hope you will try out the new interface and let us know what you think. As always, feel free to join the discussion in the #covenant channel in the <a href="https://bloodhoundgang.herokuapp.com/">BloodHound Gang Slack</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a7a596a4772" width="1" height="1" alt=""><hr><p><a href="https://medium.com/specter-ops-posts/covenant-the-usability-update-9a7a596a4772">Covenant: The Usability Update</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[Designing Peer-To-Peer Command and Control]]></title>
            <link>https://medium.com/specter-ops-posts/designing-peer-to-peer-command-and-control-ad2c61740456?source=rss-d248a36145f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad2c61740456</guid>
            <category><![CDATA[peer-to-peer]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[command-and-control]]></category>
            <dc:creator><![CDATA[Ryan Cobb]]></dc:creator>
            <pubDate>Wed, 01 May 2019 14:50:34 GMT</pubDate>
            <atom:updated>2019-05-01T14:50:34.675Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post we will discuss the design and implementation of peer-to-peer command and control protocols in general, as well as the concrete example of the peer-to-peer design implemented in <a href="https://github.com/cobbr/Covenant">Covenant</a>, an open-source command and control framework, as of v0.2 (released today), which I will refer to often.</p><h3>Command and Control</h3><p>To start at a high level, Command and Control (C2) refers to the process of establishing and maintaining control of implants on a single or on a set of targeted victim machines. A C2 framework typically provides the ability to communicate with implants via a communication protocol, issue commands to the victim systems, and receive the output of these commands back on the C2 server, to which an attacker generally has physical or direct virtual access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X6sY_GU40bUgPOL61kcOxQ.png" /><figcaption>Standard Command and Control</figcaption></figure><h3>P2P Command and Control</h3><p>Command and Control (C2) protocols rely upon a synchronous or asynchronous communication channel between each controlled implant and the C2 server. Peer-To-Peer (p2p) C2 protocols allow for a single implant to maintain the communication channel back to the C2 server, while all other implants communicate over a “mesh” network that funnels communication through the single egress implant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*53V57zDZAbPOllqpginKhA.png" /><figcaption>Peer-To-Peer Command and Control</figcaption></figure><h3>Advantages</h3><p>There are many advantages to this approach. One, is that the reduced egress communication channels provides less potential indicators to defenders that may be attempting to identify the malicious traffic. Defenders tend to prioritize traffic inspection on the edge of the organization’s network over internal traffic. With a sufficiently large set of implants, an increased amount of egress communication channels may tip off a defender to your activity.</p><p>Another advantage to this approach is that of access. Well-protected networks may treat certain classes of traffic differently internally than they do at the edge of the network. A common example of this is an organization that allows HTTP traffic outbound over the edge of their network to allow employees to browse the internet but may restrict HTTP traffic originating from servers or other high-value network subnets. This type of restriction may prevent common C2 frameworks that rely on each implant to establish an egress communication channel from maintaining access to these restricted servers or high-value network subnets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QX0s0cuAg0tkOClXg80thA.png" /><figcaption>Restricted Protocol</figcaption></figure><p>A C2 framework can utilize a different type of communication channel for egress traffic than for the mesh network to solve this problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AbbgpkxkqwasSadnoNaSTQ.png" /><figcaption>Multi-Channel P2P Protocol</figcaption></figure><p>We often can’t be sure of the protocols that will assure our success before landing the first implant on the target network and putting the protocols to the test. Unfortunately, this is often too late to implement new protocols into a C2 framework, unless we have a significant amount of time and resources. As C2 framework developers, the best we can do is to implement as many protocols as we can in preparation and/or make educated guesses ahead of time at the types of protocols that will allow us to succeed.</p><h3>Selecting Protocols</h3><p>At SpecterOps, we often find that many of the same protocols will provide success on the majority of the networks we find ourselves assessing. There are certainly exceptions to this rule, but we can be reasonably certain that a set of protocols have legitimate business use that require them to be allowed. For instance, it is a reasonable assertion that HTTP will be allowed outbound over the edge of the network if an organization expects employees to be able to browse the internet. This is one of several reasons that HTTP is a common egress communication protocol for C2 frameworks. However, as mentioned earlier, it is common that HTTP is not permitted from high-value areas of the network.</p><p>For the secondary, internal communication protocol, we must rely on the technology of the victim system for both ends of the communication channel, which influences our decision on what protocol to select. Ideally, we’d like a protocol that blends in with the normal traffic of the network and is simple to implement in our implant.</p><p>At SpecterOps, we often find that organizations largely rely on a Windows stack for business operations, and a very common protocol required internally for Windows systems is SMB. <a href="https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wpo/4de75e21-36fd-440a-859b-75accc74487c">Named pipes</a> are a native Windows technology that allows for inter-process communication across remote systems over the SMB access protocol and is fairly simple to implement into a Windows implant.</p><p>For these reasons, Covenant utilizes HTTP as the egress protocol and SMB named pipes for the mesh protocol, which is a common set of protocols for this type of behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NGLIYlj997oRpHIqpk9gLA.png" /><figcaption>Using HTTP and SMB Protocols</figcaption></figure><p>However, there are many different protocols that could be used for peer-to-peer protocol. For a successful peer-to-peer protocol, we just need a means to read and write data between two systems. There are many inter-process communication options on a primarily Windows network, including <a href="https://github.com/PowerShellMafia/PowerSploit/blob/master/CodeExecution/Invoke-WmiCommand.ps1">WMI</a>, <a href="https://docs.microsoft.com/en-us/windows/desktop/ipc/mailslots">mailslots</a>, <a href="https://www.harmj0y.net/blog/powershell/command-and-control-using-active-directory/">Active Directory</a>, or even just raw TCP or UDP sockets. For now, however, we will stick to the SMB protocol via named pipes.</p><h3>Extending the Graph</h3><p>Now that we have defined the protocols we will be using, we’d like to expand the p2p mesh, or graph, beyond a single “hop”. Since we have a protocol that is capable of connecting compromised endpoints, we can extend this behavior to a full p2p mesh that hops between several nested, compromised endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*PFWEmzxsW7KxrtQMo6w2ZQ.png" /><figcaption>Extending the Graph</figcaption></figure><p>These connected endpoints form a <a href="https://en.wikipedia.org/wiki/Directed_acyclic_graph">directed acyclic graph</a> (DAG) of compromised endpoints. With the added complexity of these communication channels, implants now must track connected “child” edges as well as have the knowledge of which edge eventually leads to the C2 server. Once again, attackers must think in graphs.</p><p>You could also, theoretically, create a directed, cyclic graph for your C2. Meaning that implant messages could route back to a node it has already traveled through (i.e. A-&gt;B-&gt;G-&gt;A). I can’t think of many reasons why anyone would want to do so, and it would increase the complexity of the implant, so I mostly ignore this option and refer to the graph as a DAG for the remainder of the post.</p><h3>Implementation</h3><p>There may be multiple ways to accomplish these objectives, so many of these implementation details will be specific to Covenant, but I would guess that many of the methods are utilized in many different frameworks. In Covenant, each implant (or “Grunt”) is only responsible for knowing where each immediate edge leads and which edge eventually leads to the C2 server. A Grunt is not responsible for knowing the entire path to the server or the entire path to a nested child Grunt.</p><p>The graph structure is maintained by Covenant itself, and it must use this graph to craft messages that all intermediate Grunts will be able to interpret which direction to send the message next along the path within the graph. Covenant messages sent across the wire to the egress Grunt are obfuscated and stuffed into HTTP messages, but eventually these messages translate into a GruntEncryptedMessage JSON structure that looks something like this:</p><pre>{<br>    &quot;GUID&quot; : &quot;3630b87066&quot;,<br>    &quot;Type&quot; : 1,<br>    &quot;Meta&quot; : &quot;&quot;,<br>    &quot;IV&quot; : &quot;srwjK0WYY/XvFBPXGD7MOg==&quot;,<br>    &quot;EncryptedMessage&quot; : &quot;bU86lKwVJn1sb5m7U1Kekr3qg2KjKyNZeOP1rVoshjGpVK5LURcfYN6sWWGs+20NJUfhz7Jj6o7geAymVwJknRV2s4+Y8uDnRndGxZZKCjiiBGVWMVCPWewRzA93U+SLM55hqdmuLWLR2SPjxGzR5A==&quot;,<br>    &quot;HMAC&quot; : &quot;n+whkeAvDV+RcLPvazmkakrX8oPwBCCSqRQ8Pte9Ayo=&quot;<br>}</pre><p>A Grunt receives this structure and somehow needs to determine which direction to send the message. As an example, let’s label all of our Grunts with simpler names and walk through the process step-by-step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WK2CYSqKvGwrsT8DTowVHg.png" /><figcaption>Delivering a Message</figcaption></figure><p>The C2 server delivers a GruntEncryptedMessage, referred to in the diagram as G(message), to the <strong>A</strong> egress Grunt that has been crafted to be delivered to the <strong>G</strong> connected grunt. The GruntEncryptedMessage may look like this:</p><pre>{<br>    &quot;GUID&quot; : &quot;G&quot;,<br>    &quot;Type&quot; : 1,<br>    &quot;Meta&quot; : &quot;&quot;,<br>    &quot;IV&quot; : &quot;srwjK0WYY/XvFBPXGD7MOg==&quot;,<br>    &quot;EncryptedMessage&quot; : &quot;bU86lKwVJn1sb5m7U1Kekr3qg2KjKyNZeOP1rVoshjGpVK5LURcfYN6sWWGs+20NJUfhz7Jj6o7geAymVwJknRV2s4+Y8uDnRndGxZZKCjiiBGVWMVCPWewRzA93U+SLM55hqdmuLWLR2SPjxGzR5A==&quot;,<br>    &quot;HMAC&quot; : &quot;n+whkeAvDV+RcLPvazmkakrX8oPwBCCSqRQ8Pte9Ayo=&quot;<br>}</pre><p>The <strong>A</strong> Grunt has no knowledge of the key needed to decrypt this message and no knowledge of how to route this message to Grunt <strong>G</strong>. What could be the solution to this problem?</p><h3>Path Method</h3><p>One option could be to include the entire path as a new field within the GruntEncryptedMessage structure, like the following:</p><pre>{<br>    &quot;GUID&quot; : &quot;G&quot;,<br>    &quot;Path&quot; : [&quot;A&quot;, &quot;B&quot;, &quot;G&quot;]<br>    &quot;Type&quot; : 1,<br>    &quot;Meta&quot; : &quot;&quot;,<br>    &quot;IV&quot; : &quot;srwjK0WYY/XvFBPXGD7MOg==&quot;,<br>    &quot;EncryptedMessage&quot; : &quot;bU86lKwVJn1sb5m7U1Kekr3qg2KjKyNZeOP1rVoshjGpVK5LURcfYN6sWWGs+20NJUfhz7Jj6o7geAymVwJknRV2s4+Y8uDnRndGxZZKCjiiBGVWMVCPWewRzA93U+SLM55hqdmuLWLR2SPjxGzR5A==&quot;,<br>    &quot;HMAC&quot; : &quot;n+whkeAvDV+RcLPvazmkakrX8oPwBCCSqRQ8Pte9Ayo=&quot;<br>}</pre><p>Grunt <strong>A</strong> would inspect this message, would see that Grunt <strong>B</strong> is the next Grunt along the path, and has knowledge of how to route to Grunt <strong>B</strong>, given that it is connected with an immediate edge in the Graph. Grunt <strong>B </strong>would perform a similar operation and pass the message along to Grunt <strong>G</strong>, which is able to decrypt and interpret the message from the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Az6tcaZh5cV08Nkb5QbscQ.png" /><figcaption>Routing a Message</figcaption></figure><h3>Limitations</h3><p>However, this method suffers from a couple of unfortunate properties. First, this violates our premise that a Grunt should only know about Grunts that are connected through immediate edges. By viewing a single message, a Grunt gains knowledge of an entire path through the graph. Similarly, defenders that are able to intercept or otherwise obtain access to this GruntEncryptedMessage gain intimate knowledge of the p2p graph and may be able to discover large parts of your implant mesh that is unrelated to the message you are actually trying to deliver. Even worse, this portion of the message is <strong><em>unencrypted</em></strong>. All of the hard-earned cryptographic properties we obtain through the use of an encrypted key exchange protocol are wasted on this plaintext path, making it easier for defenders to identify your activity throughout the network. While these Grunt labels might not directly correlate to an internal hostname, it still gives a defender unnecessary information about the extent of your operation.</p><h3>Recursive Method</h3><p>Covenant avoids this problem by using a recursive GruntEncryptedMessage structure. Instead of placing the entire path as a plaintext field within the message, the path is recursively encrypted. For instance, we take the final message that we would like to deliver to Grunt <strong>G</strong>:</p><pre>{<br>    &quot;GUID&quot; : &quot;G&quot;,<br>    &quot;Type&quot; : 1,<br>    &quot;Meta&quot; : &quot;&quot;,<br>    &quot;IV&quot; : &quot;srwjK0WYY/XvFBPXGD7MOg==&quot;,<br>    &quot;EncryptedMessage&quot; : &quot;bU86lKwVJn1sb5m7U1Kekr3qg2KjKyNZeOP1rVoshjGpVK5LURcfYN6sWWGs+20NJUfhz7Jj6o7geAymVwJknRV2s4+Y8uDnRndGxZZKCjiiBGVWMVCPWewRzA93U+SLM55hqdmuLWLR2SPjxGzR5A==&quot;,<br>    &quot;HMAC&quot; : &quot;n+whkeAvDV+RcLPvazmkakrX8oPwBCCSqRQ8Pte9Ayo=&quot;<br>}</pre><p>We treat this entire JSON structure as a message and encrypt this using the symmetric key for Grunt <strong>B</strong>, and stuff the resulting value into the EncryptedMessage field of a message crafted for Grunt <strong>B</strong>:</p><pre>{<br>    &quot;GUID&quot; : &quot;B&quot;,<br>    &quot;Type&quot; : 0,<br>    &quot;Meta&quot; : &quot;&quot;,<br>    &quot;IV&quot; : &quot;jKbU80WYY/XvFBPwVJnPWd==&quot;,<br>    &quot;EncryptedMessage&quot; : &quot;kr3qg2KjKbU86lKwVJn1sb5m7U1Kekr3qg2KjKyNZeOP1rVoshjGpVK5LURcfYN6sWWGs+20NJUfhz7Jj6o7geAymVwJknRV2s4+Y8uDnRnd6lKwVJnGxZZKCjiiBGVWMVC6lKwVJnPWewRzA93U+SLm7U1Kekr3M55hqdmuLWL20NJUfhz7=&quot;,<br>    &quot;HMAC&quot; : &quot;KwVJnPAvDV+RcLPva93U+krX8oPwBCCSqRQ8PtLPvaz=&quot;<br>}</pre><p>And we do this once more, by taking this entire JSON structure, encrypting this using the symmetric key for Grunt <strong>A</strong>, and stuffing the resulting value into the EncryptedMessage field of a message crafted for Grunt <strong>A</strong>:</p><pre>{<br>    &quot;GUID&quot; : &quot;A&quot;,<br>    &quot;Type&quot; : 0,<br>    &quot;Meta&quot; : &quot;&quot;,<br>    &quot;IV&quot; : &quot;geAymV0WYY/XvFBqg2KjKyNZ==&quot;,<br>    &quot;EncryptedMessage&quot; : &quot;6lKwVJn1sb5m7U1Kekr3qg2KjKyNZeOP1rVoshAymVwJknRV2sjGpVK5LURcKbU86lKwVJn1sb5m7U1Kekr3qg2KjKyNZeOP1rVoshjGpVK5LURcfYN6sWWGs+20NJUfhz7Jj6o7geAymVwJknRV2s4+Y8uDnRnd6lKwVJnGxZZKCjiiBGVWMVCb5m7U1Kekr36lKwVJnPWewRzA93U+SLm7U1Kekrb5m7U1Kekr3=&quot;,<br>    &quot;HMAC&quot; : &quot;Rnd6lKwVJV+RcLPva93U+krX8oPwBCCSqkr3qg2KjKy=&quot;<br>}</pre><p>With this method, a Grunt decrypts the EncryptedMessage field within the GruntEncryptedMessage and checks the GUID field of the decrypted structure to determine which Grunt to route the message through next. Importantly, the Type field is set to 0 for the “Routing” messages and set to 1 for “Delivery” messages. This switch indicates to the Grunt whether the message is intended for it or if the message should continue to be routed along the path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OiS6-JSDZ3UDej4oIFzcEA.png" /><figcaption>Routing a Message</figcaption></figure><p>This recursive method eliminates the previous issue of revealing the entire path to a man-in-the-middle observer. We utilize our existing per-Grunt symmetric keys, negotiated through an encrypted key exchange, to cryptographically seal the path to observers and Grunts alike. The cost is that the final GruntEncryptedMessage will be larger in size, due to the recursive encryption operations. (<strong>Note</strong>: Grunts should also not be labeled sequentially as shown in this example, as this could also leak the extent to which the network has been compromised. Fortunately, this is just an example and Covenant does not use this behavior in practice.)</p><h3>Named Pipes for C2</h3><p>So far, we’ve covered the routing implementation in detail, but not the implementation details of the access protocol itself. While often referred to as “SMB named pipes”, what we really are doing is accessing named pipes remotely over the SMB access protocol. A named pipe connection consists of a NamedPipeServer and a NamedPipeClient. In .NET, these can be accessed using <a href="https://docs.microsoft.com/en-us/dotnet/api/system.io.pipes.namedpipeserverstream?view=netframework-3.5">NamedPipeServerStream</a> and <a href="https://docs.microsoft.com/en-us/dotnet/api/system.io.pipes.namedpipeclientstream?view=netframework-3.5">NamedPipeClientStream</a> objects.</p><p>Every peer Grunt (i.e. all Grunts aside from the egress Grunt) will have a single NamedPipeServer, and a NamedPipeClient for each immediately connected child Grunt. A NamedPipeServer listens on a pipe name, waiting for connecting clients. A NamedPipeClient connects to a server given the hostname and pipe name, which creates the named pipe. Each end of the named pipe has the ability to read and write from the opposite end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*71Z2CBMfBV5UPO9FgMvCCQ.png" /><figcaption>Named Pipe Connection</figcaption></figure><p>This is sometimes referred to as a “bind” connection, meaning that the NamedPipeServer is started on the child Grunt and the parent Grunt creates the connection with a NamedPipeClient. It is also possible to create a “reverse” connection, meaning that the NamedPipeServer is started on the parent Grunt and the child Grunt creates the connection with a NamedPipeClient.</p><p>Either way, the outcome is that we have a named pipe connection with the ability to read and write from either end. However, Covenant currently implements only “bind” named pipe connections.</p><p>When opening a new named pipe, you have a few options to consider:</p><ul><li><strong>PipeName</strong> — Both ends of the pipe must agree on a pipe name. By default, Grunt uses gruntsvc as the pipe name, not exactly inconspicuous. It is highly recommended to customize this name, and Covenant even allows you to use a custom pipe name per NamedPipeServer.</li><li><strong>Direction</strong> (In, Out, InOut) - Named pipe streams can be read-only, write-only, or read-write. For p2p communication, we are always going to need to use read-write or InOut.</li><li><strong>TransmissionMode</strong> (Byte or Message) - Named pipes can communicate as a stream of bytes or as serialized “messages”. Either could work here, but for a number of reasons Covenant uses Byte mode and must serialize messages on its own. The reading end of the pipe reads bytes as a continuous stream and must have a means of determining once it has reached the end of a message. There are two popular approaches to this sort of problem: a delimiting character (i.e. a null terminated string) or prepending the length of the message and reading bytes up to this length. Covenant chooses the latter approach, to avoid limiting the character set available in messages.</li><li><strong>SecurityDescriptor</strong> — Named pipes are <a href="https://docs.microsoft.com/en-us/windows/desktop/secauthz/securable-objects">securable objects</a>, meaning that they are protected by one or more security descriptors. We could apply security descriptors that only allow the current users on HOST01 and HOST02 access to the pipe but implants often need to perform some atypical credential management. Token manipulation, for instance, could render our named pipe inaccessible to the new user and orphan a section of our graph. For this reason, Covenant applies a single security descriptor that allows FullControl to the Everyone group, to ensure we don’t inadvertently make the pipe inaccessible.</li></ul><p>An important note when using named pipes within Covenant, is that two Grunt implants cannot share the same pipe name <em>on the same host</em>. However, a new Grunt implant can be started on the same host with a <em>different pipe name</em>.</p><h3>Detection</h3><p>Detection of general peer-to-peer malicious traffic and malicious named pipes can be difficult, but not impossible. Generally, it will be easier to detect malicious behaviors of the implant itself rather than the peer-to-peer protocol.</p><p>However, there are indicators that could be detected. Many of these detections require baselining certain metrics and comparing new behaviors to this baseline to give additional insight into the abnormality of the event occurring.</p><h3>Host Detections</h3><ul><li><strong>Known Malicious Named Pipe Names</strong> — This detection is the most obvious, low-hanging fruit. C2 frameworks may utilize default named pipe names that could be detected. For instance, Covenant uses gruntsvc as the default pipe name and Cobalt Strike uses msagent as the default pipe name. These pipe names can be easily changed within both frameworks, but it’s still useful to take advantage of this low-hanging fruit to detect attackers that do not change the defaults.</li></ul><p>Sysmon can be used to collect information about named pipes. <a href="https://github.com/Cyb3rWard0g/OSSEM/blob/master/data_dictionaries/windows/sysmon/event-17.md">Sysmon Event ID 17</a> is generated when a named pipe is created. The PipeName field can be inspected against a list of known malicious pipe names.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*2GYuMJ7uF7yC53D9VZRaMQ.png" /><figcaption>Sysmon Event ID 17 Gruntsvc</figcaption></figure><ul><li><strong>Abnormal Process to Named Pipe Relationships</strong> — To properly utilize this detection, an organization should have a way of collecting and baselining process to named pipe relationships. Sysmon Event ID 17, again, has all the needed information for this detection. These events should be collected over a period of time, and new events can be compared to his baseline.</li></ul><p>For instance, Chrome has a common set of named pipes that it communicates with that are typically of the form mojo.#####.#####.################## where # is a number. For instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*nb4MHVv5MRgSBQ7oyl2_Rg.png" /><figcaption>Sysmon Event ID 17 Chrome</figcaption></figure><p>If the process of baselining process to named pipe relationships reveals that C:\Program Files (x86)\Google\Chrome\Application\chrome.exe never, or hardly ever, creates named pipes that are <em>not</em> of this mojo.####.#####.#################### form, then a new event that shows C:\Program Files (x86)\Google\Chrome\Application\chrome.exe creating a new named pipe that does not match this form, say pipe123, is anomalous:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*j7VSC8O8HffqVy_2qqYIjg.png" /><figcaption>Sysmon Event ID 17 Chrome</figcaption></figure><p>An anomalous named pipe such as this one may be worth investigating. Ideally, this detection works in conjunction with other host indicators to add additional context to a potential compromise.</p><ul><li><strong>Abnormal Named Pipe SecurityDescriptor</strong> — As mentioned earlier in this post, Covenant applies a single security descriptor to it’s named pipe that allows FullControl to the Everyone group. This is not strictly necessary, but improves operator usability by quite a bit. For instance, operations such as token manipulation on a parent Grunt could change the user interacting with the named pipe and prevent the named pipe from being used if the security descriptor was limited to a particular user. For instance, we can see that a Grunt named pipe applies this security descriptor by using <a href="https://twitter.com/tiraniddo">James Forshaw</a>’s excellent <a href="https://www.powershellgallery.com/packages/NtObjectManager/1.1.21">NtObjectManager</a> project:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zi0Uowue7uEsPs7t1Vxjew.png" /><figcaption>NtObjectManager SecurityDescriptor</figcaption></figure><p>An organization can take advantage of this usability tradeoff to identify potentially malicious named pipes by searching for this security descriptor. Used by itself, this detection may result in false positives. Ideally, this would be used as a complimentary indicator to increase the severity of other related indicators.</p><h3>Network Detections</h3><p>Network based detections that identify peer-to-peer traffic often must rely on data that is captured on the internal network of the affected organization. In many organizations this data is not collected at all, but organizations <em>should</em>, at the very least, collect internal network traffic at some key points within the internal network. Where specifically this collection takes place and how much should be collected will always be highly specific to the individual organization.</p><p>Network traffic patterns can often be inferred from host-based indicators. For example, <a href="https://docs.microsoft.com/en-us/windows/security/threat-protection/auditing/event-4624">Windows Event ID 4624</a> logon events from one system to another imply a network connection from the first system to the second. The downside of data collected from the host is that it is more prone to manipulation by an attacker on the compromised endpoint.</p><p>Some of the detections mentioned below may rely on data collected explicitly from the network (i.e. “netflow” data), while some may infer network activity based on host indicators, and some may be collected through either means.</p><ul><li><strong>Remote Connections to Named Pipes</strong> — The peer-to-peer command and control graph depends upon remotely accessed named pipes. We can collect and baseline named pipes being accessed from remote systems. There could be two approaches to collecting this data. One approach is the purely network approach, using some sort of network tap or collector, SMB network traffic can be inspected to look for a named pipe being accessed. As an example, we can see a named pipe being accessed using Wireshark:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pfiIgSB22mUoumQh_ISsNA.png" /><figcaption>Wireshark SMB Named Pipe</figcaption></figure><p>The second approach is the host-based approach. We could use <a href="https://github.com/Cyb3rWard0g/OSSEM/blob/master/data_dictionaries/windows/sysmon/event-18.md">Sysmon Event ID 18</a>, which logs new <em>connections</em> to named pipes, and identify connections that do not originate from the current host. It turns out that when a pipe is being remotely accessed the Image field is set to System. Unfortunately, we do not get the originating hostname, but we can at least identify that the pipe was accessed remotely:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*rnAhlkfODkH4ju1U0YrGSg.png" /><figcaption>Sysmon Event ID 18 Gruntsvc</figcaption></figure><ul><li><strong>Abnormal Host-To-Host Traffic</strong> — This final detection is more general than detecting named pipes specifically. We can attempt to identify peer-to-peer traffic in general by baselining normal internal host-to-host traffic. After a process of baselining this activity, it may be the case that certain high-value servers never, or hardly ever, create network connections with certain network subnets that mostly contain user workstations. If, suddenly, a substantial amount of network connections is identified from one of these high-value servers to a workstation subnet, this could be identified as anomalous and worthy of further investigation. This detection, again, relies upon proper baselining and may result in false positives. Ideally, this detection would be used as a complimentary indicator to increase the severity of other related indicators.</li></ul><h3>Conclusion</h3><p>Peer-to-peer communication between implants is useful for command and control and is nearly essential for robust platforms. Using named pipes over the SMB protocol is a useful, common mechanism for peer-to-peer communication and is the mechanism implemented in Covenant. However, many different protocols exist that could allow for this communication, and you may see some of these other protocols eventually added to Covenant.</p><p>Detection of these behaviors can be difficult but are not impossible. It’s often easier to detect behavior of the implant itself, rather than behaviors of the peer-to-peer protocols themselves, but useful data can be collected, especially data related to the creation and use of named pipes through the use of Sysmon and/or NtObjectManager.</p><p>Peer-to-peer has officially been added to <a href="https://github.com/cobbr/Covenant">Covenant</a> in v0.2, released today. Feel free to make use of it! The video below shows the basic how-to for using peer-to-peer within Covenant:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWsy_yvxZI4s%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWsy_yvxZI4s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWsy_yvxZI4s%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/9de5ddc934d21fba1e490c4b61a0054b/href">https://medium.com/media/9de5ddc934d21fba1e490c4b61a0054b/href</a></iframe><h3>References</h3><ul><li><a href="https://github.com/Cyb3rWard0g/OSSEM/blob/master/data_dictionaries/windows/sysmon/event-17.md">Sysmon Event ID 17 — OSSEM</a></li><li><a href="https://github.com/Cyb3rWard0g/OSSEM/blob/master/data_dictionaries/windows/sysmon/event-18.md">Sysmon Event ID 18 — OSSEM</a></li><li><a href="https://docs.microsoft.com/en-us/windows/security/threat-protection/auditing/event-4624">Windows Event ID 4624</a></li><li><a href="https://www.powershellgallery.com/packages/NtObjectManager/1.1.21">NtObjectManager</a></li><li><a href="https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wpo/4de75e21-36fd-440a-859b-75accc74487c">Named Pipes</a></li><li><a href="https://github.com/cobbr/Covenant">Covenant</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad2c61740456" width="1" height="1" alt=""><hr><p><a href="https://medium.com/specter-ops-posts/designing-peer-to-peer-command-and-control-ad2c61740456">Designing Peer-To-Peer Command and Control</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[Entering a Covenant: .NET Command and Control]]></title>
            <link>https://medium.com/specter-ops-posts/entering-a-covenant-net-command-and-control-e11038bcf462?source=rss-d248a36145f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e11038bcf462</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[infosec]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[Ryan Cobb]]></dc:creator>
            <pubDate>Thu, 07 Feb 2019 15:51:02 GMT</pubDate>
            <atom:updated>2019-02-07T15:51:02.112Z</atom:updated>
            <content:encoded><![CDATA[<h3>Entering a Covenant: .NET Command and Control</h3><p>I’ve slowly <a href="https://posts.specterops.io/introducing-sharpsploit-a-c-post-exploitation-library-5c7be5f16c51">been</a> <a href="https://posts.specterops.io/operational-challenges-in-offensive-c-355bd232a200">open</a> <a href="https://posts.specterops.io/sharpshell-the-worst-scripting-engine-of-all-time-3bbfed6c50e4">sourcing</a> .NET tradecraft that I’ve been working on for some time, including the <a href="https://github.com/cobbr/SharpSploit">SharpSploit</a>, <a href="https://github.com/cobbr/SharpGen">SharpGen</a>, and <a href="https://github.com/cobbr/SharpShell">SharpShell</a> projects. All of these projects have originated from supporting development on a larger project that I’ve been working on over the last year, <a href="https://github.com/cobbr/Covenant">Covenant</a>.</p><p><a href="https://github.com/cobbr/Covenant">Covenant</a> is a .NET command and control framework that aims to highlight the attack surface of .NET, make the use of offensive .NET tradecraft easier, and serve as a collaborative command and control platform for red teamers.</p><h3>Architecture</h3><p>Covenant has a client-server architecture that allows for multi-user collaboration. There are three main components of Covenant’s architecture:</p><ul><li><strong>Covenant</strong> — Covenant is the server-side component of the client-server architecture. Covenant runs the command and control server hosted on infrastructure shared between operators. I will also frequently use the term “Covenant” to refer to the entire overarching project that includes all components of the architecture.</li><li><strong>Elite</strong> — Elite is the client-side component of the client-server architecture. Elite is a command-line interface that operators use to interact with the Covenant server to conduct operations.</li><li><strong>Grunt</strong> — A “Grunt” is the name of Covenant’s implant that is deployed to targets.</li></ul><p>All three components of Covenant are written in C#. Covenant and Elite both target .NET Core and have docker support, while Grunt implants target the .NET framework.</p><h3>Features</h3><p>Covenant has a few key features that I think make it useful and differentiate it from some other command and control frameworks:</p><ul><li><strong>Multi-Platform</strong> — Covenant and Elite both target .NET Core, which makes them multi-platform. This allows these programs to run natively on Linux, MacOS, and Windows platforms. Additionally, both Covenant and Elite have docker support, allowing these programs to run within a container on any system that has docker installed.</li><li><strong>Multi-User</strong> — Covenant supports multi-user collaboration. The ability to collaborate has become crucial for effective red team operations. Many users can start Elite clients that connect to the same Covenant server and operate independently or collaboratively.</li><li><strong>API Driven</strong> — Covenant is driven by a server-side API that enables multi-user collaboration and is easily extendible. Additionally, Covenant includes a Swagger UI that makes development and debugging easier and more convenient.</li><li><strong>Listener Profiles</strong> — Covenant supports listener “profiles” that control how the network communication between Grunt implants and Covenant listeners look on the wire.</li><li><strong>Encrypted Key Exchange</strong> — Covenant implements an encrypted key exchange between Grunt implants and Covenant listeners that is largely based on a similar exchange in the <a href="https://github.com/EmpireProject/Empire">Empire project</a>, in addition to optional SSL encryption. This achieves the cryptographic property of forward secrecy between Grunt implants.</li><li><strong>Dynamic Compilation</strong> — Covenant uses the <a href="https://github.com/dotnet/roslyn">Roslyn API</a> for dynamic C# compilation. Every time a new Grunt is generated or a new task is assigned, the relevant code is recompiled and obfuscated with <a href="https://github.com/mkaring/ConfuserEx">ConfuserEx</a>, avoiding totally static payloads. Covenant reuses much of the compilation code from the <a href="https://github.com/cobbr/sharpgen">SharpGen</a> project, which I described in much more detail <a href="https://cobbr.io/SharpGen.html">in a previous post</a>.</li><li><strong>Inline C# Execution</strong> — Covenant borrows code and ideas from both the <a href="https://github.com/cobbr/sharpgen">SharpGen</a> and <a href="https://github.com/cobbr/sharpshell">SharpShell</a> projects to allow operators to execute C# one-liners on Grunt implants. This allows for similar functionality to that described in the <a href="https://posts.specterops.io/sharpshell-the-worst-scripting-engine-of-all-time-3bbfed6c50e4">SharpShell post</a>, but allows the one-liners to be executed on remote implants.</li><li><strong>Tracking Indicators</strong> — Covenant tracks “indicators” throughout an operation, and summarizes them in the Indicators menu. This allows an operator to conduct actions that are tracked throughout an operation and easily summarize those actions to the blue team during or at the end of an assessment for deconfliction and educational purposes. This feature is still in it’s infancy and still has room for improvement.</li><li><strong>Developed in C#</strong> — Personally, I enjoy developing in C#, which may not be a surprise for anyone that has read my latest blogs or tools. Not everyone might agree that development in C# is ideal, but hopefully everyone agrees that it is nice to have all components of the framework written in the same language. I’ve found it very convenient to write the server, client, and implant all in the same language. This may not be a true “feature”, but hopefully it allows others to contribute to the project fairly easily.</li></ul><h3>Usage</h3><p>Covenant is designed to primarily be used with Docker, and the quick-start information is found in the <a href="https://github.com/cobbr/Covenant/blob/master/README.md">Covenant readme</a> and <a href="https://github.com/cobbr/Elite/blob/master/README.md">Elite readme</a>. Following those instructions, you should launch Covenant on your shared C2 server, and launch the Elite client on your own machine, connecting it to the Covenant server.</p><p>While there is more detailed information available in the readmes, these are the basic commands to build Covenant and Elite docker containers to follow along with these usage instructions:</p><pre>$ ~/Covenant/Covenant &gt; docker build -t covenant .</pre><pre>$ ~/Covenant/Covenant &gt; docker run -it -p 7443:7443 -p 80:80 -p 443:443 --name covenant covenant-username AdminUser --computername 0.0.0.0</pre><pre>$ ~/Elite/Elite &gt; docker build -t elite .</pre><pre>$ ~/Elite/Elite &gt; docker run -it -rm -name elite elite --username AdminUser --computername &lt;covenant_ip&gt;</pre><p>When you first launch Elite, you’ll be prompted for a username, password, and certificate hash. After authenticating, you’ll be presented with the command-line interface. Using the help command, which can be used on any sub-menu in Elite, will let you know your options at the current menu or sub-menu:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*fe4-gu4XqwCuKcZm8UFtvQ.png" /><figcaption><strong>Covenant Help Menu</strong></figcaption></figure><h3>Listeners</h3><p>You’ll see that you have a few options. The first thing you’ll want to do is to start a Listener. Navigating to the Listeners menu, you will see the types of listeners you have the option of using:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*4xdAHTmKavbi6GbURwjnhw.png" /><figcaption><strong>Listeners Menu</strong></figcaption></figure><p>Currently, HTTP is the only supported type of listener, though I’ll be looking to add more in the future. The second, empty menu is the list of created listeners. We’ll see an entry added to this menu shortly.</p><p>Navigating to the HTTP menu, you are presented with options for the HTTP listener:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*yX2AdNOPs5QABgIL3fymyQ.png" /><figcaption><strong>HTTP Listener Menu</strong></figcaption></figure><p>When Covenant is operating within a Docker container, the BindAddress will often be 0.0.0.0, and the ConnectAddress may be the IP Address or domain name of the Covenant system or a redirector. You may also set the BindPort, a local SSL certificate, and an HttpProfile. You can then Start the listener and it will begin waiting for connecting Grunts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*fPSr4md_A4qwCSKfwyvCdg.png" /><figcaption><strong>Started HTTP Listener</strong></figcaption></figure><p>You can also rename the Listener to something more convenient:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*2egLhVrfP2g45hhjnnus6A.png" /><figcaption><strong>Renaming Listeners</strong></figcaption></figure><h3>Launchers</h3><p>Now that a Listener is started, you’ll want to navigate to the Launchers menu. The Launchers menu allows for the generation of one-liners or binaries/scripts that launch new Grunts. The Launchers menu is roughly organized by host binary name:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*1ltJr_FTm9D2Vt_hJrxnjQ.png" /><figcaption><strong>Launchers Menu</strong></figcaption></figure><p>As an example, we’ll choose the PowerShell launcher. We are presented with options for the launcher, and set the Listener to the one we set up previously:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*B2TFX_zFYxjKXe0tuNLzCw.png" /><figcaption><strong>PowerShell Launcher Menu</strong></figcaption></figure><p>We have several options for generating the launcher. The simplest option, generate, generates a pre-staged PowerShell one-liner that ends up being fairly long and complex:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*te2ESyjUdKPwvNIw7rD33w.png" /><figcaption><strong>Generated PowerShell Launcher</strong></figcaption></figure><p>We can also choose to host the PowerShell stager and generate a shorter, non-staged PowerShell one-liner that does a simple “download cradle”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*CiHJssNUpBCANu5232Er7w.png" /><figcaption><strong>Hosted PowerShell Launcher</strong></figcaption></figure><p>Finally, there’s the more generic code command that returns the C# stager and/or grunt code that could be used for more customized launch scenarios:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*qje4dYbLm1KpfHqji9Xksw.png" /><figcaption><strong>Generated C# Stager</strong></figcaption></figure><p>And as always, the help command will give you more information about all the options available:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*bOQd4qMaqwuq2TJpZEpcpw.png" /><figcaption><strong>Launcher Help Menu</strong></figcaption></figure><h3>Grunts</h3><p>Executing a launcher on a system that successfully connects back to the Covenant listener results in a Grunt, Covenant’s implant, being activated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*Coub3gBdwYOMv6Z34KGA8Q.png" /><figcaption><strong>Activated Grunt</strong></figcaption></figure><p>Navigating to the Grunts menu shows a list of all activated Grunts and some key information about each. Using the interact command, we can interact with individual Grunts and conduct further actions. Navigating to this menu will display a few other settings applied to the Grunt:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*STKRgQLRSr9rQePFEiq5BQ.png" /><figcaption><strong>Grunt Interact Menu</strong></figcaption></figure><p>The help command in this menu will display the built-in post-exploitation options for a Grunt:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bi0dOvAh9C3GMStPkwbvnQ.png" /><figcaption><strong>Grunt Built-In Commands</strong></figcaption></figure><p>If you’ve ever used the <a href="https://github.com/cobbr/SharpSploit">SharpSploit</a> project, hopefully you recognize some of these options. SharpSploit is tightly integrated with Covenant, allowing for the easy use of its most practical functions within a Grunt. This includes executing shell commands, PowerShell commands, mimikatz commands, etc:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*FvrVCPf3OcSZBk14D6jdVA.png" /><figcaption><strong>Post-Exploitation with Grunts</strong></figcaption></figure><p>Grunts have another interesting built-in command, sharpshell, that combines some features of the <a href="https://github.com/cobbr/SharpGen">SharpGen</a> and <a href="https://github.com/cobbr/SharpShell">SharpShell</a> projects to allow for the execution of inline C# code that compiles against the SharpSploitlibrary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*Fl4nJiiux0nojqvUdDXV-g.png" /><figcaption><strong>Grunt SharpShell Example</strong></figcaption></figure><h3>Defense</h3><p>Defense against C# and, more generally, .NET tradecraft has been a frequently discussed topic over the last year or so. The good news is that the options for defenders seems to be increasing.</p><p>While there doesn’t appear to be any official Microsoft documentation on the subject, an undocumented ETW provider may be used to capture loaded assemblies and AppDomains, which was discovered by Matt Graeber (<a href="https://twitter.com/mattifestation">@mattifestation</a>) and I discussed in my <a href="https://posts.specterops.io/sharpshell-the-worst-scripting-engine-of-all-time-3bbfed6c50e4">last post</a>. Matt has also published a PoC PowerShell script for capturing relevant .NET runtime artifacts that is available <a href="https://gist.github.com/mattifestation/444323cb669e4747373833c5529b29fb">here</a>.</p><p>Additionally, the <a href="https://docs.microsoft.com/en-us/windows/desktop/amsi/antimalware-scan-interface-portal">AMSI</a> (Antimalware Scan Interface) has officially <a href="https://blogs.msdn.microsoft.com/dotnet/2018/11/28/announcing-net-framework-4-8-early-access-build-3694/">been added to .NET 4.8</a>, which may increase the insights of security products into .NET assemblies loaded from locations other than disk. I’ve <a href="https://cobbr.io/PSAmsi-Minimizing-Obfuscation-To-Maximize-Stealth.html">posted</a> <a href="https://cobbr.io/AbstractSyntaxTree-Based-PowerShell-Obfuscation.html">extensively</a> on the topic of AMSI as it relates to PowerShell, and I imagine it will have similar effects on .NET tradecraft in the future. .NET 4.8 is still in the “early access” phase of development, so it may be some time before organizations have deployed .NET 4.8 throughout the enterprise. However, the sooner an organization can do so, the better.</p><p>These methods of detection and prevention will certainly be effective against Covenant specifically. Covenant is almost entirely reliant on the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly.load?view=netframework-4.0#System_Reflection_Assembly_Load_System_Byte___">System.Reflection.Assembly.Load()</a> function. AMSI in .NET will certainly target assemblies loaded in this manner.</p><p>Additionally, Covenant attempts to track some of the more traditional indicators that are not specific to .NET. As you operate within Covenant, it tracks domain names you use, files you generate, etc.</p><p>Navigating to the Indicators menu you will see the indicators that Covenant has tracked:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N6BdoMhmVKN7m3CCUdmnlg.png" /><figcaption><strong>Indicators Menu</strong></figcaption></figure><p>Covenant tracks TargetIndicators, the computers and users you have established Grunt implants on, NetworkIndicators, listeners you have started, and FileIndicators, files that you have hosted on your listener.</p><p>The idea behind tracking indicators is to allow operators to conduct actions and easily summarize those actions to the blue team during or at the end of an assessment. Covenant’s capability for tracking indicators has a lot of room for improvement, and this is a feature I will continue to enhance. Eventually, I would love to track many other types of indicators and incorporate some sort of report generation.</p><h3>Roadmap</h3><p>I plan to actively develop and continue to enhance Covenant. I have plans for lots of things I’d like to add or enhance. I’ll list below some of the things I’d like to add in the short-term, so people know what to expect (and hopefully spark ideas for outside contributions :)):</p><ul><li><strong>Bug Squashing</strong> — As a warning, Covenant is a brand new project. I fully expect users to break it and discover all sorts of bugs. I imagine I will primarily be squashing bugs in the short-term.</li><li><strong>Credential Tracking</strong> — Users are likely accustomed to these sorts of tools tracking credentials that are obtained throughout an operation. I would like to integrate a similar feature into Covenant.</li><li><strong>Keylogging Utility</strong> — Covenant allows for users to use their own keylogging assemblies in memory as a task, but I think it’d be useful for Covenant to implement a built-in keylogger.</li><li><strong>Screenshot Utility</strong> — Similar to a keylogging utility, Covenant allows for users to use their own screenshot assemblies in memory as a task, but I think it’d be useful for Covenant to implement a built-in screenshot utility.</li><li><strong>Enhanced Indicator Tracking</strong> — As alluded to earlier in the post, indicator tracking is a feature I would like to further enhance. Specifically, I’d like to add many more types of indicators that are tracked, and eventually would like to track them based on specific tasks conducted on Grunt implants.</li><li><strong>Improved User Roles</strong> — Covenant implements a user and role structure that I think can be enhanced. I’d like to allow for the idea of administrative users, read-only users, etc. Eventually users could be assigned with specific privileges for specific listeners or Grunt implants.</li></ul><p>I have some long-term goals and enhancements I’d like to make as well, but those are the enhancements you’re likely to see in the short-term.</p><p>Additionally, I plan to write several follow-up blog posts on Covenant usage that I have not gone into depth on here. I’ve kept this post high-level enough to introduce Covenant and the basics of how to use it, but look for more detailed information and advanced usage in the near future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e11038bcf462" width="1" height="1" alt=""><hr><p><a href="https://medium.com/specter-ops-posts/entering-a-covenant-net-command-and-control-e11038bcf462">Entering a Covenant: .NET Command and Control</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[SharpShell: The Worst Scripting Engine of All-Time]]></title>
            <link>https://medium.com/specter-ops-posts/sharpshell-the-worst-scripting-engine-of-all-time-3bbfed6c50e4?source=rss-d248a36145f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bbfed6c50e4</guid>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Ryan Cobb]]></dc:creator>
            <pubDate>Tue, 11 Dec 2018 16:37:11 GMT</pubDate>
            <atom:updated>2018-12-11T16:37:11.237Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://cobbr.io/SharpGen.html">my last post</a> I introduced <a href="https://github.com/cobbr/SharpGen">SharpGen</a>, a .NET Core console application that utilizes the Roslyn C# compiler to quickly cross-compile .NET Framework console applications and libraries. In this post I’ll introduce a very similar, but slightly different tool: <a href="https://github.com/cobbr/SharpShell">SharpShell</a>!</p><p>To preface, I view <a href="https://github.com/cobbr/SharpShell">SharpShell</a> mostly as a fun proof-of-concept that demonstrates some C# tradecraft possibilities for future operational projects. I view <a href="https://github.com/cobbr/SharpGen">SharpGen</a> as a more operationally useful tool.</p><h3>SharpShell</h3><p>The idea of <a href="https://github.com/cobbr/SharpShell">SharpShell</a> is very similar to SharpGen, in that it uses the <a href="https://github.com/dotnet/roslyn">Roslyn</a> C# compiler to cross-compile .NET Framework assemblies. However, unlike SharpGen, SharpShell is designed to compile <em>and</em> execute the compiled assemblies in memory. SharpShell provides a rudimentary shell-like interface and acts as a <strong>very</strong> basic scripting engine.</p><p>By very basic, I mean very basic. Every one-liner exists on it’s own, no variables are carried over between one-liners, and it has no tab-completion or any of the other nice features or syntax you might be used to having in a legitimate scripting engine. SharpShellessentially just takes C# one liners, embeds them into a class, compiles them into assemblies, executes them, and outputs the results as text. This is why I like to refer to it as the worst scripting engine of all time!</p><p>SharpShell is broken up into three distinct C# projects:</p><ul><li><strong>SharpShell</strong> — SharpShell is the most straightforward of the three projects. It acts as an interactive shell and scripting engine for C# code compiled against chosen source code, references, and resources. The main caveat with SharpShell is that it depends upon .NET Framework 4.6 and 3.5/4.0 being installed on the system. This is because SharpShell depends upon the Roslyn API, which requires 4.6, and executes an assembly in memory cross-compiled for you choice of versions 3.5 or 4.0.</li><li><strong>SharpShell.API</strong> — SharpShell.API and SharpShell.API.SharpShell are two projects meant to be used in tandem. To avoid the opsec limitations and .NET Framework 4.6 requirements of SharpShell, SharpShell.API acts as a web-server that handles the compilation for SharpShell.API.SharpShell. SharpShell.API is a ASP.NET Core 2.1 application and is cross-platform.</li><li><strong>SharpShell.API.SharpShell</strong> — SharpShell.API.SharpShell provides the same interface as SharpShell, but doesn’t have the .NET Framework 4.6 requirement. SharpShell.API.SharpShell runs on .NET Framework 3.5, but also requires network communication with a SharpShell.API server for handling compilation of assemblies.</li></ul><h3>Standalone SharpShell</h3><p>Let’s walkthrough an example using the standalone version of SharpShell. We start up SharpShell and are given a shell-like interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AkdwS_OqP-WDQZTbXvcoPg.png" /></figure><p>As the name suggests, we can execute C# code through this shell interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b125Zx_wBHeaMdcRhUjrMw.png" /></figure><p>SharpShell expects a return statement somewhere in your code, and will transform the returned value into a string and display it as output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NCe5jFwm9_PSqGqE-w4BMw.png" /></figure><p>You can specify multi-line code strings by using the \ escape symbol. The logic can be as complex as you like, as long as you have a return statement:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EPINdLbtMLVDh-GYbQ9MrQ.png" /></figure><p>SharpShell starts to become more powerful once combining this shell-like interface with the capabilities of SharpGen, such as compiling against chosen source code, references, and resources. SharpShell by default compiles against the SharpSploitsource code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yfryud6pIBGREhwarBM_mw.png" /></figure><p>For simple one-liners, SharpShell will add the return statement for you:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MPeEsgyO8lx49LKwYbJXMQ.png" /></figure><p>SharpShell can be configured with custom source code, references, and embedded resources in just the same way as SharpGen by editing YAML configuration files. Reference the <a href="https://stage.cobbr.io/a93aba721e8184fddff77ea5e102263d/SharpGen.html">SharpGen blog post for configuration details</a>.</p><p>Finally, SharpShell will print out the compilation errors in the event that you experience a typo (I’m sure this will never happen):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*ZdUhgwNt6m9wSlmsKa7OTA.png" /></figure><h3>Opsec Considerations</h3><p>There are some important opsec considerations when using the standalone SharpShell. First, there is the obvious consideration that the SharpShell binary and all configuration files have to be present on disk. As mentioned before, SharpShell is a proof-of-concept. However, SharpShell could fairly easily be weaponized to remove all need for those files to be present on disk.</p><p>When developing SharpShell, I also assumed that conducting the compilation on the target system itself would result in temporary compilation files being written to disk. This is what happens when compiling with csc.exe, PowerShell’s Add-Type, or the System.CodeDom.Compiler namespace. For instance, an example of using PowerShell’s Add-Type module:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*_c0Eqtx_kXd32nf0eMD5Tg.png" /></figure><p>With ProcMon, we can see that powershell.exe spawns off csc.exe and writes several temporary files in the %TEMP% directory, including a *.cs file containing the source code to be compiled. These files are quickly deleted, but appear in a predictable location that could allow an EDR or other endpoint product to create signatures on the compilation of malicious code.</p><p>During development, I was under the impression that SharpShell would suffer from this opsec limitation as well. If that were the case, this would be an opsec limitation that would be difficult to avoid. However, I discovered that by using the <a href="https://github.com/dotnet/roslyn">Roslyn API</a>, we avoid this limitation. This library does not spawn csc.exe and compiles truly in memory.</p><h3>SharpShell.API</h3><p>SharpShell.API is an extremely simple API that abstracts the compilation process away from the client-side project, SharpShell.API.SharpShell. SharpShell.API is a ASP.NET Core 2.1 application, so you must install dotnet core to use this project. However, this also makes the project cross-platform.</p><p>You can start SharpShell.API by using the dotnet command-line tool: dotnet .\SharpSploit.API.dll</p><p>This starts up a locally-bound web server on port 5000. SharpSploit.API also includes a Swagger page for interactive API usage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*j3vFMlHDbUvN7wHdUBjGYg.png" /></figure><p>SharpShell.API is very simple and only includes a single API endpoint that accepts compilation requests and returns the compiled assembly. All the configuration details are included in the compilation requests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*Kj3mONZaGlUMIzBXTzjU-g.png" /></figure><p>SharpShell.API.SharpShell uses this web server to request source code to be compiled. SharpShell.API is really only meant to be used for this simple proof-of-concept. SharpShell.API is not C2, please don’t use SharpShell.API as C2.</p><h3>SharpShell.API.SharpShell</h3><p>I created SharpShell.API.SharpShell as a proof-of-concept that does not have a dependency on .NET Framework 4.6, runs only on .NET Framework 3.5, doesn’t write or expect any extraneous files on disk, and still provides the same shell interface as the standalone SharpShell.</p><p>Once SharpShell.API has been started, we can start SharpShell.API.SharpShell and it will connect to our SharpShell.APIinstance and function just the same as SharpShell:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_DVxieBTo8qluCCgBQlckQ.png" /></figure><p>We can also point SharpShell.API.SharpShell at a remote address to communicate with a remote SharpShell.API:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*7zXPrOtQ0lUBf01hG2WHjA.png" /></figure><h3><strong>Detection</strong></h3><p>While Microsoft doesn’t appear to yet have any guidance on .NET optics or detection, it does appear that they are beginning to implement these optics. <a href="https://twitter.com/mattifestation">Matt Graeber</a> discovered an undocumented ETW provider that could be utilized to begin taking advantage of these optics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OUNtqa9JfMUWfSoPjWrmyA.png" /></figure><p>Matt published a script for collecting these type of events <a href="https://gist.github.com/mattifestation/444323cb669e4747373833c5529b29fb">here</a>.</p><p>In order to demonstrate how this ETW provider could be utilized to detect SharpShellactivity, I published a slightly modified copy of Matt’s script to make it a bit easier to use and is available <a href="https://gist.github.com/cobbr/1bab9e175ebbc6ff93cc5875c69ecc50">here</a>. I’ll be using this script to in the examples below.</p><p>First, we’ll start the collector by using the Start-DotNetEventCollection method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5hunQjT5lCThGNAeagsu4A.png" /></figure><p>Now that we have begun event collection, we will use SharpShell to execute a shell command and use the Mimikatz coffee command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4l8rq-xNTFTJx7T-_lWYCQ.png" /></figure><p>We will use the Get-DotNetEvents command to gather .NET events from the specified process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JIF6bGl2FyuF7npQKl_V4w.png" /></figure><p>You can see in the AssembliesLoaded property the SharpShell and Microsoft.CodeAnalysis (Roslyn) assemblies being loaded. While this would not be a particularly resilient detection, defenders could look for these assemblies being loaded to detect SharpShell or assembly compilation activity.</p><p>You’ll also be able to look through any of the other properties collected by Matt’s script:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NvFavqZ5wG6csE4yKDqwLA.png" /></figure><p>While this script may not be scalable to the enterprise level, defenders could look to collect this type of data using something like <a href="https://github.com/Microsoft/krabsetw">KrabsETW</a>.</p><p>For more information on .NET optics and detection, I’d recommend watching <a href="https://www.youtube.com/watch?v=02fL2xpR7IM">Luke Jenning’s recent talk at Bluehat that covers this topic</a>.</p><h3>Summary</h3><p>To describe it succinctly, SharpShell is best for convenience and ease-of-use as a simple proof-of-concept C# scripting engine, and SharpShell.API and SharpShell.API.SharpShell are a proof-of-concept of how this could be properly weaponized.</p><p>I see SharpShell.API and SharpShell.API.SharpShell as an example of what could be accomplished over a legitimate C2 channel. Even though SharpShell does accomplish compilation on the target without writing temporary files to disk, I still think it is always safer to compile on the server-side, since there is no real benefit from compiling on the target. And in realistic scenarios, we typically have a convenient C2 communication channel we can use to bring down pre-compiled assemblies to be executed.</p><h3>References</h3><ul><li>Roslyn — <a href="https://github.com/dotnet/roslyn">https://github.com/dotnet/roslyn</a></li><li>SharpSploit — <a href="https://sharpsploit.cobbr.io/api">https://sharpsploit.cobbr.io/api</a></li><li>SharpGen — <a href="https://stage.cobbr.io/a93aba721e8184fddff77ea5e102263d/SharpGen.html">https://cobbr.io/SharpGen.html</a> and <a href="https://github.com/cobbr/SharpGen">https://github.com/cobbr/SharpGen</a></li><li>CollectDotNetEvents.ps1 (original) — <a href="https://gist.github.com/mattifestation/444323cb669e4747373833c5529b29fb">https://gist.github.com/mattifestation/444323cb669e4747373833c5529b29fb</a></li><li>CollectDotNetEvents.ps1 (modified) — <a href="https://gist.github.com/cobbr/1bab9e175ebbc6ff93cc5875c69ecc50">https://gist.github.com/cobbr/1bab9e175ebbc6ff93cc5875c69ecc50</a></li><li>KrabsETW — <a href="https://github.com/Microsoft/krabsetw">https://github.com/Microsoft/krabsetw</a></li><li>Luke Jennings, Bluehat v18 (covers .NET Optics) — <a href="https://www.youtube.com/watch?v=02fL2xpR7IM">https://www.youtube.com/watch?v=02fL2xpR7IM</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bbfed6c50e4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/specter-ops-posts/sharpshell-the-worst-scripting-engine-of-all-time-3bbfed6c50e4">SharpShell: The Worst Scripting Engine of All-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>
        <item>
            <title><![CDATA[Operational Challenges in Offensive C#]]></title>
            <link>https://medium.com/specter-ops-posts/operational-challenges-in-offensive-c-355bd232a200?source=rss-d248a36145f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/355bd232a200</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ryan Cobb]]></dc:creator>
            <pubDate>Wed, 07 Nov 2018 16:28:38 GMT</pubDate>
            <atom:updated>2018-11-07T16:28:38.461Z</atom:updated>
            <content:encoded><![CDATA[<p>As offensive toolsets <a href="https://posts.specterops.io/ghostpack-d835018c5fc4">continue</a> <a href="https://github.com/tevora-threat/SharpView">to</a> <a href="https://github.com/rvrsh3ll/SharpFruit">move</a> <a href="https://github.com/chrismaddalena/SharpCloud">towards</a> using C# as the language of choice for post-exploitation, I thought it’d be useful to think about some of the operational challenges associated with using C# offensively, especially as compared with PowerShell. PowerShell has many operational and convenience benefits for offensive operators that we lose when moving to C#. However, stealth should almost always take precedence over convenience during red team operations. With that being said, we always want our toolset to be as flexible and convenient as possible, while staying below the bar of detection.</p><p>In this post, I’ll try to document some operational challenges with using C# and offer solutions to help combat these challenges. Examples in this post will utilize <a href="https://github.com/cobbr/SharpSploit">SharpSploit</a>, a .NET post-exploitation library I recently developed (and introduced in my <a href="https://posts.specterops.io/introducing-sharpsploit-a-c-post-exploitation-library-5c7be5f16c51">last post</a>). My goal, however, is to document in a way that is applicable to any C# library or project.</p><p>Additionally, I’ll introduce <a href="https://github.com/cobbr/SharpGen">SharpGen</a>, a new project I built to combat some of these operational challenges.</p><h3>Operational Challenge — Execution</h3><p>When releasing SharpSploit, I made the decision to publish as a library, as opposed to a standalone executable. I did this with some hesitation, as I knew it could cause some operational pain points, but as I continue to develop on C# toolsets, I’m further convinced that it was the right decision. Formatting toolsets as libraries allows them to be utilized together, and helps regain a bit of the flexibility lost in the transition from PowerShell.</p><p>However, publishing as a library also adds an operational challenge that you won’t have to deal with for the majority of other C# toolsets, <strong>how do I actually use this DLL</strong>? There are several options! And as promised in my previous post, I’ll document several options here.</p><h3>Console Application</h3><p>The easiest, and most obvious, method of invoking SharpSploit methods is to create a new console application, add a reference to the compiled SharpSploit.dll, write any custom code that utilizes SharpSploit, and compile. This will result in a compiled .exe file that you should be able to execute from the command line. However, an important caveat with this approach is that the resulting .exe expects the SharpSploit.dll to be present on the target system.</p><p>DLL references are used during compilation to embed metadata about the .dll into the .exe so that the .exe can search for the DLL on a system at runtime. This approach will be successful if you plan to copy the .exe and the SharpSploit.dll to disk on the target system, but will not be successful through a method such as Cobalt Strike’s execute-assembly command, which does not write the .exe or it’s references to disk on the target system.</p><p>So how can we combat this missing DLL conundrum? I document four methods below: <strong>ILMerge</strong>, <strong>Costura</strong>, <strong>Reflection</strong>, and <strong>DotNetToJScript</strong>.</p><h3>ILMerge</h3><p><a href="https://github.com/dotnet/ILMerge">ILMerge</a> is an open source, static linker for .NET assemblies. As the name implies, it merges multiple .NET assemblies into a single output assembly. To do so, ILMerge actually modifies the merged assemblies by stripping out the metadata of the merged assemblies, and creates an entirely new assembly with its own metadata and identity. If the first assembly in the list provided to ILMerge contains an EntryPoint, the EntryPoint is taken as the EntryPoint of the merged assembly. An “EntryPoint” is what makes a console application a console application, and not just a library. The EntryPoint is often the “Main” function that you may be familiar with.</p><p>I’ll walkthrough a quick example of how to use ILMerge. First, you’ll create a new console application that references SharpSploit, and write your custom code that uses it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sSfcez6QUBWa99fjdOnAEg.png" /></figure><p>You’ll build this application, which results in a .exe, SharpSploitDriver.exe in this case, and the SharpSploit.dll. Now we can use ILMerge to merge these two assemblies into a SharpSploit.exe. In this case, ILMerge.exe is already on my Path. You’ll also need to make sure you delete any generated .pdb files prior to merging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QnWn1xLFlCIC7RT_IaxXlw.png" /></figure><p>This generated SharpSploit.exe is a self-contained executable that will not expect a SharpSploit.dll on the target system. ILMerge can also be automated as a part of the build process with some configuration. If you choose to go this route, ILMerge documents how to do this in the <a href="https://github.com/dotnet/ILMerge/blob/master/README.md">README</a>.</p><p>There’s also some interesting forensic implications of this merge. If we open SharpSploit.exe in DNSpy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*t4GBLC0ekx3U_A1--sPWAg.png" /></figure><p>We see that SharpSploit is not actually included as a reference, but the SharpSploit namespaces are embedded as modules in the SharpSploit.exe assembly. We can compare this with SharpSploitDriver.exe in DNSpy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*4KRSP6vwcEJUlcuoKSjQvQ.png" /></figure><p>In this case, SharpSploit is included as a reference, but not as a module. I’m not sure that one or the other is forensically “stealthier”, although references can result in “ImageLoad” events (to use the Sysmon nomenclature) that could be detected. Either way, I think it’s important to be aware of potential forensic artifacts.</p><p>To be clear, this process is more than just merging files together, but actually merging assemblies. This process is partially destructive and <em>could</em> have an impact on how the application executes. For instance, if the functionality depends on the assembly’s name:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vHemFO4imel_RvOjgEeZuQ.png" /></figure><h3>Costura</h3><p>Costura is another open source project with a similar goal to ILMerge. However, the method used is slightly different. Costura adds DLL references as “embedded resources” to the console application. Embedded resources are commonly used for miscellaneous files needed by an application, such as images, videos, or other files.</p><p>Costura embeds reference DLLs as embedded resources, and appends a callback to the AppDomain’s AssemblyResolve event that attempts to load assemblies from the application’s embedded resources! This affects the way the system will resolve assembly loads for the application, and allows us to load assemblies from arbitrary locations, such as an application’s embedded resources.</p><p>This trick originates from <a href="https://blogs.msdn.microsoft.com/microsoft_press/2010/02/03/jeffrey-richter-excerpt-2-from-clr-via-c-third-edition/">a 2010 blog post by Jeffrey Richter</a>, in which he demonstrates the process for registering a callback for the AssemblyResolve event.</p><p>I’ll walkthrough a quick example of how to use Costura. You’ll start out just like last time by creating a console application, adding a reference to the SharpSploit.dll, and writing any custom C# code that utilizes SharpSploit. You’ll also have to add a reference to Costura.Fody. This can be installed as a Nuget package by right-clicking on References and selecting Manage Nuget Packages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E230oJUd0ZkaTqmsv9cUFA.png" /></figure><p>A “gotcha” to keep in mind with Costura, is that the most recent versions have deprecated support for .NET Framework v3.5. For offensive operations, .NET Framework v3.5 is usually what you will want to be working with. Be sure to install Costura v1.6.2 to work with .NET Framework v3.5 assemblies. After installing ILMerge, you’ll see that a FodyWeavers.xml file has been created. This is the Costura configuration, which by default will embed all referenced assemblies as resources. Now when we recompile, it results in a self-contained SharpSploitDriver.exe executable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k9AKQz5NstXpkH7hZupuWA.png" /></figure><p>There are some interesting forensic implications of Costura-generated binaries as well. When opening SharpSploitDriver.exe in DNSpy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*D8rE9e8cfIYyy4eeEk0W8g.png" /></figure><p>You’ll see that not only will SharpSploitDriver.exe maintain its reference to SharpSploit, it also includes: a reference to Costura, several embedded references: costura.sharpsploit.dll.compressed, costura.sharpsploit.pdb, and costura.system.management.automation.dll, as well as a Costura module.</p><p>So how do ILMerge and Costura compare? Well, you’ll find an interesting comment on the previously mentioned blog post from the author of ILMerge:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*1t79Er7nkjnrI65xzEMlGg.png" /></figure><p>Despite that comment, I think there are use cases for both solutions. In fact, for stealth and forensic reasons, I’d probably recommend ILMerge over Costura unless ILMerge impacts how your specific application executes. For SharpSploit specifically, I have not noticed any issues using ILMerge.</p><h3>Reflection</h3><p>Reflection can be used to execute .NET assemblies that do not contain an EntryPoint (i.e. a DLL). The System.Reflection namespace can be used to load .NET assemblies, invoke methods, and much more. So we can use .NET reflection to load the SharpSploit assembly and invoke methods.</p><p>One method for utilizing reflection is using PowerShell. For example, we could invoke SharpSploit methods like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf86431425b410cd9368b4fb8ea0ea65/href">https://medium.com/media/bf86431425b410cd9368b4fb8ea0ea65/href</a></iframe><p>Or we could load it from a hosted location, and then load the assembly and invoke methods by utilizing reflection:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/840c7cf517f02529f8514e7d1fcce5ef/href">https://medium.com/media/840c7cf517f02529f8514e7d1fcce5ef/href</a></iframe><p>And of course, anything we can do from PowerShell, we can do from C#:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bce6bf1fd71ae13f2ab7b7b0942ed34/href">https://medium.com/media/5bce6bf1fd71ae13f2ab7b7b0942ed34/href</a></iframe><p>For that example, you’ll want to remember to compile as a console application. However, you will not need to worry about adding any references, as SharpSploit is loaded through reflection, not through the typically assembly resolving process. Though it is worth noting that Costura’s “AssemblyResolve” technique <strong>itself</strong> uses reflection, by utilizing the System.Reflection.Assembly.Load() method.</p><p>Reflection is an interesting vector for execution, and can serve as a useful “download cradle” to save on executable size and avoid reference complications. For more information on reflection, I’d recommend checking out <a href="https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/reflection">Microsoft’s documentation</a>.</p><h3>DotNetToJScript</h3><p><a href="https://github.com/tyranid/DotNetToJScript">DotNetToJScript</a> is an open source tool written by <a href="https://twitter.com/tiraniddo">James Forshaw</a> that creates JScript or VBScript files that load a given .NET assembly. However, there are a few limiting factors that make this option less practical for use with SharpSploit. It’s still possible, but will require some customization!</p><p>The first thing you’ll notice is that DotNetToJScript does not work nicely with large assemblies, and by default, SharpSploit is a large assembly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZJ1GwLZLATtv_X9oauLV9w.png" /></figure><p>Embedded Mimikatz binaries cause SharpSploit to be large. Luckily, it’s easy to choose not to embed the binaries at compile time, if you don’t need them. Just comment out a couple lines in the SharpSploit.csproj file, like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b322faf77a1bedd390b8fd179faf0302/href">https://medium.com/media/b322faf77a1bedd390b8fd179faf0302/href</a></iframe><p>After making this change, you’ll just have to recompile SharpSploit and copy over the new SharpSploit.dll to the DotNetToJScript folder.</p><p>The next thing you’ll find is that DotNetToJScript does not work well with static classes or methods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5PmbCGhyiQWse_baiYYKPQ.png" /></figure><p>Most of SharpSploit’s useful methods are static, including ShellExecute. To use this method with DotNetToJScript, you’ll have to edit the method in SharpSploit by removing the static classifier on the ShellExecute method, recompiling, and copying the new SharpSploit.dll to the DotNetToJScript folder. And, finally, it should succeed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VQQkNT5InMyQkoxJ3Bz0Bg.png" /></figure><p>This method is interesting for one-off executions or launching an agent, but it requires us to drop a JScript or VBScript file to disk on the target system, which is unnecessary if you already have an agent on the system.</p><h3>Comparison</h3><p>So far, I’ve documented four potential options for creating a self-contained executable and/or script that can invoke SharpSploit methods: Costura, ILMerge, Reflection, and JScript/VBScript via DotNetToJScript. Let’s quickly compare and contrast these methods and when they might be useful:</p><ul><li><strong>DotNetToJScript</strong> — The JScript/VBScript method is most useful in agent launch scenarios, which is certainly not the goal of SharpSploit. I imagine SharpSploit being used almost entirely in situations where we already have an agent on a system. In this case, we don’t want to drop JScript or VBScript files to disk, so we’ll mostly ignore this method for now. However, I wanted to document this vector for those interested in agent launch scenarios.</li><li><strong>Reflection</strong> — The reflection method is interesting, and is most useful in agent launch or “AssemblyResolve” scenarios (i.e. Costura). Using a reflection-based .NET download cradle is a good vector to kick off the launch of an agent. We certainly could continue to use these download cradles to execute each and every post-exploitation module we desire, but this also creates additional, unwanted network traffic that we could avoid.</li><li><strong>Costura/ILMerge</strong> — The final two methods, and, in my opinion, the most operationally useful are Costura and ILMerge. These methods both create self-contained executables that can be used with Cobalt Strike’s execute-assembly command and similar methods. I’ve already compared and contrasted these methods earlier, and the conclusion was that ILMerge is <em>usually</em>, but not always, the right option.</li></ul><p>The real downside to the Costura/ILMerge methods, at least as described so far, is convenience. Not only do you have to compile the SharpSploit library, you also have to create an additional console application that references the library, implement either ILMerge or Costura configurations, and compile.</p><p>At first, this doesn’t seem like too much additional work to ask for. However, you would need to do all of this <strong>every time you want to invoke any SharpSploit method</strong>. As an operator, you really want to be able to quickly invoke consecutive SharpSploit methods, and this is a real hindrance to the operational effectiveness of the project.</p><p>So how can we solve the operational challenge of convenience?</p><h3>Operational Challenge — Convenience</h3><p>Since the release of SharpSploit a little over a month ago, two open source projects have already attempted to combat the operational challenge of convenience. <a href="https://github.com/anthemtotheego/SharpSploitConsole">SharpSploitConsole</a> and <a href="https://github.com/jaredhaight/SharpAttack">SharpAttack</a> have both sought to solve this problem in similar, but different ways. They both serve as a singular console application that can interface with many different methods included in SharpSploit. SharpSploitConsole leverages Costura, while SharpAttack leverages ILMerge.</p><p>Both of these applications accept arguments as command line parameters that specify SharpSploit methods and parameters to be executed. <strong>These projects allow us to compile a console application just once</strong>, and have access to a majority of the functionality of SharpSploit without having to constantly recompile new console applications. This is a huge win for convenience, however, I think there is a downside in flexibility with these approaches.</p><p>For example, let’s say you wanted to use SharpSploit to enumerate all Domain computers, and find the local administrators for these computers. In a custom console application with SharpSploit, you’d do something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46197c020f6a446743c293ebd6e74b8e/href">https://medium.com/media/46197c020f6a446743c293ebd6e74b8e/href</a></iframe><p>With SharpSploitConsole or SharpAttack, you’d likely have to run GetDomainComputers(), parse out the results as text, and run GetNetLocalGroupMembers() on each of the computer names.</p><p>Or let’s say that we want to run some custom C# code as an alternative user, runas.exe-style. In a custom console application with SharpSploit, you’d do something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65f5455f162fb40df15d90573c843ebe/href">https://medium.com/media/65f5455f162fb40df15d90573c843ebe/href</a></iframe><p>With SharpSploitConsole or SharpAttack, I’m not sure this would be possible, as the custom C# code would need to be compiled and loaded as an assembly.</p><p>An additional caveat with these approaches, which is really the fault of SharpSploit itself, is that they don’t work out of the box with Cobalt Strike’s execute-assembly. You must strip out the embedded Mimikatz PE binaries prior to use with execute-assembly, as Cobalt Strike has an upper size limit of 1 MB for assemblies. It’s a real bummer to not be able to utilize Mimikatz from within SharpSploit over Cobalt Strike. Luckily, I’ve made some changes in SharpSploit v1.1 that will allow it to happen, which we will discuss later in the post.</p><p>With these approaches, we gain convenience at the cost of the loss of power of using SharpSploit as a library in customizable ways. We introduce the operational challenge of flexibility.</p><h3>Operational Challenge — Flexibility</h3><p>There are key operational differences in using a compiled language like C# as opposed to an interpreted language like PowerShell. We lose quite a bit of flexibility making this change. With a scripting language, we are able to quickly edit scripts on the fly without worrying about the extra step of compilation. Without PowerShell, we lose the power of the pipeline and the ability to combine toolsets or quickly filter or format output with built-in cmdlets, such as Select-Object or Format-List.</p><p>With C#, there’s no native way to send the output of one tool over the pipeline as input to another tool. There’s no native way to make a small edit to a compiled executable. To help bring back a bit of this flexibility, I’ve written a tool called SharpGen, which is described throughout the remainder of the post.</p><h3>SharpGen</h3><p>To attempt to combat the operational challenge of flexibility, I’ve created a .NET Core console application called <a href="https://github.com/cobbr/SharpGen">SharpGen</a>. SharpGen utilizes the <a href="https://github.com/dotnet/roslyn">Roslyn</a> C# compiler to quickly cross-compile .NET Framework console applications or libraries. .NET Core allows SharpGen to be cross-platform, permitting operators to utilize SharpGen from whatever OS they prefer.</p><p>Remember, the challenge of convenience was caused by having to constantly create new console applications in Visual Studio, add references, embed the references using Costura or ILMerge, etc. SharpGen solves this challenge by making it as quick as a single command to create a new console application, and comes with some additional benefits.</p><h3>Basic Usage</h3><p>The most basic usage of SharpGen would be to provide SharpGen an output filename and a C# one-liner that you’d like to execute. SharpGen will generate a .NET Framework console application that will execute the one-liner. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ceabcc820f67c3b416e480a9e6bee892/href">https://medium.com/media/ceabcc820f67c3b416e480a9e6bee892/href</a></iframe><p>This example generates example.exe, a .NET Framework console application that executes the Mimikatz sekurlsa::logonpasswords module and writes the output to the screen.</p><p>The C# one-liner should always be specified as the final, unnamed command line argument when using SharpGen. However, you can alternatively specify a source file to read from. You may require some logic that does not fit nicely into a single line, or perhaps you are having trouble with escaping quotes on the command line. SharpGen supports reading from a file with the --source-file command line argument.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9769014781b827effda4d104bc6e9caa/href">https://medium.com/media/9769014781b827effda4d104bc6e9caa/href</a></iframe><p>Or, you can specify a source file with a pre-defined class, complete with a Main function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abccbfe2da492347c7dac520dfe61e75/href">https://medium.com/media/abccbfe2da492347c7dac520dfe61e75/href</a></iframe><p>Those are the very basics of the tool. The complete command line usage information is included below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/308e5acea8798ed6efd2999a0a69bd17/href">https://medium.com/media/308e5acea8798ed6efd2999a0a69bd17/href</a></iframe><p>We’ll dive into some details on how SharpGen works under the hood and additional usages in the following sections.</p><h3>Intermediate Usage</h3><p>To understand how SharpGen works, let’s take a quick look at the directory structure of the project:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f292ddb633d7922fec8ea46212a15b86/href">https://medium.com/media/f292ddb633d7922fec8ea46212a15b86/href</a></iframe><p>You’ll want to pay particularly close attention to the Source, References, and Resources directories, as these drive SharpGen’s core functionality. All source code placed under the Source folder will be compiled as source into a single assembly. Because it is compiled as source, there is no need to worry about combining assemblies or embedding them as resources. By default, SharpSploit source code is included in the Source directory, for easy compilation against SharpSploit. However, SharpGen is built in a way so that <em>any</em> source libraries could be dropped into this folder and included.</p><p>For instance, we could drop in the <a href="https://github.com/GhostPack">GhostPack</a> SharpWMI source code into the Source folder (with a few minor modifications) and compile against it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a27641b1d71863a155f8526d24fd7b62/href">https://medium.com/media/a27641b1d71863a155f8526d24fd7b62/href</a></iframe><p>This allows us to invoke SharpWMI and SharpSploit methods from a single assembly! The ability to drop in other libraries and quickly compile against a combination of libraries might be my favorite feature of SharpGen. I did have to make a few minor modifications to SharpWMI to enable this to work. I would love to see new offensive C# toolsets formatted as libraries to allow this sort of tool combination by default, without customizations.</p><p>Assembly references can be configured under the References directory. References can be applied to net35 or net40 assemblies, by being placed in the corresponding directory and configured in the references.yml configuration file. This references.yml configuration comes with sane defaults, but you may want some customization. For instance, if you add additional source code that expects an additional reference, you will need to add this reference in the configuration.</p><p>Or, let’s say you know that you <strong>won’t</strong> need a particular reference. For instance, you know you <strong>won’t</strong> need to execute any PowerShell and the endpoint you are on will detect a System.Management.Automation.dll ImageLoad event. SharpSploit includes a reference to System.Management.Automation.dll by default, but can be removed if you don’t plan on using the SharpSploit.Execution.Shell.PowerShellExecute() method. In this scenario, you can simply disable the System.Management.Automation.dll reference in the references.yml configuration by setting Enabled: false:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81e8c42d30938fadbbfe890dbe1c824f/href">https://medium.com/media/81e8c42d30938fadbbfe890dbe1c824f/href</a></iframe><p>Make sure to also disable the Net40 reference if you plan on targeting .NET framework v4.0!</p><p>If you plan to use SharpGen to create assemblies for use with Cobalt Strike’s execute-assembly command (which it was specifically designed to do), you’ll want to pay attention to the Resources directory. The main limiting factor of the execute-assembly command is the 1MB upper size limit. SharpSploit embeds both x86 and x64 Mimikatz binaries by default that pushes it over the 1MB limit. You have a few options to combat this limiting factor:</p><ol><li>If you aren’t planning to use any Mimikatz methods, you can safely disable the Mimikatz embedded resources in the resources.yml configuration file, which will drastically reduce your binary size. To do so, simply switch the resource configuration to Enabled: false:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/670e34792b1874449001d99d502e1821/href">https://medium.com/media/670e34792b1874449001d99d502e1821/href</a></iframe><p>2. If you do plan to use use Mimikatz methods, do you really need both the x86 and x64 copy of Mimikatz? If not, we can embed only the resource of the platform we need. There are two ways to do this:</p><p>2a. You can filter resources based on platform through command line arguments. This should get you just below the 1MB limit:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85a0260516249c053631156a4aa19333/href">https://medium.com/media/85a0260516249c053631156a4aa19333/href</a></iframe><p>2b. You can also simply disable the unneeded resource in the resources.yml configuration file like we did earlier:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7b04adf46b93d2845f6305335051148/href">https://medium.com/media/d7b04adf46b93d2845f6305335051148/href</a></iframe><p>3. To further reduce binary size, you can embed compressed Mimikatz resources instead of the default resources, which is supported and handled by SharpSploit. These are compressed using the built-in System.IO.Compression library. This compression is not efficient enough to allow you to embed both the x64 and x86 resources and stay under the 1MB limit, but still significantly reduces binary size. This can be done using the resources.yml configuration file by enabling compressed resources and disabling uncompressed resources:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/970d2c1c27dd5e386e63254f538bbc85/href">https://medium.com/media/970d2c1c27dd5e386e63254f538bbc85/href</a></iframe><p>4. The more robust way to use Mimikatz and embed both the x64 and x86 resources, while staying underneath the 1MB limit, is by using ConfuserEx resource protection, which uses a much more efficient compression algorithm. We’ll discuss this in the Advanced Usage section.</p><h3>Advanced Usage</h3><p>SharpGen supports the use of <a href="https://github.com/mkaring/ConfuserEx">ConfuserEx</a>, an open-source protector for .NET applications. The original ConfuserEx that I had been familiar with is available <a href="https://github.com/yck1509/ConfuserEx">here</a>. I was pretty excited to find that ConfuserEx has been forked and maintained in a new location, as the originally project has been abandoned. I was even more excited when I realized that the new ConfuserEx supports .NET Core! This allows us to automate protection and obfuscation of our binaries from within SharpGen, cross-compiled for .NET Framework!</p><p>SharpGen includes a default ConfuserEx project file, confuse.cr that can be used and/or customized with additional ConfuserEx rules, and can be utilized through command line arguments:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50402a613ddf987f2db5f5e49e90934a/href">https://medium.com/media/50402a613ddf987f2db5f5e49e90934a/href</a></iframe><p>The default confuse.cr file includes only a single rule that enables resource protection. ConfuserEx resource protection performs encryption and LZMA compression on the embedded resources. LZMA compression is a much more efficient compression algorithm than the System.IO.Compression compression performed on the powerkatz*.dll.comp files included in SharpGen. This more efficient compression allows us to embed both of the Mimikatz binaries into a compiled binary and still come in <strong>under the 1MB Cobalt Strike</strong> execute-assembly <strong>limit</strong>! An important caveat is that you should embed the non-compressed version of the resources when using this technique, as compression of previously compressed files does not work nearly as well.</p><p>In addition to resource protection, the confuse.cr project file can be modified with additional ConfuserEx rules. For ease of use, the default contains many additional rules that can be uncommented to enable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf9bf8c1f31b38abb67b578d54e816b2/href">https://medium.com/media/cf9bf8c1f31b38abb67b578d54e816b2/href</a></iframe><p>For further information on available ConfuserEx protections, I’ll point you to the <a href="https://github.com/yck1509/ConfuserEx/wiki/Protections">ConfuserEx Wiki documentation</a>.</p><p>Another feature of SharpGen to be aware of, is that SharpGen attempts to optimize your source code by removing unused types. It does this to reduce the final binary size, but also for stealth. There’s no reason your assembly should contain Mimikatz and PE loading source code if it doesn’t need it! This becomes much more useful if you are adding many libraries underneath the Source folder, as you might not need to reference all of them for each compilation.</p><p>SharpGen is fairly transparent about the optimizations made during compilation and will always print the original source and the optimized source code while compiling.</p><p>This optimization appears to work well, but of course there’s always the risk of breaking things when automating source code modifications. So if you run into issues with this optimization, you can always disable it with the --no-optimization command line argument (be aware that this could increase your binary size!):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d226e1ee3f5f1a7d690b659c76d42e7b/href">https://medium.com/media/d226e1ee3f5f1a7d690b659c76d42e7b/href</a></iframe><h3>Future Additions</h3><p>Coincidentally, a similar tool with some key differences, was released just last week called <a href="https://github.com/SpiderLabs/SharpCompile">SharpCompile</a>, that I would encourage everyone to look into as well. I think the coolest aspect of SharpCompile is that includes an aggressor script that handles all of the compilation in the background, so you never have to leave the Cobalt Strike interface!</p><p>I would love to add a similar feature to SharpGen that would handle all of the compilation in the background, and prevent users from ever having to leave the Cobalt Strike interface to generate new assemblies. So look for that to be added to SharpGen here in the near future.</p><h3>Conclusion</h3><p>The use of offensive C# is exciting, but also comes with a set of operational challenges, particularly when formatting toolsets as libraries. Personally, I’d love to see additional open-source toolsets published as a libraries with an optional front-end console application interface, which would give us the best of both worlds.</p><p>Solutions to these operational challenges have to select a method of execution while balancing the needs for convenience and flexibility. SharpGen is my solution to this balancing act, and I hope that others find it useful. But other viable solutions such as SharpSploitConsole, SharpAttack, and SharpCompile do exist, and I am sure that others will emerge. I encourage others to think about these challenges to pick the right tool for the right use case.</p><h3>Credits</h3><p>SharpGen utilizes several open source libraries that I’d like to credit:</p><ul><li><a href="https://github.com/dotnet/roslyn">Roslyn</a> — SharpGen utilizes the Roslyn C# compiler or Microsoft.CodeAnalysis.CSharp, written by Microsoft.</li><li><a href="https://github.com/natemcmaster/CommandLineUtils">CommandLineUtils</a> — SharpGen parses command line arguments using the McMaster.Extensions.CommandLineUtils library, written by <a href="https://twitter.com/natemcmaster">Nate McMaster</a>.</li><li><a href="https://github.com/mkaring/ConfuserEx">ConfuserEx</a> — SharpGen optionally utilizes ConfuserEx for assembly protection and obfuscation, originally written by <a href="https://github.com/yck1509/ConfuserEx">yck1509</a> and now maintained by <a href="https://github.com/mkaring">mkaring</a>.</li><li><a href="https://github.com/0xd4d/dnlib">dnlib</a> — ConfuserEx itself utilizes dnlib, an open source .NET assembly reader/writer libary, written by <a href="https://github.com/0xd4d">0xd4d</a>.</li><li><a href="https://github.com/aaubry/YamlDotNet">YamlDotNet</a> — SharpGen parses YAML configuration files using YamlDotNet, an open source .NET library for parsing YAML, written by <a href="https://github.com/aaubry">aaubry</a>.</li></ul><p>I’d also like to acknowledge some of the other open source projects mentioned throughout this post:</p><ul><li><a href="https://github.com/jaredhaight/SharpAttack">SharpAttack</a> — SharpAttack is an open-source console application front-end for SharpSploit that leverages ILMerge and is written by <a href="https://twitter.com/jaredhaight">Jared Haight</a>.</li><li><a href="https://github.com/anthemtotheego/SharpSploitConsole">SharpSploitConsole</a> — SharpSploitConsole is an open-source console application front-end for SharpSploit that leverages Costura and is written by <a href="https://twitter.com/anthemtotheego">anthemtotheego</a> and <a href="https://twitter.com/G0ldenGunSec">g0ldengunsec</a>.</li><li><a href="https://github.com/SpiderLabs/SharpCompile/">SharpCompile</a> — An automated, offensive .NET compilation solution that leverages aggressor script and an HTTP server that utilizes csc.exe.</li><li><a href="https://github.com/Fody/Costura">Costura</a> — Costura embeds references assemblies as resources.</li><li><a href="https://github.com/dotnet/ILMerge">ILMerge</a> — ILMerge is a static linker for .NET assemblies, written by <a href="https://github.com/mike-barnett">Mike Barnett</a> and maintained by Microsoft.</li></ul><p>And finally, some additional resources I’d recommend checking out:</p><ul><li>AssemblyResolve — <a href="https://blogs.msdn.microsoft.com/microsoft_press/2010/02/03/jeffrey-richter-excerpt-2-from-clr-via-c-third-edition/">https://blogs.msdn.microsoft.com/microsoft_press/2010/02/03/jeffrey-richter-excerpt-2-from-clr-via-c-third-edition/</a>.</li><li>More AssemblyResolve — <a href="https://jimshaver.net/2018/02/22/net-over-net-breaking-the-boundaries-of-the-net-framework/">https://jimshaver.net/2018/02/22/net-over-net-breaking-the-boundaries-of-the-net-framework/</a></li><li>System.Reflection Documentation — <a href="https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/reflection">https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/reflection</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=355bd232a200" width="1" height="1" alt=""><hr><p><a href="https://medium.com/specter-ops-posts/operational-challenges-in-offensive-c-355bd232a200">Operational Challenges in Offensive C#</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[Introducing SharpSploit: A C# Post-Exploitation Library]]></title>
            <link>https://medium.com/specter-ops-posts/introducing-sharpsploit-a-c-post-exploitation-library-5c7be5f16c51?source=rss-d248a36145f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c7be5f16c51</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[sharpsploit]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dot-net-framework]]></category>
            <category><![CDATA[windows]]></category>
            <dc:creator><![CDATA[Ryan Cobb]]></dc:creator>
            <pubDate>Thu, 20 Sep 2018 16:01:10 GMT</pubDate>
            <atom:updated>2018-09-20T16:01:10.333Z</atom:updated>
            <content:encoded><![CDATA[<p>Today, I’m releasing <a href="https://github.com/cobbr/SharpSploit">SharpSploit</a>, the first in a series of offensive C# tools I have been writing over the past several months. <a href="https://github.com/cobbr/SharpSploit">SharpSploit</a> is a .NET post-exploitation library written in C# that aims to highlight the attack surface of .NET and make the use of offensive .NET easier for red teamers.</p><p><a href="https://github.com/cobbr/SharpSploit">SharpSploit</a> is named, in part, as a homage to the <a href="https://github.com/PowerShellMafia/PowerSploit">PowerSploit</a> project, a personal favorite of mine! While <a href="https://github.com/cobbr/SharpSploit">SharpSploit</a> does port over some functionality from <a href="https://github.com/PowerShellMafia/PowerSploit">PowerSploit</a>, my intention is <strong>not</strong> at all to create a direct port of <a href="https://github.com/PowerShellMafia/PowerSploit">PowerSploit</a>. <a href="https://github.com/cobbr/SharpSploit">SharpSploit</a> will be it’s own project, albeit with similar goals to <a href="https://github.com/PowerShellMafia/PowerSploit">PowerSploit</a>.</p><h4><strong>The Appeal of C#</strong></h4><p>There seems to be a trend developing on the offensive side of the security community in porting existing PowerShell toolsets to C#, particularly with the recent releases from my SpecterOps teammates, including: <a href="https://twitter.com/harmj0y">@harmj0y</a>&#39;s <a href="https://github.com/GhostPack">GhostPack</a> toolset and <a href="https://twitter.com/0xthirteen">@0xthirteen</a>&#39;s <a href="https://github.com/tevora-threat/SharpView">SharpView</a>. And <a href="https://github.com/cobbr/SharpSploit">SharpSploit</a> is another piece to that puzzle. With the added security features in PowerShell (ie. ScriptBlock Logging, AMSI, etc.), it makes sense that red teamers are investing in other options. And C# is the logical next step from PowerShell, seeing that they both are based on the .NET framework and porting toolsets from PowerShell to C# is fairly easy to do.</p><p>However, C# does not come without its own set of issues from an offensive perspective. It certainly seems as if optics into .NET <a href="https://twitter.com/mattifestation/status/1034197284043419648">are on the way</a>, and from an operator usability perspective we lose quite a bit of flexibility moving from a scripting language like PowerShell to a compiled language like C#.</p><p>We also need to start worrying about .NET versions. You’ll find .NET v3.5 on a majority of Windows OS versions by default, but newer Windows 10 and Server 2016 systems will only have .NET v4.0+ installed by default. Another “gotcha” is that .NET is not enabled by default on all Windows OS versions either, you’ll find that it needs to be explicitly enabled on Windows Server 2008 and earlier server OS versions. <a href="https://github.com/cobbr/SharpSploit">SharpSploit</a> attempts to deal with this by targeting .NET v3.5 and v4.0 to get the most coverage possible, but you’ll need to be careful to use the correct version on the correct system.</p><h4><strong>To Console or Not to Console?</strong></h4><p>The most significant difference you will see between <a href="https://github.com/cobbr/SharpSploit">SharpSploit</a> and most other offensive C# libraries that have been released so far, is that there is no SharpSploit.exe! <a href="https://github.com/cobbr/SharpSploit">SharpSploit</a> is designed as a library, so there is only a SharpSploit.dll.</p><p>My intention is for <a href="https://github.com/cobbr/SharpSploit">SharpSploit</a> to be primarily used as a library for operators to reference in their own toolsets; however, I anticipate some limitations from this implementation that will likely force me to add a console-based interface eventually. For instance, Cobalt Strike’s execute-assembly module expects an application to have an EntryPoint (i.e. “main” function) to execute, so SharpSploit currently does not operate easily with Cobalt Strike. This is a great example of some of the flexibility issues with offensive C# we will have to solve in the transition from PowerShell.</p><p>Try not to worry about this too much for now, you’ll see some other creative methods for <a href="https://github.com/cobbr/SharpSploit">SharpSploit</a> execution from me here in the near future. <strong>:)</strong> And I will likely add a follow-up post at some point on convenient methods for executing <a href="https://github.com/cobbr/SharpSploit">SharpSploit</a> functions.</p><h3><strong>SharpSploit</strong></h3><p>So what exactly does SharpSploit include? Let’s dive in! SharpSploit currently includes 4 key high-level namespaces: Credentials, Enumeration, Execution, and LateralMovement. We’ll walk through the details of each of these individually.</p><h4><strong>SharpSploit.Credentials</strong></h4><p>The SharpSploit.Credentials namespace includes any classes that deal with…well, credentials! Currently, this includes all Mimikatz functionality as well as token manipulation.</p><p><strong>SharpSploit.Credentials.Mimikatz</strong></p><p>The SharpSploit.Credentials.Mimikatz class implements the ability to execute any Mimikatz command. SharpSploit’s implementation uses an adapted version of <a href="https://twitter.com/subtee">@subtee</a>&#39;s PELoader and borrows from <a href="https://twitter.com/xorrior">@xorrior</a>&#39;s <a href="https://github.com/xorrior/Random-CSharpTools/blob/master/DllLoader/DllLoader/PELoader.cs">implementation</a> as well to load <a href="https://twitter.com/gentilkiwi">@gentilkiwi</a>’s excellent <a href="https://github.com/gentilkiwi/mimikatz">Mimikatz</a> project.</p><p>I’d be remiss if I didn’t also mention <a href="https://twitter.com/harmj0y">@harmj0y</a>’s <a href="https://github.com/GhostPack/SafetyKatz">SafetyKatz</a> project. The primary difference is that <a href="https://github.com/GhostPack/SafetyKatz">SafetyKatz</a> provides convenience for using Mimikatz on a minidump of lsass.exe, while SharpSploit.Credentials.Mimikatz opens the user up to any Mimikatz command.</p><p>The following are the primary functions implemented in the SharpSploit.Credentials.Mimikatz class:</p><ul><li>Command() — Loads the Mimikatz PE with PE.Load() and executes a chosen Mimikatz command.</li><li>LogonPasswords() — Loads the Mimikatz PE with PE.Load() and executes the Mimikatz command to retrieve plaintext passwords from LSASS. Equates to Commands(&quot;privilege::debug sekurlsa::logonPasswords”). (Requires Admin)</li><li>SamDump() — Loads the Mimikatz PE with PE.Load() and executes the Mimikatz command to retrieve password hashes from the SAM database. Equates to Command(&quot;privilege::debug lsadump::sam&quot;). (Requires Admin)</li><li>LsaSecrets() — Loads the Mimikatz PE with PE.Load() and executes the Mimikatz command to retrieve LSA secrets stored in registry. Equates to Command(&quot;privilege::debug lsadump::secrets&quot;). (Requires Admin)</li><li>LsaCache() — Loads the Mimikatz PE with PE.Load() and executes the Mimikatz command to retrieve Domain Cached Credentials hashes from registry. Equates to Commands(&quot;privilege::debug lsadump::cache&quot;). (Requires Admin)</li><li>Wdigest() — Loads the Mimikatz PE with PE.Load() and executes the Mimikatz command to retrieve Wdigest credentials from registry. Equates to Commands(&quot;sekurlsa::wdigest&quot;).</li><li>All() — Loads the Mimikatz PE with PE.Load() and executes each of the above builtin, local credential dumping commands. (Requires Admin)</li><li>DCSync() — Loads the Mimikatz PE with PE.Load() and executes the “dcsync” module to retrieve the NTLM hash of a specified (or all) Domain user. (Requires Domain Admin (or equivalent rights))</li><li>PassTheHash() — Loads the Mimikatz PE with PE.Load() and executes the “pth” module to start a new process as a user using an NTLM password hash for authentication. (Requires Admin)</li></ul><p><strong>SharpSploit.Credentials.Tokens</strong></p><p>The SharpSploit.Credentials.Tokens class implements token manipulation functions, as well as more complex actions that rely on token manipulation. While many token manipulation projects have already been created, SharpSploit.Credentials.Tokens often borrows from <a href="https://twitter.com/0xbadjuju">@0xbadjuju</a>&#39;s awesome <a href="https://github.com/0xbadjuju/Tokenvator">Tokenvator</a> project.</p><p>The following are the primary functions implemented in the SharpSploit.Credentials.Tokens class:</p><ul><li>WhoAmI() — Gets the username of the currently used/impersonated token.</li><li>ImpersonateUser() — Impersonate the token of a process owned by the specified user. Used to execute subsequent commands as the specified user. (Requires Admin)</li><li>ImpersonateProcess() — Impersonate the token of the specified process. Used to execute subsequent commands as the user associated with the token of the specified process. (Requires Admin)</li><li>GetSystem() — Impersonate the SYSTEM user. Equates to ImpersonateUser(&quot;NT AUTHORITY\SYSTEM&quot;). (Requires Admin)</li><li>BypassUAC() — Bypasses UAC through token duplication and spawns a specified process with high integrity. (Requires Admin)</li><li>RunAs() — Makes a new token to run a specified function as a specified user with a specified password. Automatically calls RevertToSelf() after executing the function.</li><li>MakeToken() — Makes a new token with a specified username and password, and impersonates it to conduct future actions as the specified user.</li><li>RevertToSelf() — Ends the impersonation of any token, reverting back to the initial token associated with the current process. Useful in conjuction with functions that impersonate a token and do not automatically RevertToSelf, such as: ImpersonateUser(), ImpersonateProcess(), GetSystem(), and MakeToken().</li><li>EnableTokenPrivilege() — Enables a specified security privilege for a specified token. (Requires Admin)</li></ul><h4><strong>SharpSploit.Enumeration</strong></h4><p>The SharpSploit.Enumeration namespace includes any classes that do enumeration. Currently, this includes some basic local host-based enumeration, network enumeration (i.e. ping/port scanning), and Domain and Net enumeration. I think there’s room for a lot of addition and improvement to this namespace, but it is a start.</p><p><strong>SharpSploit.Enumeration.Host</strong></p><p>The SharpSploit.Enumeration.Host class does basic local host-based enumeration. This class is currently <strong>very</strong> basic. I plan to eventually make some useful additions, but currently there are many other more robust tools, such as <a href="https://github.com/GhostPack/Seatbelt">Seatbelt</a>.</p><p>The following are the primary functions implemented in the SharpSploit.Enumeration.Host class:</p><ul><li>GetProcessList() — Gets a list of running processes on the system.</li><li>CreateProcessDump() — Creates a minidump of the memory of a running process. Useful for offline Mimikatz if dumping the LSASS process. (Requires Admin)</li><li>GetHostname() — Gets the hostname of the system.</li><li>GetUsername() — Gets the current Domain and username of the process running.</li><li>GetCurrentDirectory() — Gets the current working directory full path.</li><li>GetDirectoryListing() — Gets a directory listing of the current working directory.</li><li>ChangeCurrentDirectory() — Changes the current directory by appending a specified string to the current working directory.</li><li>RegistryRead() — Reads a value stored in registry.</li><li>RegistryWrite() — Writes a value into the registry.</li></ul><p><strong>SharpSploit.Enumeration.Network</strong></p><p>The SharpSploit.Enumeration.Network class includes a threaded TCP ping/port scanner for network enumeration.</p><p>The following are the primary functions implemented in the SharpSploit.Enumeration.Network class:</p><ul><li>PortScan() — Conducts a port scan of specified computer(s) and port(s) and reports open ports.</li><li>Ping() — Pings specified computer(s) to identify live systems.</li></ul><p><strong>SharpSploit.Enumeration.Domain</strong></p><p>The SharpSploit.Enumeration.Domain class provides libraries for Active Directory domain enumeration. This is a <strong>partial</strong> port of <a href="https://twitter.com/harmj0y">@harmj0y</a>&#39;s <a href="https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/PowerView.ps1">PowerView</a> project.</p><p>This class does not intend to be a direct or complete port of <a href="https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/PowerView.ps1">PowerView</a>, things will be formatted and implemented differently. I should also mention <a href="https://twitter.com/0xthirteen">@0xthirteen</a>&#39;s <a href="https://github.com/tevora-threat/SharpView">SharpView</a> project, which does aim to be a more direct/complete port of <a href="https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/PowerView.ps1">PowerView</a>.</p><p><strong>SharpSploit.Enumeration.Domain.DomainSearcher</strong></p><p>The SharpSploit.Enumeration.Domain.DomainSearcher class facilitates searching a particular AD domain with a set of credentials.</p><p>This is the first major difference you will notice when using SharpSploit.Enumeration.Domain <a href="https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/PowerView.ps1">PowerView</a>. <a href="https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/PowerView.ps1">PowerView</a> functions can all be executed independently as “static” functions, conforming to the nature of PowerShell as a scripting language. SharpSploit embraces the nature of an object-oriented programming language such as C#. You will need to create a DomainSearcher object that is setup to search a particular domain with a particular set of credentials, and call specific enumeration functions on that DomainSearcher object.</p><p>The DomainSearcher class contains the following primary functions:</p><ul><li>GetDomainUsers() — Gets a list of specified (or all) user DomainObjects in the current Domain.</li><li>GetDomainGroups() — Gets a list of specified (or all) group DomainObjects in the current Domain.</li><li>GetDomainComputers() — Gets a list of specified (or all) computer DomainObjects in the current Domain.</li><li>GetDomainSPNTickets() — Gets SPNTickets for specified DomainObjects.</li><li>GetDomainGroups() — Gets a list of SPNTickets for specified (or all) users with a SPN set in the current Domain.</li></ul><p><strong>SharpSploit.Enumeration.Net</strong></p><p>The SharpSploit.Enumeration.Net class continues the <strong>partial</strong> <a href="https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/PowerView.ps1">PowerView</a> port, and includes functions for enumerating local users, groups, logons, and sessions on remote computers by using Windows API functions (similar to the native, Windows “net.exe” utility). A key note is that the “WinNT” <a href="https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/PowerView.ps1">PowerView</a> collection method is not supported.</p><p>The SharpSploit.Enumeration.Net class includes the following primary functions:</p><ul><li>GetNetLocalGroups() — Gets a list of LocalGroups from specified remote computer(s).</li><li>GetNetLocalGroupMembers() — Gets a list of LocalGroupMembers from specified remote computer(s) for a specified group.</li><li>GetNetLoggedOnUsers() — Gets a list of LoggedOnUsers from specified remote computer(s).</li><li>GetNetSessions() — Gets a list of SessionInfos from specified remote computer(s).</li></ul><h4><strong>SharpSploit.Execution</strong></h4><p>The SharpSploit.Execution namespace includes any classes that deal with executing “stuff”. Currently, this includes PE loading, .NET assemblies, and shell/powershell commands.</p><p><strong>SharpSploit.Execution.Assembly</strong></p><p>The SharpSploit.Execution.Assembly class includes methods for loading .NET assemblies and executing functions within the assembly through reflection.</p><p>The SharpSploit.Execution.Assembly class includes the following primary functions:</p><ul><li>Load() — Loads a .NET assembly byte array or base64-encoded byte array.</li><li>AssemblyExecute() — Loads a .NET assembly byte array or base64-encoded byte array and executes a specified method within a specified type with specified parameters using reflection.</li></ul><p><strong>SharpSploit.Execution.PE</strong></p><p>The SharpSploit.Execution.PE class is planned to be a class for loading arbitrary PEs. Currently, it really only serves as a Mimikatz PE loader. This class is an adapted version of <a href="https://twitter.com/subtee">@subtee</a>’s PE loader that has been made to support arbitrary PEs. As a warning, I have not been successful in loading any arbitrary PE with this class, so your mileage may vary. I hope that this will eventually be fully implemented.</p><p>The SharpSploit.Execution.PE class includes the following primary functions:</p><ul><li>Load() — Loads a PE with a specified byte array. (Requires Admin)</li><li>GetFunctionExport() — Get a pointer to an exported function in a loaded PE. The pointer can then be used to execute the function in the PE.</li></ul><p><strong>SharpSploit.Execution.Shell</strong></p><p>The SharpSploit.Execution.Shell class includes methods for executing “shell” (cmd.exe) commands and PowerShell commands/scripts. It is possible to execute shell commands as an alternative user (provided that you have a valid password), similar to the native Windows runas.exe executable.</p><p>I’m particularly excited about the PowerShellExecute() function. The PowerShellExecute() function by default uses <a href="https://twitter.com/mattifestation">@mattifestation</a>’s AMSI bypass and <a href="https://twitter.com/tifkin_">@tifkin_</a>&#39;s PowerShell logging bypass (which bypasses ScriptBlock logging and Module logging). An issue with executing some of these types of bypasses previously through PowerShell is that the bypasses themselves are logged or AMSI-scanned, creating a bit of a chicken and the egg problem. By utilizing C#, we can execute these bypasses in C# prior to the execution of any PowerShell, resulting in log-free and AMSI-free PowerShell execution!</p><p>The SharpSploit.Execution.Shell class includes the following primary functions:</p><ul><li>PowerShellExecute() — Executes specified PowerShell code using the System.Management.Automation.dll and bypasses AMSI, ScriptBlock Logging, and Module Logging (but not Transcription Logging).</li><li>ShellExecute() — Executes a specified Shell command, optionally with an alternative username and password. Equates to ShellExecuteWithPath(ShellCommand, “C:\\WINDOWS\\System32&quot;).</li><li>ShellExecuteWithPath() — Executes a specified Shell command from a specified directory, optionally with an alternative username and password.</li></ul><p><strong>SharpSploit.Execution.ShellCode</strong></p><p>The SharpSploit.Execution.ShellCode class includes a method for executing shellcode. Shellcode execution is accomplished by copying it to pinned memory, modifying the memory permissions with Win32.Kernel32.VirtualProtect(), and executing with a .NET delegate. This class is based on code written by <a href="https://twitter.com/enigma0x3">@enigma0x3</a>.</p><p>The SharpSploit.Execution.ShellCode class includes the following primary function:</p><ul><li>ShellCodeExecute() — Executes a specified ShellCode byte array by copying it to pinned memory, modifying the memory permissions with Win32.Kernel32.VirtualProtect(), and executing with a .NET delegate.</li></ul><p><strong>SharpSploit.Execution.Win32</strong></p><p>SharpSploit.Execution.Win32 is a large library of PInvoke signatures and structures for Win32 API functions used by various SharpSploit functionality. <a href="http://www.pinvoke.net/">www.pinvoke.net</a> was an invaluable resource for the implementation of this class. I will not attempt to document all of the signatures here, but feel free to check them out in the Win32.cs file.</p><h4><strong>SharpSploit.LateralMovement</strong></h4><p>The SharpSploit.LateralMovement namespace includes classes that allow for any type of code execution on remote computers. Currently, this only includes WMI lateral movement, but others will be coming soon!</p><p><strong>SharpSploit.LateralMovement.WMI</strong></p><p>The SharpSploit.LateralMovement.WMI class includes basic WMI lateral movement capabilities. Currently, the only capability is to spawn a process on a remote system using the Win32_Process.Create WMI method with a specified username and password.</p><p>The SharpSploit.LateralMovement.WMI class currently includes only the following primary function:</p><ul><li>WMIExecute() — Execute a process on a remote system with Win32_Process Create with specified credentials.</li></ul><h4><strong>Testing and Documentation</strong></h4><p>Complete documentation for SharpSploit is available at <a href="https://sharpsploit.cobbr.io/api/index.html">https://sharpsploit.cobbr.io/api/index.html</a>!</p><p>The SharpSploit project also includes SharpSploit.Tests, hooray for unit testing! By no means have I implemented complete coverage in these unit tests, but I am still working at it. I think it would be great if we as a security community could try to up our software development game a bit and include unit tests for offensive projects. They provide great examples for how to use our toolsets, promote code quality, and are useful for contributors.</p><h4><strong>More To Do</strong></h4><p>This is just the beginning for SharpSploit! You’ll notice I alluded to lots of needed additions to SharpSploit throughout the description above. I plan to continue working on and maintaining SharpSploit, so hopefully you will see lots of updates coming soon. The format of SharpSploit as a library is also very conducive to contribution from others. I am very open to pull requests and hope that others will want to contribute to the project to make it better for everyone.</p><h4><strong>Defensive .NET</strong></h4><p>This is really an offensive post and meant as an intro to SharpSploit, but I will at least touch on the defensive side. After educating myself a bit, I’ll plan on a more thorough defensive blog post as a follow up.</p><p>To begin discussing defense for .NET, it’s important to clarify terms. I’ve used “.NET” and “C#” almost interchangably throughout this post, but there is a subtle distinction. The .NET framework is a library and runtime for Windows for “managed code”. “Managed code” is any code that compiles to CIL (Common Intermediate Language, formerly referred to as “MSIL”) and will be managed by the CLR (Common Language Runtime), which is the runtime for the .NET framework and converts CIL to “native” machine code. C# is an example of a language that uses managed code that compiles to CIL. Further, C# was created specifically to target .NET and it’s object model aligns to the .NET object model. Other languages that can compile to CIL (and thus, can be executed under the .NET framework) include VB.NET and JScript.NET.</p><p>So while we’ve talked quite a bit about C# from the offensive side, from a defensive perspective what we really care about is .NET. Specifically, we care about the CIL code being interpreted by the CLR. The bad news is that traditionally, defenders do not have much optics into what is happening in .NET code. And even if they did, it may be hard to identify malicious .NET. In fact, that admission in <a href="https://twitter.com/blowdart/status/889458747516506113">this tweet</a> from <a href="https://twitter.com/blowdart">@blowdart</a> was what first got me excited about offensive .NET:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ukkj7ZV7WEwFGfeCsD-P0w.png" /></figure><p>The good news is that this appears to be changing. I alluded to this at the beginning of the post, but it does seem as if .NET optics are in the works (discovered by <a href="https://twitter.com/mattifestation/status/1034197284043419648">@mattifestation</a>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OUNtqa9JfMUWfSoPjWrmyA.png" /></figure><p>However, as far as I know, there is no official guidance from Microsoft on how to utilize these optics quite yet. Though hopefully we will get some guidance and documentation as this appears to still be in the works.</p><p>Without these optics, what other options do we have? Well the good news is that there is still very few ways to execute .NET without touching disk at some point. And if you can recover the .NET assembly off of disk, it is very easy to reverse the assembly to source code and begin to identify key indicators (CIL code is still bytecode!).</p><p>The easiest and most popular way to execute malicious .NET assemblies is through the System.Reflection.Assembly.Load() method. So how will operators execute this method to kick off their malicious .NET assembly? Typically, either through powershell.exe or through scriptlet-based execution techniques such as regsvr32.exe and wmic.exe through techniques demonstrated by the great <a href="https://github.com/tyranid/DotNetToJScript">DotNetToJScript</a> project by <a href="https://twitter.com/tiraniddo">@tiraniddo</a>. While those scriptlet-based techniques do have the ability to execute remotely hosted scriplets, this still results in the scriptlet hitting disk in a predictable location under %LOCALAPPDATA%\Microsoft\Windows\Temporary Internet Files\ (which I’m not sure all red teamers have yet realized). This leaves powershell.exe as the last real way to execute .NET assemblies without touching disk, and PowerShell has great logging capabilities to ensure you capture the assembly in ScriptBlock logs! Once you have captured the assembly off disk or in logs, you will be able to easily reverse it to source and analyze using a .NET debugger, such as <a href="https://github.com/0xd4d/dnSpy">dnSpy</a>.</p><p>I hope this is a decent, if not brief, start to detecting malicious .NET. Again, once I further educate myself, I’ll try to follow up with a more detailed post.</p><h4><strong>Conclusion</strong></h4><p>This is just the beginning for SharpSploit! You’ll notice I alluded to lots of needed additions to SharpSploitthroughout this post. I plan to continue working on and maintaining SharpSploit, so hopefully you will see lots of updates coming soon.</p><p>I hope that others find SharpSploit helpful, particularly for those trying to diversify their toolset from PowerShell. And as I hinted to at the beginning of this post, SharpSploit is the first in a series of C# tooling that I have been developing over the last few months, so expect to see much more here soon!</p><h4><strong>Credits</strong></h4><p>I owe a ton of credit to a lot of people. Nearly none of SharpSploit is truly original work. SharpSploit ports many modules written in PowerShell by others, utilizes techniques discovered by others, and borrows ideas and code from other C# projects as well. With that being said, I’d like to thank the following people for contributing to the project (whether they know they did or not <strong>:)</strong>):</p><ul><li>Justin Bui (<a href="https://twitter.com/youslydawg">@youslydawg</a>) — For contributing the SharpSploit.Enumeration.Host.CreateProcessDump() function.</li><li>Matt Graeber (<a href="https://twitter.com/mattifestation">@mattifestation</a>), Will Schroeder (<a href="https://twitter.com/harmj0y">@harmj0y</a>), and Ruben (<a href="https://twitter.com/fuzzysec">@FuzzySec</a>) — For their work on <a href="https://github.com/PowerShellMafia/PowerSploit">PowerSploit</a>.</li><li>Will Schroeder (<a href="https://twitter.com/harmj0y">@harmj0y</a>) — For the <a href="https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/PowerView.ps1">PowerView</a> project.</li><li>Alexander Leary (<a href="https://twitter.com/0xbadjuju">@0xbadjuju</a>) — For the <a href="https://github.com/0xbadjuju/Tokenvator">Tokenvator</a> project.</li><li>James Foreshaw (<a href="https://twitter.com/tiraniddo">@tiraniddo</a>) — For his discovery of the token duplication UAC bypass technique documented <a href="https://tyranidslair.blogspot.com/2017/05/reading-your-way-around-uac-part-3.html">here</a>.</li><li>Matt Nelson (<a href="https://twitter.com/enigma0x3">@enigma0x3</a>) — For his <a href="https://github.com/enigma0x3/Misc-PowerShell-Stuff/blob/master/Invoke-TokenDuplication.ps1">Invoke-TokenDuplication</a> implementation of the token duplication UAC bypass, as well his C# shellcode execution method.</li><li>Benjamin Delpy (<a href="https://twitter.com/gentilkiwi">@gentilkiwi</a>) — For the <a href="https://github.com/gentilkiwi/mimikatz">Mimikatz</a> project.</li><li>Casey Smith (<a href="https://twitter.com/subtee">@subtee</a>) — For his work on a C# PE Loader.</li><li>Chris Ross (<a href="https://twitter.com/xorrior">@xorrior</a>) — For his implementation of a Mimikatz PE Loader found <a href="https://github.com/xorrior/Random-CSharpTools/blob/master/DllLoader/DllLoader/PELoader.cs">here</a>.</li><li>Matt Graeber (<a href="https://twitter.com/mattifestation">@mattifestation</a>) — For discovery of the AMSI bypass found <a href="https://twitter.com/mattifestation/status/735261120487772160">here</a>.</li><li>Lee Christensen (<a href="https://twitter.com/tifkin_">@tifkin_</a>) — For the discovery of the PowerShell logging bypass found <a href="https://github.com/leechristensen/Random/blob/master/CSharp/DisablePSLogging.cs">here</a>.</li><li>All the contributors to <a href="http://www.pinvoke.net/">www.pinvoke.net</a> — For numerous PInvoke signatures.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c7be5f16c51" width="1" height="1" alt=""><hr><p><a href="https://medium.com/specter-ops-posts/introducing-sharpsploit-a-c-post-exploitation-library-5c7be5f16c51">Introducing SharpSploit: A C# Post-Exploitation Library</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>