CredBandit (In memory BOF MiniDump) - Tool review - Part 1

 
One of the things I find fascinating about being on the Cobalt Strike team is the community. It is amazing to see how people overcome unique challenges and push the tool in directions never considered. I want explore this with CredBandit (https://github.com/xforcered/CredBandit). This tool has had updates since I started exploring. I’m specifically, looking at this version for this blog post.

In part 2, I ‘ll explore the latest version and how it uses an “undocumented” feature to solve the challenges discussed in this post.

Per the author:

CredBandit is a proof of concept Beacon Object File (BOF) that uses static x64 syscalls to perform a complete in memory dump of a process and send that back through your already existing Beacon communication channel. The memory dump is done by using NTFS transactions, which allows us to write the dump to memory. Additionally, the MiniDumpWriteDump API has been replaced with an adaptation of ReactOS’s implementation of MiniDumpWriteDump.
When you dig into this tool,  you will see that CredBandit is “just another minidump tool.” This is true, but there are some interesting approaches to this.
My interest in CredBandit is less from the minidump implementation but the “duct tape engineering” used to bend Beacon to anthemtotheego‘s will.

CredBandit uses an unconventional way of transferring in memory data through Beacon by overloading the BEACON_OUTPUT aggressor function to handle data sent from BeaconPrintf() function.

There are other interesting aspects to this project, namely:

    • Beacon Object File (BOF) using direct syscalls
    • In memory storage of data (The dump does not need to be written to disk)
    • ReactOS implementation of MiniDumpWriteDump
You can read more about the minidump technique here (T1003-001) or here (Dump credentials from lsass without mimikatz).

Note on the Defense Perspective

Although the focus on this post is to highlight an interesting way to bend Cobalt Strike to a user’s will, it does cover a credential dumping technique. Understanding detection opportunities of techniques vs. tools is an important concept in security operations. It can be helpful to highlight both the offense capabilities and defense opportunities of a technique. I’ve invited Jonny Johnson (https://twitter.com/jsecurity101) to add context to the detection story of this technique, seen below in the Detection Opportunities section.

Quick Start

Warning: BOFs run in Beacon’s memory. If they crash, Beacon crashes. The stability of this BOF may not be 100% reliable. Beacons may die. It’s something to consider if you choose to use this or any other BOF.

CredBandit is easy to use, but don’t that fool you into thinking it isn’t a clever approach to creating a minidump. All the hard work has been done, and you only need a few commands to use it.

The basic process is as follows:

  1. Clone the project: https://github.com/xforcered/CredBandit
  2. Compile CredBandit to a BOF
  3. Load the aggressor script in Cobalt Strike
  4. Launch a beacon running in context with the necessary permissions (i.e., high integrity process running as administrator)
  5. Locate the PID of LSASS
  6. Run CredBandit
  7. Wait …. 🙂
  8. Convert the CredBandit output into a usable dump
  9. Use Mimikatz to extract information from the dump

Consult the readme for details.

Let’s See This in Action

Load the aggressor script from the Cobalt Strike manager

Get the PID of LSASS

Interact with a beacon running with the permissions needed to dump LSASS memory and get the PID of LSASS.

An output of PS gives us a PID of 656.

Run CredBandit to capture the minidump of LSASS

Loading the MiniDumpWriteDump.cna aggressor script added the command credBandit to Beacon.

Running help shows we only need the PID of LSASS to use the command credBandit.

This will take time. Beacon may appear to be unresponsive, but it is processing the minidump and sending back chunks of data by hijacking the BeaconPrintf function. In this example, over 80mb in data must be transferred.

Once the Dump is complete, Beacon should return to normal. A word of caution: I had a few Beacons die after the process completed. The data was successfully transferred, but the Beacon process died. This could be due to the BOF being functional but missing error handling, but I did not investigate.

NOTE: The CredBandit aggressor script, MiniDumpWriteDump.cna, changed the behavior of BEACON_OUTPUT. This can cause other functions to fail. You should unload the script and restart the Cobalt Strike client or use RevertMiniDumpWriteDump.cna to reverse the changes.

Convert the extracted data to a usable format

The file dumpFile.txt is created in the cobaltstrike directory. This file is the result generated by  “highjacking” the BEACON_OUTPUT function to write the received chunks of data from the BeaconPrintf function.

Run the cleanupMiniDump.sh command to convert this file back into something useful:

./cleanupMiniDump.sh

You will now have two new files in the cobaltstrike directory: .dmp and .txt.

The .txt is a backup of the original dumpFile.txt.

The .dmp is the minidump file of LSASS.

Use Mimikatz to extract information from the dump

At this point, we are done with CredBandit. It provided the dump of LSASS. We can now use Mimikatz offline to extract information.

You can use something like the following commands:

mimikatz
mimikatz # sekurlsa::minidump c:\payloads\credBandit\lsass.dmp
mimikatz # sekurlsa::logonPasswords



BTW, dontstealmypassword


Demo

Here is a quick demo of the tool.


Breaking down the key concepts

Beacon Object File (BOF) using direct syscalls

Direct syscalls can provide a way of avoiding API hooking from security tools by avoiding the need for calling these APIs.

CredBandit uses much of work done by Outflank on using Syscall in Beacon Object Files. I won’t spend time on this but here are great resources:

In memory storage of data

The minidump output is stored in Beacon’s memory vs. being written to disk. This is based on using a minidump implementation that uses NTFS transactions to write to memory: https://github.com/PorLaCola25/TransactedSharpMiniDump

ReactOS implementation of MiniDumpWriteDump

MiniDumpWriteDump API is replaced with an adaptation of ReactOS’s implementation of MiniDumpWriteDump: https://github.com/rookuu/BOFs/tree/main/MiniDumpWriteDump

Unconventional way of transferring in memory data through Beacon via overloaded BeaconPrintf() function

This is what I find most interesting about this project. In short, the BEACON_OUTPUT aggressor function is used to send the base64 encode dump it receives as chunks from BeaconPrintf. These chunks are written to a file that can be cleaned up and decoded.

How does this hack work? It’s clever and simple. The BOF uses the BeaconPrintf function to send chunks of the base64 encoded minidump file to the teamserver. This data is captured and written to a file on disk.

The following is an example of the output file:

received output:
TURNUJOnAAAEAAAAIAAAAAAAAAAAAAAAIggAAAAAAAAHAAAAOAAAAFAAAAAEAAAAdCMAAIwAAAAJAAAAUCQAAMI6AAAAAAAAAAAAAAAAAAA...
received output:
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABolPx/AAAA4AkACJUKAP2mu1yUJQAAvQTv/gAAAQAAAAcAAQDuQgAACgABAO5CPwAAAAA...
received output:
AAAAAAAAAAAAAAAAAAAAAAAAAAC5kPx/AAAAoA4A94kOABHEhU5sJwAAvQTv/gAAAQACAAYAAQDuQgAACgABAO5CPwAAAAAAAAAEAAQAAgA...
received output:
AAAAAAAAAAAAAAAYkfx/AAAAoAcADk4IABy/Gt86KQAAvQTv/gAAAQACAAYAAQDuQgAACgABAO5CPwAAAAAAAAAEAAQAAgAAAAAAAAAAAAA...

This minidump file is rebuilt using the script cleanupMiniDump.sh. Credential material can be extracted using Mimikatz.


 Adjusting the Technique

The heart of this technique is based on accessing and dumping LSASS. Instead of using the suspicious activity of payload.exe accessing lsass.exe, you could find a process that regularly accesses LSASS, inject into that process, and perform your dump.

The BOF (https://github.com/outflanknl/FindObjects-BOF) may help you locate a process that has a handle to lsass.exe using similar OPSEC as CredBandit by using a BOF and direct systems calls. FindObjects-BOF is “A Cobalt Strike Beacon Object File (BOF) project which uses direct system calls to enumerate processes for specific modules or process handles.

Give it a try!


Detection Opportunities

Although the focus on this post was to highlight an interesting way to bend Cobalt Strike to a user’s will, it does cover a credential dumping technique. Understanding detection opportunities of techniques vs. tools is an important concept in detection engineering. I’ve invited Jonny Johnson (https://twitter.com/jsecurity101) to provide context to the detection story of this technique.

Jonny’s detection note are in the left column, and I hae added my take in the right.

Detection Story by Jonny Joe’s comments
Before we can start creating our detection we must identify what is the main action of this whole chain – opening a handle to LSASS. That will be the core of this detection. If we detect on the tool or code specifically, then we lose detection visibility once someone creates another code that uses different functions. By focusing on the technique’s core behavior, we prevent manually creating a gap in our detection strategy. For this piece I am going to leverage Sysmon Event ID: 10 – Process Accessed. This event allows me to see the source process that was requesting access to the target process, the target process, the granted access rights (explained in a moment), along with both the source process GUID and target process GUID.

Sysmon Event ID 10 fires when OpenProcess is called, and because Sysmon is a kernel driver, it has insight into OpenProcess in both user-mode and kernel-mode. This particular implementation uses a syscall for NtOpenProcess within ntdll.dll, which is the Native API version of the Win32 API OpenProcess.

How is this useful?

Within the NtOpenProcess documentation, there is a parameter called DesiredAccess.This correlates to the ACCESS_MASK type, which is a bitmask. This access is typically defined by the function that wants to obtain a handle to a process. OpenProcess acts as a middle man between the function call and the target process. The function in this instance is MiniDumpWriteDump. Although ReactOS’s implementation of MiniDumpWriteDump is being used, we are still dealing with Windows securable objects (e.g. processes and files). Due to this, we must follow Windows built-in rules for these objects. Also, ReactOS’s MiniDumpWriteDump is using the exact same parameters as Microsoft’s MiniDumpWriteDump API.

Don’t overemphasize tools. Fundamentally, this technique is based on the detection a process accessing LSASS.

ReactOS’s MiniDumpWriteDump is using the exact same parameters as Microsoft’s MiniDumpWriteDump API.” It is important to focus on the technique’s primitives. There can be multiple implementations by different tools but the technique can often be broken down in to primitives.

Within Microsoft’s documentation, we can see that if MiniDumpWriteDump wants to obtain a handle to a process, it must have PROCESS_QUERY_IMFORMATION & PROCESS_VM_READ access to that process, which we can see is requested in the CredBandit source code below:

However, this still isn’t the minimum rights that a process needs to perform this action on another process. After reading Microsoft’s Process Security and Access Rights we can see that anytime a process is granted PROCESS_QUERY_IMFORMATION, it is automatically granted PROCESS_QUERY_LIMITED_IMFORMATION. This has a hex value of 0x1410 (this will be used in the analytic later).

Next, we want to see the file created via NtCreateTransacted. Sysmon uses a minifilter driver to monitor file system’s stacks indirectly, so it has insight into files being written to disk or a phantom file. One thing we have to be careful with is that we don’t know the extension the actor might have for the dump file. Bottom line: this is attacker-controlled and if we specify this into our analytic we risk creating a blind spot, which can lead to an analytical bypass.

Lastly, a little icing on the cake would be to add a process creation event to this analytic as it would just provide context around which user was leveraged for this activity.

Data Sources/Events:

User Rights:

Process Access:

File Creation:

  • Sysmon Event ID 11

Process Creation:

A detection strategy hypothesis should account for potential blind spots. Blind spots are not bad, but should be identified. https://posts.specterops.io/detection-in-depth-a2392b3a7e94

Analytics:

The following analytics are not meant to be copy and paste, but more of the beginning of detection for your environment. If you only look for the access rights 0x1410, then you will create a blind spot if an actor uses ReadProcessMemory to dump LSASS. Ideally, multiple detections would be made for dumping LSASS so that blind spots could be covered along the way.

Sysmon EID 10 Process Access

Regarding Detection:

Multiple combinations of access rights may be requested based on the implementation. Focus on a query to cover minimal rights needed. This will reduce blind spots based on a specific implementation.

Regarding OPSEC:

Notice that payload.exe is accessing lsass.exe. This is due to this implementation as a BOF running directly under the context of Beacon.

BOF and syscalls can be great, but maintain OPSEC awareness.

Sysmon EID 10 & EID 11

Sysmon EID 10, 11, & 1

Detection Summary

When writing a detection the first thing I do is identify the capabilities that a tool and/or technique has. This helps me narrow in on a scope. A piece of code could be implementing 3-4 techniques. When this happens, I separate these techniques and look into them separately. This allows me to create a detection strategy per capability.
When the capability is identified and the components being used are highlighted, proper scoping can be applied. We can see a commonality between this implementation and many others. That commonality is MiniDumpWriteDump and the access rights needed for that function call. This is the foundation of our detection or base condition. However, this could be evaded if an actor uses ReadProcessMemory because there are a different set of minimum access rights needed. A separate detection would need to be created for this function. This is ideal as it applies an overlap of our detection to cover the blind spots that are related to a technique.
Pulling attributes like file creation and process creation are contextual attributes that can be applied back to the core detection (MiniDump). The detection shouldn’t rely on these attributes because they are not guaranteed to be present.

Cobalt Strike is not inherently malicious. It is simply a way for someone to implement an action. The intent behind that action is what determines a classification of malicious or benign. Consequently, I don’t focus on Cobalt Strike specific signatures, I look at the behavior/technique being implemented.

I like how Palantir outlines a method for documenting detection strategies using their Alerting and Detection Strategy Framework (ADS).
Jonny Johnson (https://twitter.com/jsecurity101)

Thanks to https://twitter.com/anthemtotheego  for creating this tool.

Stay tuned for part 2 where I ‘ll talk about how the latest version uses an “undocumented” feature to download the minidump file instead of hijacking the BEACON_OUTPUT function.

Conclusion

Wait?!?! This post highlighted the need to ‘hack’ Cobalt Strike because of a lack of features.  Why isn’t this part of the toolset?

Cobalt Strike is a framework. It is meant to be tuned to fit a user’s need. Projects like this help expose areas that can be improved. This helps the team add new features, update documentation, or provide examples.

References

Detection References:

New home for Cobalt Strike malleable c2 profiles and scripts

 

The Cobalt Strike references (malleable c2 profiles, scripts, Elevate Kit, etc.) have been consolidated under a new GitHub account. https://github.com/cobalt-strike

We understand that many blog posts (and even our documentation) have references to the original links. The original links will be available for the time being but may not be in the future.

Update your references to use the new repositories. All future updates will be made under the new account.

Create listeners with an aggressor script - listener_create_ext

 

This short post is a follow up to the post “Manage Cobalt Strike with Services” where I described a method to automate Cobalt Strike teamservers by creating services.

In this post, I will take a closer look at the aggressor function that is used to create listeners listener_create_ext to expanded on the documentation and provide an example.

The documentation shows three arguments. Let’s focus on $3, the key/value pairs. The key/values control the settings used to setup a listener.

From the Documentation

listener_create_ext

Create a new listener.

Arguments

$1 - the listener name
$2 - the payload (e.g., windows/beacon_http/reverse_http)
$3 - a map with key/value pairs that specify options for the listener

Let’s break down the options with an aggressor script that creates an HTTP listener. I formatted the script to be easier to read and added comments to provide a bit of guidance.

listener_create_ext(
    "HTTP",                             # Listener name, use something unique across all teamservers (i.e., server1-http)
    "windows/beacon_http/reverse_http", # Listener type, remember, payloads are driven by listeners
    %(host => "stage.host",             # Staging host, Only one staging host can be set
        profile => "default",           # The profile variant name, variants are set in the malleable c2 profile
        port => 80,                     # Port for c2 communications
        beacons => "b1.host,b2.host",   # Comma separated list of beacon hosts
        althost => "alt.host",          # host header value
        bindto => 8080,                 # The port HTTP Beacon payload web server will bind to.
        strategy => "failover-5x",      # Host rotation strategy aka fail strategy
        proxy => "http://user:[email protected]:8080" # Proxy host settings 
    ) 
);

This aggressor script will create a listener that looks like this in the GUI.

References:

  • https://www.cobaltstrike.com/aggressor-script/functions.html#listener_create_ext
  • https://www.cobaltstrike.com/help-http-beacon
  • https://www.cobaltstrike.com/2021/06/23/manage-cobalt-strike-with-services/

Manage Cobalt Strike with Services

 

This post is part of a “Quality of Life” series, where tips and tricks will be shared to make using Cobalt Stike easier. 

Cobalt Strike is a post-exploitation framework and requires customization to meet your specific needs. This flexibility is one of the most powerful features of Cobalt Strike. While this is great, some may find it challenging to quickly set up a teamserver. Even if you are only conducting quick tests, consider building an automated deployment process using something as simple as a bash script or something more complex like a DevOps process based on tools like Ansible or Terraform. 

This post covers the aspect of considering adding to a deployment process to enhance teamserver automation. It does not cover complete infrastructure design. Several people in the security community have posted excellent design guidance.

Teamserver and Listener Automation

This post explores the automation of:

  • auto-starting teamserver using a random custom malleable c2 profile
  • creating listeners using a headless aggressor script

This process needs three files:

  • teamserver.service (controls the teamserver as a Linux service)
  • listener. service (controls the auto-creation of listeners as a Linux service)
  • listener_service.cna (aggressor script that specifies the parameters for the listeners)

These templates can be found here: https://github.com/vestjoe/cobaltstrike_services

Steps

Summary

I’ll summarize the steps here, but you should integrate these steps into an infrastructure deployment plan in actual practice. I demo the results of a practical example at the end of the post. 

Note: These scripts have been tested on Ubuntu server and may need to be adjusted based on your actual use case.

  • Update the service files to match your environment.
    • teamserver.service
    • listener.service
    • listener_service.cna
  • Copy the service files to your teamserver host
    • /etc/systemd/system/teamserver.service
    • /etc/systemd/system/listener.service
    • /opt/cobaltstrike/listener_service.cna
  • Register the new services
    • systemclt daemon-reload
  • Start the services
    • systemctl start teamserver.service
    • systemctl start listener.service
  • Test that everything works

Step Details

Note: The following steps show the details, but should broken down into deployment steps (ansible, terraform, etc.) that fit your own process.

1) Update the Teamserver Service Configuration File

This file is used to configure teamserver as a Linux service.

Use the template below as a starting point. Update the settings to match your environment and save it to a temporary location. (I’m using /tmp for this demo)

Specifically, you should update: 

  • WorkingDirectory: Set to the cobaltstrike directory
  • ExecStart: Set with your teamserver parameters
## TEMPLATE START

# teamserver.service

[Unit]
Description=Cobalt Strike Teamserver Service
After=network.target
Wants=network.target

[Service]
Type=Simple
WorkingDirectory=/opt/cobaltstrike
ExecStart=/opt/cobaltstrike/teamserver <TEAMSERVER IP> <PASSWORD> <PATH TO C2 PROFILE>

# Example
# ExecStart=/opt/cobaltstrike/teamserver `hostname -I` thisismypassword /opt/cobaltstrike/c2.profile

[Install]
WantedBy=multi-user.target

## TEMPLATE END

The malleable c2 profile can be any you create. I like to use randomly generated profiles for quick tests. https://github.com/threatexpress/random_c2_profile

2) Update the Listener Service Configuration File

The listener service uses agscript to run a headless aggressor script as a service. If you are not familiar with agscript, take a look at “Headless Cobalt Strike” in the manual https://www.cobaltstrike.com/aggressor-script/index.html

Use the template below as a starting point. Update the settings to match your environment and save them to a temporary location. (I’m using /tmp for this demo)

Specifically, you should update:

  • WorkingDirectory: Set to the cobaltstrike directory
  • ExecStart: Set with the values you need to run the agscript
## TEMPLATE START
# listener.service
[Unit]
Description=Cobalt Strike aggressor service
After=teamserver.service network.target
Wants=teamserver.service
StartLimitIntervalSec=33

[Service]
Restart=on-failure
RestartSec=10
WorkingDirectory=/opt/cobaltstrike
ExecStartPre=/bin/sleep 60
ExecStart=/bin/bash /opt/cobaltstrike/agscript <TEAMSERVER IP> <TEAMSERVER PORT> <USER to LOGON TO COBALTSTRIKE> <TEAMSERVER PASSWORD> <PATH TO listener_service.cna>
# Example
# ExecStart=/bin/bash /opt/cobaltstrike/agscript 127.0.0.1 50050 listener_service thisismypassword /opt/cobaltstrike/listener_service.cna

[Install]
WantedBy=multi-user.target
## TEMPLATE END

Headless Aggressor Script

This example aggressor script is used to create and start an HTTP, HTTPS, and SMB listener with all the needed parameters. It is a regular aggressor script and can be loaded manually through the Cobalt Strike client or run headless using agscript. 

Use the template below as a starting point. Update the settings to match your environment and save them to a temporary location. (I’m using /tmp for this demo)

The script uses the listener_create_ext function. Take a look at the support documentation for additional options.

At a minimum, change the following to match your environment.

  • HTTP Listener
    • listener name
    • host
    • althost
  • HTTPS Listener
    • listener name
    • host
    • althost
  • SMB Listener
    • listener name
    • port
## TEMPLATE START
println("
###################################################################
 CobaltStrike Aggressor Script          
 Author: Joe Vest
 Description: Headless script to create listeners
###################################################################");

println('listener_service.cna: Loading listener_service.cna...');

on ready{
    println('listener_service.cna: Creating HTTP Listener...');
    listener_create_ext("HTTP", "windows/beacon_http/reverse_http", %(host => "iheartredteams.com", port => 80, beacons => "iheartredteams.com", althost => "iheartredteams.com", bindto => 80));

    println('listener_service.cna: Creating HTTPS Listener...');
    listener_create_ext("HTTPS", "windows/beacon_https/reverse_https", %(host => "iheartredteams.com", port => 443, beacons => "iheartredteams.com", althost => "iheartredteams.com", bindto => 443));
    
    println('listener_service.cna: Creating SMB Listener...');
    listener_create_ext("SMB", "windows/beacon_bind_pipe", %(port => "mojo.5887.8051.34782273429370473##"));

    sleep(10000);

}
## TEMPLATE END

Copy the Files to the Appropriate Location

sudo cp /tmp/teamserver.service /etc/systemd/system/teamserver.service
sudo cp /tmp/listener.service /etc/systemd/system/listener.service
sudo cp /tmp/listener_service.cna /opt/cobaltstrike/listener_service.cna

Register and Start the New Services

sudo systemclt daemon-reload
sudo systemctl start teamserver.service
sudo systemctl start listener.service

Test to Make Sure Everything is Working as Expected

Teamserver should be running, and the script should have created the listeners. If so, test a few payloads and commands to make sure everything works as expected.

Consider Adding this Process to an Infrastructure Deployment Process

These manual steps and templates provide a means to automate some of the Cobalt Strike but can be enhanced further through a more formal process.

For example, I do this in a couple of ways:

  • I use simple bash scripts and the AWS CLI to deploy and configure a test environment.
  • I create ansible roles to automate the deployment and configuration of a teamserver as part of a larger deployment script.

Demonstrating a Practical Example

In this demo, I show how I fully automate the deployment and configuration of the range I used for quick realistic testing to AWS LightSail. The deployment is fully automated and includes settings to protect the teamserver from direct public access. 

Range Highlights

The script results in a small test range that follows this traffic pattern

  1. Beacon reaches out to a valid Cloud front redirector. These cloud redirectors are really just HTTP proxies. (https://www.blackhillsinfosec.com/using-cloudfront-to-relay-cobalt-strike-traffic/)
  2. Traffic is redirected to the Apache redirector. (again, just another HTTP proxy that applies our logic)
  3. Apache forwards the HTTP to the teamserver.

Services Running

The agscript user logon event (listener_service) can be seen in the Event Log.

The listeners are automatically created based on the service settings.

References


Interested in Trying Cobalt Strike?

REQUEST A QUOTE

There's a New Deputy in Town

 

It’s been less than a month since I joined the Cobalt Strike team. My first impressions of this team have been overwhelmingly positive. As Raphael transitioned out, He left us with a message “Cobalt Strike is in good hands.” I couldn’t agree more.

What can you expect from me? I’m here to provide input and guidance to Cobalt Strike’s overall direction, but more importantly, I’m here to interact with and learn from the community to help drive the best improvements. I encourage you to reach out with questions or discussions on offensive or defensive security topics. Consider following us on Twitter @joevest, @CoreAdvisories, and @FortraOfficial if you’d like to keep up with the latest news on Cobalt Strike, Core Security, or Fortra. You can also find me hanging out in the BloodhoundGang #aggressor channel on Slack.

I titled this post “There’s a new deputy in town.” You may hear my voice more than others on the team, but I am not the sheriff. I’m just the newest member of a fantastic team. We all play different but crucial roles. I’m excited to start this new journey with this great team.