RedCloud: Learning from Astaroth

Steve Walker
13 min readMar 4, 2020

Adding Red Baron modules to automate CloudFlare configuration with TerraForm — protecting red infrastructure, deploying redirectors, delivering payloads, and rebuilding it all at a moment’s notice.

TL;DR; We can seed a categorized domain by providing resiliency for a benign site with CloudFlare, then use workers and firewall rules to siphon off specific URIs, filter for IR, deliver files or staged payloads, and relay C2. All behind legitimate CloudFlare SSL certificates and no hosting costs. When combined with TerraForm and Red Baron we can do it all on the fly.

Resilient red team infrastructure takes effort

As a red team director I enjoyed (most) of the effort of building resilient red team infrastructure that included protections from (and detection of) incident response actions. Jeff Dimmock and rvrsh3ll in particular helped consolidate that knowledge into the Red Team Infrastructure Wiki that has become THE reference point for many red teams on this front. It takes a lot of thought and effort to develop a concept and deploy infrastructure, but the introduction of Terraform and abstraction frameworks like Red Baron have really improved the ability to quickly change even the most complicated infrastructure setups.

Jeff Dimmock created this diagram of ideal red team infrastructure, separating phishing from long-term DNS beaconing, and short-term more interactive C2. I’ve used this and even color coded tracking my infrastructure during ops to match.

When it comes to CloudFlare, you’ll see we can replace the middle redirector server layer, and in some cases even the payload hosting/delivery layer.

The Threat Landscape: MaaS, Astaroth, and CloudFlare Workers

Over the past couple of years I’ve worked closely with threat intel groups to understand emerging threats. I always find myself drawn to the deep analysis of malware and delivery techniques. There’s an appreciation I have for one of the more difficult tasks for an attacker: reliably gaining a foothold on a network with a payload that works. Threat actors put a lot of effort into protecting both delivery mechanisms and that ultimate payload to extend its value. If all it takes is an A/V signature to kill either then it’s not going to be profitable. As a result, we’ve seen the evolution of malware like Emotet into MaaS (Malware as a Service) options. Malware who’s main purpose is to be a trojan horse for another actor’s ultimate payload and objectives.

This past fall (in 2019) a lot of great analysis surfaced for new variants of the fileless malware Astaroth. Specifically, Renato Marinho of Morphus Labs posted his analysis of a variant using Facebook and YouTube profiles to dynamically adjust C2 addresses using trusted domains.

And then shortly after that, Marcel Afrahim posted his research on Astaroth using CloudFlare Workers to dynamically deliver malware. Go check it out, I’ll wait here, they’re worth the read.

While CloudFlare has since changed the way Worker previews are generated to prevent the random URL string staging Afrahim details, it quickly became apparent to me the value CloudFlare could serve for better attack infrastructure.

CloudFlare for Resilient Infrastructure

There have been several good write-ups on using CloudFlare for domain fronting (and debate), and for direct C2. However, I see the value in CloudFlare differently. There’s much more value to be had. Here’s a quick list of capabilities I put together and then automated deployment with Terraform and Red-Baron:

  1. Easily “hide” infrastructure behind CloudFlare shared SSL certificates and IP addresses using proxied DNS records.
  2. Weaponize CNAME redirection and ease the categorization battle
  3. Firewall rules can prevent access based on geographic location, requested URI, user-agent strings, and more. Hello anti-incident response!
  4. Workers.dev as Domain Fronting Lite
  5. Serverless Worker Routes enable unique targeted handling of requests
  6. Serverless Workers can be redirectors instead of building server instances, Apache+mod_rewrite+.htaccess
  7. Serverless Workers can be custom payload delivery mechanisms

We can seed a categorized domain by providing resiliency for a benign site with CloudFlare, then use workers and firewall rules to siphon off specific URIs, filter for IR, deliver files or staged payloads, and relay C2. All with legitimate CloudFlare SSL certificates and no hosting costs. When combined with TerraForm and Red Baron we can do it all on the fly.

Let’s dive into how we can build these key capabilities and then automate it!

1) Proxied DNS Records

Using proxied DNS records from CloudFlare results in our domains resolving to CloudFlare IPs and they use CloudFlare SSL certificates. It’s all intended to provide front-end protection for webservers.

It can just as easily be used to protect red team infrastructure. All without having to setup anything on our back-end C2 server. Huge win right there! No more LetsEncrypt certs, and all it took was a DNS record.

Our domain resolves to CloudFlare IP space
CloudFlare Shared SSL Certificate for our proxied site

Using a categorized domain is a key component for today’s attackers. Organizations routinely filter web traffic based on domain categorization by security vendors. This adds time and effort to care and feed for a domain to make sure it remains categorized.

It’s also important to note that categorization often only applies to the specific host vs every subdomain. Example, the categorization applied to badexample.com hosting a cloned site or a CNAME to benignsite.com would not carry over to payload.badexample.com. So normally I’d need to leave badexample.com up all the time and change the handling configuration to use it in an operation or change a CNAME DNS record to point to my new op server… which often means rekeying SSL certificates and getting added scrutiny from those watching certificate issuances.

Not so with CloudFlare proxied records.

2) Weaponizing CNAME redirection

In fact, we can take it a step further. Using Worker routes (see section below) we can even weaponize those proxied CNAME records so no DNS or SSL changes are needed!

Normally a CNAME record would return the IP of the downstream host. However, with CloudFlare proxied records CloudFlare will still return a CloudFlare IP. This is so that CloudFlare can provide the caching benefits before redirecting the client to the other domain. We can take advantage of this.

CNAME record pointing to a benign domain

Now I can submit mysite.badexample.com for categorization, it inherits the categorization of benignsite.com without having to stand up or update any servers or certificates. Long-term and free domain categorization.

Weaponizing. If we combine proxied CNAME records with Worker routes and script capability below, we can redirect targeted URIs from what would normally go directly from client to benignsite.com, and handle it however we want. All without changing records or certificates. Hidden infrastructure FTW.

3) Firewall Filtering

CloudFlare’s Firewall filtering is straight-forward and easy to setup. Here we can match URI strings and filter clients based on a huge range of fields. While the free account only gives you 5 rules, this is more than enough. We can make very complex rules where each rule can handle all the filtering logic for a given Worker (or even the whole domain if we’d like).

Firewall rule template

With a few quick edits we can block all requests outside of our target country and IP ranges. We can also filter for our specific implant’s user-agent string or any number of custom settings that you know your target or implant will use. The higher-fidelity we get the more we can prevent security firms from grabbing our payload or interacting with our C2 servers… oh and there’s great metric tracking on these rules too.

Traffic sources

Now that we have restricted access to our infrastructure as much as possible, let’s move on to handling redirection and payload delivery with ephemeral Workers instead of paying for server instances somewhere.

4) Workers.dev for Domain Fronting Lite

With Workers you can point your clients directly at the workers.dev subdomain assigned to your account. As covered in Astaroth threat reporting, threat actors used this domain for dynamic hostname generation. The great Workers live editor that makes it really easy to debug a Worker script and make sure everything works just like we want.

Working with a C2 redirector deployed to workers.dev

While the dynamic preview feature no longer works the way threats were leveraging it, it still provides a CloudFlare domain that we use to access Workers. As a result, it’s like a domain fronting technique and without Host headers. However, as a single domain name it’s easily blocked. Still worth noting, as you could use it as a secondary callback for your implant without any extra configuration. Just weigh that as an option with the trade-off of adding a potentially known indicator.

5) Worker Routes for Targeted Request Handling

Back to hosting Workers on our own domain. Workers are triggered by matching a URI pattern in a Worker Route.

Worker Routes

It’s as easy as putting in a URI pattern (note that this means we don’t have to specify the entire URL, and could key on a single word… or GUID…), and selecting the Worker it should map to.

With this in place if anyone goes to our CNAME record, fits our target profile in Firewall rules, and is requesting the specific URI that we designate then they are handed off to the Worker to serve up the response. Very cool.

The potential client traffic paths would then look like this:

Client → Proxied badexample.com → Blocked by Firewall = CloudFlare block page

Client → Proxied badexample.com → No route match = redirect Benign site

Client → Proxied badexample.com → route match → Worker handler → payload

While we could have done all that filtering within a Worker script (and maybe we’d want a second level of redundancy?) It frees us up to make concise Worker scripts focused on what the Worker needs to do: deliver the payload or proxy our C2 comms.

6) Workers as Redirectors

Workers can easily take a request pass it to a secondary server and send back the response. So here’s our simple C2 redirector now that all the OpSec filtering is done.

Simple C2 redirection

Now we have front-end OpSec filtering, rules for targeted C2 handling that only allows our implants to communicate, fast server redirection, and all served up over SSL through a huge network of CloudFlare IP edge nodes. I’ll leave the C2 server setup and profile to the reader. But that’s the point: we’ve protected that investment in the payload.

7) Workers for Payload Delivery

Payload delivery, such as a deaddrop of a file payload is also a quick task. We could either serve it up from another server via the C2 type script above, or we could use the Worker to serve it up directly. Here’s a quick script to return a file download prompt to the user where all we have to do is put the payload contents in a variable.

Return a file for download

Ok, this is great, but I thought you said this was supposed to be easy to setup and teardown?? Bring on Terraform and Red Baron!

Terraform and Red Baron

Before doing this research I had only heard of Terraform for configuring and managing cloud infrastructure. It has a ton of integrations now, and makes creating all this infrastructure on the fly as easy as a few commands.

Red Baron is another tool intended to abstract out the Terraform modules even further so that infrastructure only a few abstract blocks away from going live. It has a lot of forks at this point including ports to Terraform v0.12 that have been merged back in.

CloudFlare has a Terraform provider and a cf-terraforming tool for importing your current CloudFlare configurations into Terraform format. That got me started and after fighting differing documentation and then a GitHub issue request I finally got it all straightened out. Aside: if you’re looking for more programatic API calls, the wrangler tool referenced in CloudFlare’s developer documentation can also be used to push configurations.

Alright, let’s automate! Here are the Red Baron modules I’ve added:

My CloudFlare Red Baron Modules

Setup

First you’ll need to put your account info and API keys in a script or environment variables so that Terraform can reference them, just like we do for other providers. I found that I needed to create a Token within my CloudFlare account with a bunch of permissions as well. The ACCT variable may not actually be needed now.

export CLOUDFLARE_EMAIL=”[email address]”

export CLOUDFLARE_API_KEY=”[API key]"

export CLOUDFLARE_TOKEN=”[Token]”

export CLOUDFLARE_ACCT_ID=”[Account ID]”

export CLOUDFLARE_ACCOUNT_ID = “[Account ID]”

At this point we create a filename.tf file to deploy the CloudFlare objects we want. I’ve included an example deploy-cf-infra.tf file in my repo as a great starting point that spins up each of the types of infrastructure below. Use it and modify to fit your needs. The worker_script_content variables within the modules has default content that you could override if you’d like (along with many other variables) or just let it roll.

Deployment Workflow

The high-level deployment steps are as follows:

  1. Install Terraform and set your provider credentials in environment variables (AWS, Google, CloudFlare, etc)
  2. git clone git clone https://github.com/wheelsvt/Red-Baron
  3. cd ./Red-Baron and cp ./examples/deploy-cf-infra.tf ./myinfra.tf
  4. Edit the myinfra.tf file to your specifications
  5. terraform init terraform plan terraform apply
  6. When you’re done a terraform destroy will tear it all down

Below are some of the details to help out with configuring the Red Baron CloudFlare modules.

Create a Zone

In CloudFlare you have to create a new zone containing your domain name, then you’ll need to set your nameservers for the zone to the returned CloudFlare DNS servers.

The cloudflare\zone_creation module adds a domain to your account, sets up a @ CNAME record pointing to a designated benign_domain and optionally accepts another a_record setting if you want to create a second CNAME record like www.

HTTP/s Redirector

The HTTP/s Redirector is the most used module that filters inbound traffic to prevent non-implant requests from reaching our C2 servers.

Here we reference the zone_id from our Zone block, set our domain name, a uri_pattern to indicate what URI should send clients to our C2 server, a filter_selection option, and override the filter details if we’d like..

HTTP/s Dropper

The HTTP/s Dropper module takes the same options as HTTP/s Redirector with two added variables: filename and file_content

We can push ASCII encoded payload file like HTAs, JS, XML, others easily here by specifying both the content and the filename you want the client to be presented with.

HTTP/s Stager

Like the analysis of Astaroth early on in this blog, I wanted to build a capability to serve a partial payload, then refer the client to a second stage where alternate filters protect it. Then, once assembled, the payload executes. To do this requires an implant matched to the Worker request logic. For now this is just proof-of-concept level as I haven’t built the implant to complement the server side of it.

This module is a good example of building on top of previous modules. It stands up 2 Worker routes and scripts to handle serving up a split payload. The first_stage_json and second_stage_json variables for this proof-of-concept are supposed JSON representations of a split payload.

Defending against these techniques

It would be poor form to leave out a discussion on how we can detect and respond to threats that use these techniques.

  1. Block the*.worker.dev domain at the perimeter with exceptions for any developers that may be using it. There’s no reason a user should need to visit an unpublished Worker script. Domain fronting “lite” blocked.
  2. Block uncategorized and newly registered domains. That may seem like a difficult task. However, the benefits are worth it. A vast majority of phishing and payload delivery campaigns make use of recently registered domains (we’re talking days old). It preemptively blocks threats that haven’t made it into threat IOCs yet. Make sure to audit this rule first to identify outbound requests that are legit, and whitelist them before switching to full-block mode.
  3. Realize that threat actors will find new ways to hide C2 traffic, and no defensive measure is a silver bullet. Today’s threats require network perimeter defenses, email filtering, and solid endpoint protection to identify a threat or malware that gets past controls.
  4. Engage with threat research and red teams to emulate threats you are concerned about. External consulting firms are also a good route for security assessments. Make sure there is visibility for key attack path areas of the most likely threats.

Next Steps

I have a few tasks in mind to improve these scripts, and will update here as I get to them.

  1. Integrate the modules with the AWS C2 server module to automatically configure only allow CloudFlare IPs if using a CloudFlare redirector.
  2. I’ve been toying around with a client architecture checking Worker that will serve different payloads depending on if a client is x86 or x64 or other indicators (to identify a potential sandbox vs true target).
  3. Creating an example client.js payload that will make the calls and execute the cf-http-stager module’s proof-of-concept payload.
  4. Create a demo video of the spin up, implant traffic working, in the meantime, here’s some analysis of implant traffic in CloudFlare….
Auto-generated firewall rules ready to block attempts to access our dropper or C2 outside of expected parameters
Implant traffic to our C2 Worker (left) vs overall to our domain (right) — A lot of redirected traffic that never hits our infrastructure!

Conclusion

CloudFlare provides a platform for increasing the flexibility and resiliency of red team (and production web application) infrastructure. Threat actors are using it to their advantage already. We need to be understand these techniques, leverage them if we can, and take steps to protect ourselves from threats that do.

Hopefully using these CloudFlare Terraform/Red Baron building blocks open up new opportunities and learning for others as much as researching and building them has for me.

--

--