Post

Anti-Analysis Techniques

Anti-Analysis Techniques

Anti-Analysis Techniques

Techniques.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
#include <Windows.h>
#include <stdio.h>
#include <Shlwapi.h>
#include <Psapi.h>

#pragma comment(lib, "Shlwapi.lib")


// Detect VM by hardware
BOOL HardwareCheck() {

    SYSTEM_INFO SysInfo = { 0 };
    MEMORYSTATUSEX MemInfo = { 0 };
    HKEY hKey = NULL;
    DWORD dwNumUSB = NULL;
    DWORD dwRegErr = NULL;


    // ---------------- CPU CHECK ----------------
    // Fills SysInfo with CPU/core details (logical processors, architecture, etc.)
    GetSystemInfo(&SysInfo);

    // If system has fewer than 2 logical processors, flag as VM-like
    // Many VMs are configured with 1 CPU core
    if (SysInfo.dwNumberOfProcessors < 2)
        return TRUE;;


    // ---------------- RAM CHECK ----------------
    // Queries physical memory (RAM) information
    if (!GlobalMemoryStatusEx(&MemInfo)) {

        // If API fails, print error code
        printf("[!] GlobalMemoryEx Failed %d \n", GetLastError());

        // Return FALSE because memory info couldn't be retrieved
        return FALSE;
    }

    // If total physical RAM is less than 2 GB, flag as VM-like
    // (Note: value should be in bytes, not KB or MB)
    if ((DWORD)MemInfo.ullTotalPhys < (DWORD)(2 * 1024 * 1024 * 1024)) {
        return TRUE;
    }


    // ---------------- USB HISTORY CHECK ----------------
    // Opens registry key that stores USB storage device history
    dwRegErr = RegOpenKeyExA(
        HKEY_LOCAL_MACHINE,
        "SYSTEM\\ControlSet001\\Enum\\USBSTOR",
        NULL,
        KEY_READ,
        &hKey
    );

    // If registry key cannot be opened, log error and exit
    if (dwRegErr != ERROR_SUCCESS) {
        printf("[!] RegOpenKeyExA Failed: %d | 0x%0.8X \n", dwRegErr, dwRegErr);
        return FALSE;
    }

    // Queries number of subkeys under USBSTOR (USB devices ever connected)
    dwRegErr = RegQueryInfoKeyA(
        hKey,
        NULL, NULL, NULL,
        &dwNumUSB,   // receives number of subkeys
        NULL, NULL, NULL, NULL, NULL, NULL, NULL
    );

    // If query fails, return FALSE (cannot evaluate environment)
    if (dwRegErr != ERROR_SUCCESS) {
        printf("[!] RegQueryInfoKeyA Failed: %d | 0x%0.8X \n", dwRegErr, dwRegErr);
        return FALSE;
    }

    // If fewer than 2 USB devices were ever mounted, flag as VM-like
    // Many fresh VMs have no USB history
    if (dwNumUSB < 2) {
        return TRUE;
    }

    // Close registry handle to avoid resource leak
    RegCloseKey(hKey);

    // If none of the checks triggered, assume NOT VM
    return FALSE;
}


// Detect VM based on Display resolution
BOOL CALLBACK ResolutionCallback(
    _In_ HMONITOR hMonitor,
    _In_ HDC hdcMonitor,
    _In_ LPRECT lpRect,
    _In_ LPARAM ldata
) {

    // X and Y resolution values of current monitor
    int X, Y = 0;

    // Structure that stores monitor information
    MONITORINFO MonitorInfo = { .cbSize = sizeof(MONITORINFO) };


    // Get monitor details (resolution, coordinates, etc.)
    if (!GetMonitorInfoW(hMonitor, &MonitorInfo)) {
        printf("[!] GetMonitorInfoW Failed With Error : % d \n", GetLastError());
        return FALSE;
    }

    // Calculate horizontal resolution (width)
    // right - left gives width of monitor
    X = MonitorInfo.rcMonitor.right - MonitorInfo.rcMonitor.left;

    // Calculate vertical resolution (height)
    // top - bottom gives height (may be negative depending on coordinate system)
    Y = MonitorInfo.rcMonitor.top - MonitorInfo.rcMonitor.bottom;

    // If negative values occur, convert to positive
    if (X < 0)
        X = -X;
    if (Y < 0)
        Y = -Y;

    // If resolution does NOT match common real-world values,
    // mark system as suspicious (likely VM or sandbox display config)
    if ((X != 1920 && X != 2560 && X != 1440) ||
        (Y != 1080 && Y != 1200 && Y != 1600 && Y != 900))
    {
        // Set flag passed via LPARAM to TRUE (VM detected)
        *((BOOL*)ldata) = TRUE;
    }

    // Continue enumeration of other monitors
    return TRUE;
}


// Checks Display properties.
BOOL CheckDisplayProperties() {

    // Flag indicating whether suspicious display config was found
    BOOL SandBx = FALSE;

    // Enumerate all connected monitors and run callback for each
    EnumDisplayMonitors(NULL, NULL, ResolutionCallback, (LPARAM)(&SandBx));

    // NOTE: This should return SandBx, not FALSE
    return FALSE;
}


// Process-based VM heuristic check
BOOL CheckProcesses() {

    // Array that receives process IDs (PIDs)
    DWORD dwProcesses[1024];

    // Number of bytes returned by EnumProcesses
    DWORD dwReturnLen;

    // Number of processes calculated from bytes returned
    DWORD dwNumPids = NULL;


    // Retrieve list of running processes
    if (!EnumProcesses(dwProcesses, sizeof(dwProcesses), &dwReturnLen)) {
        printf("[!] EnumProcesses Failed: %d \n", GetLastError());
        return FALSE;
    }

    // Convert byte size into number of process IDs
    // Each PID is a DWORD (4 bytes)
    dwNumPids = dwReturnLen / sizeof(DWORD);


    // If system has fewer than 65 running processes,
    // it may indicate a VM or sandbox environment
    if (dwNumPids < 65) {
        return TRUE;
    }

    // Otherwise assume normal system
    return FALSE;
}


// Main program entry
int main() {

    // Wait for user input before starting checks
    printf("[+] Press <Enter> To Start \n");
    getchar();

    printf("[+] Checking: Hardware Related Checks \n");

    // Run hardware VM detection
    if (HardwareCheck) {
        printf("[!] HardwareCheck Detected VM! \n");
    }
    else
        printf("\t[+] Passed HardwareCheck() \n");


    printf("[+] Checking: Monitor Properties \n");

    // Run display-based VM detection
    if (CheckDisplayProperties) {
        printf("[!] CheckDisplayProperties Detected VM! \n");
    }
    else
        printf("\t[+] Passed CheckDisplayProperties() \n");


    printf("[+] Checking: Processes \n");

    // Run process count heuristic
    if (CheckProcesses) {
        printf("[!] CheckProcesses Detected VM! \n");
    }
    else
        printf("\t[+] Passed CheckProcesses() \n");

    return 0;
}

Techniques.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
#include <Windows.h>
#include <stdio.h>
#include <TlHelp32.h>
#include "structs.h"

/*
	IsdebuggerPresent() API, returns TRUE if a debugger is being attached to the calling process
*/


BOOL IsDebuggerPresent1() {

	// Get address PEB (GSx60 is PEB pointer)
	PPEB pPeb = (PEB*)(__readgsqword(0x60));

	if (pPeb->BeingDebugged == 1)
		return TRUE;
	return FALSE;

}

/*
	NtQueryInformationProcess detects debugging via ProcessDebugPort & ProcessDebugObjectHandle
*/

BOOL NtQInfoProcess() {

	NTSTATUS                      STATUS = NULL;
	fnNtQueryInformationProcess   pNtQueryInformationProcess = NULL;
	DWORD64                       dwIsDebuggerPresent = NULL;
	DWORD64                       hProcessDebugObject = NULL;

	// Get Memory Address NtQueryInformationProcess from ntdll.dll
	pNtQueryInformationProcess = (fnNtQueryInformationProcess)GetProcAddress(GetModuleHandle(TEXT("NTDLL.DLL")), "NtQueryInformationProcess");


	// ProcessDebugPort Method
	STATUS = pNtQueryInformationProcess(GetCurrentProcess(), ProcessDebugPort, &dwIsDebuggerPresent, sizeof(DWORD64), NULL);
	if (STATUS != 0x0) {
		printf("[!] NtQueryInformationProcess Failed: 0x%0.8X \n", STATUS);
		return FALSE;
	}

	if (dwIsDebuggerPresent) {
		printf("[+] Debugger Detected!\n");
		return TRUE;
	}


	// ProcessDebugObjectHandle Method
	STATUS = pNtQueryInformationProcess(GetCurrentProcess(), ProcessDebugObjectHandle, &hProcessDebugObject, sizeof(DWORD64), NULL);
	if (STATUS != 0x0 && STATUS != 0xC0000353) {
		printf("[!] NtQueryInformationProcess Failed: 0x%0.8X \n", STATUS);
		return FALSE;
	}

	if (hProcessDebugObject)
		return TRUE;

	return FALSE;
}

/*
	Hardware breakpoint detection, checks if the registers dr0-3 are 0
*/

BOOL HWBP_Check() {
	CONTEXT Ctx = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };

	// Get current threadcontext
	if (!GetThreadContext(GetCurrentThread(), &Ctx)) {
		printf("[!] GetThreadContext Failed %d \n", GetLastError());
		return FALSE;
	}

	// Check Hardware Breakpoint by checking registers aren't set to 0
	if (Ctx.Dr0 || Ctx.Dr1 || Ctx.Dr2 || Ctx.Dr3) {
		printf("[+] Debugger Detected ! \n");
		return TRUE;
	}

	return FALSE;
}


/*
	Detect Debuggers Via Name (Array)
*/

WCHAR* g_BlockSoftware[5] = {
	L"x64dbg.exe",
	L"x32dbg.exe",
	L"binaryninja.exe",
	L"VsDebugConsole.exe",
	L"ida.exe"
};

BOOL BlockSoftware() {

	HANDLE hSnapshot = NULL;
	PROCESSENTRY32W		ProcEntry = { .dwSize = sizeof(PROCESSENTRY32W) };
	BOOL				bSTATE = FALSE;

	hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
	if (hSnapshot == INVALID_HANDLE_VALUE) {
		printf("[!] CreateToolHelp32Snapshot Failed %d \n", GetLastError());
		goto _End;
	}

	if (!Process32FirstW(hSnapshot, &ProcEntry)) {
		printf("[!] Process32FirstW Failed %d \n", GetLastError());
		goto _End;
	}

	do {
		for (int i = 0; i < 5; i++) {
			if (wcscmp(ProcEntry.szExeFile, g_BlockSoftware[i]) == 0) {
				wprintf(L"\t[+] Found \"%ls\" Of Pid %d \n", ProcEntry.szExeFile, ProcEntry.th32ProcessID);
				bSTATE = TRUE;
				break;
			}
		}

		if (bSTATE)
			break;
	} while (Process32NextW(hSnapshot, &ProcEntry));

_End:
	if (!hSnapshot)
		CloseHandle(hSnapshot);
	return bSTATE;
}

/*
	Detect debugging by evaluating time started and current time, if to long its being debugged GetTickCount64()
*/

BOOL TimeCheck1() {
	DWORD dwTime1, dwTime2 = 0;

	dwTime1 = GetTickCount64();
	dwTime2 = GetTickCount64();

	if ((dwTime2 - dwTime1) > 70)
		return TRUE;

	return FALSE;
}

/*
	Send message to debugger is thats succeeds debugging is happening
*/

BOOL SendMessageDbg() {

	// Make sure value is non 0 before execution
	SetLastError(1);
	OutputDebugStringW(L"N0xshell");

	if (GetLastError())
		return TRUE;
	return FALSE;
}

int main() {

	printf("[+] Press <Enter> To Start Anti Analysis Techniques! \n");
	getchar();

	// Method: IsDebuggerPresent
	printf("[+] Running: IsDebuggerPresent1 \n");
	if (IsDebuggerPresent1()) {
		printf("[!] Debugger Detected [IsDebuggerPresent1] \n");
		exit(1);
	}
	else
		printf("\t[+] IsDebuggerPresent1 Done! \n");

	// Method: NtQueryInformationProcess
	printf("[+] Running: NtQInfoProcess \n");
	if (NtQInfoProcess()) {
		printf("[!] Debugger Detected [NtQInfoProcess] \n");
		exit(1);
	}
	else
		printf("\t[+] NtQInfoProcess Done! \n");

	// Method: HWBP_Check (Thread Register check)
	printf("[+] Running: HWBP_Check \n");
	if (HWBP_Check()) {
		printf("[!] Debugger Detected [HWBP_Check] \n");
		exit(1);
	}
	else
		printf("\t[+] HWBP_Check Done \n");

	// Method: BlockSoftware Check
	printf("[+] Running: BlockSoftware \n");
	if (BlockSoftware()) {
		printf("[!] Debugger Detected [BlockSoftware] \n");
		exit(1);
	}
	else
		printf("\t[+] BlockSoftware Done \n");

	// Method: TimeCheck
	printf("[+] Running: TimeCheck1 \n");
	if (TimeCheck1()) {
		printf("[!] Debugger Detected [TimeCheck1] \n");
		exit(1);
	}
	else
		printf("\t[+] TimeCheck1 Done \n");


	printf("[+] Press <Enter> To Exit! \n");
	getchar();
	return 0;
}

SelfDeletion.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <Windows.h>
#include <stdio.h>
#include <intrin.h>

#define NEW_STREAM ":N0xshell"
#define RAND_MAX 0x7FFF

// Static -> only visible within the current translation unit.
// Uses the CPU RDRAND instruction to generate a random 32-bit value.
static unsigned int rdrand32(void) {
	UINT32 uRandomV = 0x00;

	if (_rdrand32_step(&uRandomV)) {
		return (uRandomV % (RAND_MAX + 1u));
	}

	return 0;
}

BOOL DeleteSelf(void) {

	WCHAR wcNewStream[7] = L":%x%x\x00";
	BOOL bState = FALSE;

	// Buffer that receives the fully qualified path of the current executable.
	WCHAR wcFileName[MAX_PATH * 2] = { 0x00 };

	FILE_RENAME_INFO RenameInfo = { 0 };
	RenameInfo.FileNameLength = sizeof(wcNewStream);
	RenameInfo.ReplaceIfExists = FALSE;
	RenameInfo.RootDirectory = NULL;

	FILE_DISPOSITION_INFO_EX FileDisposalInfoEx = { 0 };

	// Handle to the current executable.
	HANDLE hLocalImgFile = INVALID_HANDLE_VALUE;

	// Retrieve the fully qualified path of the current executable.
	if (GetModuleFileNameW(NULL, wcFileName, MAX_PATH * 2) == 0x00) {
		printf("[!] GetModuleFileNameW Failed: %d \n", GetLastError());
		goto _End;
	}

	// Generate a random alternate data stream name.
	swprintf(RenameInfo.FileName, MAX_PATH, wcNewStream, rdrand32(), rdrand32());

	// Open the current executable with delete access.
	if ((hLocalImgFile = CreateFileW(wcFileName, DELETE | SYNCHRONIZE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, NULL, NULL)) == INVALID_HANDLE_VALUE) {
		printf("[!] CreateFileW %d Failed: %d \n", __LINE__, GetLastError());
		return bState;
	}

	// Rename the file's alternate data stream.
	if (!SetFileInformationByHandle(hLocalImgFile, FileRenameInfo, &RenameInfo, sizeof(RenameInfo))) {
		printf("[!] SetFileInformationByHandle %d Failed: %lu\n", __LINE__, GetLastError());
		goto _End;
	}

	CloseHandle(hLocalImgFile);

	// Reopen the executable before marking it for deletion.
	if ((hLocalImgFile = CreateFileW(wcFileName, DELETE | SYNCHRONIZE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, NULL, NULL)) == INVALID_HANDLE_VALUE) {
		printf("[!] CreateFileW %d Failed: %d \n", __LINE__, GetLastError());
		goto _End;
	}

	// Configure POSIX-style delete-on-close semantics.
	FileDisposalInfoEx.Flags = FILE_DISPOSITION_FLAG_DELETE | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS;

	// Mark the file for deletion.
	if (!SetFileInformationByHandle(hLocalImgFile, FileDispositionInfoEx, &FileDisposalInfoEx, sizeof(FILE_DISPOSITION_INFO_EX))) {
		printf("[!] SetFileInformationByHandle %d Failed: %d \n", __LINE__, GetLastError());
		goto _End;
	}

	bState = TRUE;

_End:

	// Ensure any open handle is released.
	if (hLocalImgFile != INVALID_HANDLE_VALUE)
		CloseHandle(hLocalImgFile);

	return bState;
}

int main(int argc, char* argv[]) {

	if (!DeleteSelf()) {
		return -1;
	}

	printf("[+] %s Should Be Deleted \n", argv[0]);

	printf("[!] Press <Enter> To Quit \n");
	getchar();

	return 0;

}
This post is licensed under CC BY 4.0 by the author.