-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathpatchapi.cpp
More file actions
475 lines (418 loc) · 12.8 KB
/
patchapi.cpp
File metadata and controls
475 lines (418 loc) · 12.8 KB
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
/*! \file patchapi.cpp
\author Ivan Shcherbakov (Bazis)
$Id: patchapi.cpp,v 1.8 2009-12-31 13:06:41 Bazis Exp $
\brief Contains implementation for API simplifying VM patching.
*/
#include "stdafx.h"
#include "patchapi.h"
#include "findproc.h"
#include <TlHelp32.h>
#include <assert.h>
#include "loader.h"
#include "hook64.h"
#include "32to64.h"
#include <bzshlp/Win32/wow64.h>
#include <ShellApi.h>
#include <bzscore/datetime.h>
#include <atlbase.h>
#include <atlcom.h>
#include <atlcomcli.h>
#include <atlsafe.h>
#include "../vkdversion.h"
#include "VBoxCmdLine.h"
#include "VMAPI/VirtualBox.h"
#include "../rpcdispatch/ServiceCommandProtocol.h"
#include "../rpcdispatch/rpcdisp.h"
#include "../rpcdispatch/kdcomdisp.h"
BazisLib::WOW64APIProvider g_Wow64;
static bool IsRundll64Required(unsigned PID)
{
#ifdef _WIN64
return false;
#else
return g_Wow64.IsWow64Process() && !g_Wow64.IsWow64Process(PID);
#endif
}
extern HMODULE g_hThisDll;
//! Enables debugging privilege for calling process. Required to debug system services.
void EnableDebugPrivilege()
{
HANDLE hToken;
LUID sedebugnameValue;
TOKEN_PRIVILEGES tkp;
OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken);
LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &sedebugnameValue);
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Luid = sedebugnameValue;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken, FALSE, &tkp, sizeof(tkp), NULL, NULL);
CloseHandle(hToken);
}
HANDLE CreateVMSessionList()
{
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
if (hSnap == INVALID_HANDLE_VALUE)
return INVALID_HANDLE_VALUE;
PROCESSENTRY32 entry = {0, };
entry.dwSize = sizeof(entry);
//First process should always be the system process. That way, we can simply ignore it and use Process32Next() every time we want to find a next session.
Process32First(hSnap, &entry);
assert(!_tcsstr(entry.szExeFile, _T("vmware-vmx.exe")));
assert(!_tcsstr(entry.szExeFile, _T("vmware-vmx-debug.exe")));
assert(!_tcsstr(entry.szExeFile, _T("vmware-vmx-stats.exe")));
assert(!_tcsstr(entry.szExeFile, _T("VirtualBox.exe")));
return hSnap;
}
void CloseVMSessionList( HANDLE hList )
{
CloseHandle(hList);
}
unsigned GetNextVMSessionPID( HANDLE hList )
{
return GetNextVMSessionPIDEx(hList, NULL);
}
unsigned GetNextVMSessionPIDEx( HANDLE hList, VMType *pVMType )
{
TCHAR *tszNames[] = {_T("VirtualBox.exe"), _T("vmware-vmx.exe"), _T("vmware-vmx-debug.exe"), _T("vmware-vmx-stats.exe")};
unsigned PID = 0;
unsigned idxMatch = 0;
for (;;)
{
PID = FindProcessByNames(hList, tszNames, __countof(tszNames), false, &idxMatch);
if ((PID == -1) || !PID)
return 0;
if (idxMatch)
break;
//Skip VirtualBox processes not running any VMs
wchar_t sessionName[MAX_PATH];
if (GetVMSessionNameW(PID, sessionName, __countof(sessionName)))
break;
}
if (pVMType)
{
if (!PID)
*pVMType = kVMUnknown;
{
BazisLib::WOW64APIProvider wow;
#ifdef _WIN64
bool Is64 = !wow.IsWow64Process(PID);
#else
bool Is64 = wow.IsWow64Process() && !wow.IsWow64Process(PID);
#endif
if (idxMatch)
*pVMType = Is64 ? kVMWare64 : kVMWare32;
else
*pVMType = Is64 ? kVBox64 : kVBox32;
}
}
return PID;
}
unsigned SessionNameFromVMWareCmdLineW(const wchar_t *pszCmdLineConst, wchar_t *pName, size_t MaxNameLength)
{
BazisLib::DynamicStringW cmdLineCopy = pszCmdLineConst;
wchar_t *pszCmdLine = const_cast<wchar_t *>(cmdLineCopy.c_str());
wchar_t *pVmx = wcsstr(pszCmdLine, L".vmx");
if (!pVmx)
return 0;
for (;;)
{
wchar_t *p = wcsstr(pVmx + 1, L".vmx");
if (!p)
break;
pVmx = p;
}
if (pVmx)
pVmx[0] = 0;
wchar_t *end = wcsrchr(pszCmdLine, '\\');
if (!end)
return 0;
end[0] = 0;
wchar_t *start = wcsrchr(pszCmdLine, '\\');
if (!start)
return 0;
else
start++;
size_t todo = end - start;
if (todo >= MaxNameLength)
todo = MaxNameLength - 1;
memcpy(pName, start, todo * sizeof(wchar_t));
pName[todo] = 0;
return (unsigned)todo;
}
#include "cmdline.h"
unsigned SessionNameFromVMCmdLineW(const RemoteProcessInfo &info, wchar_t *pName, size_t MaxNameLength)
{
int argc = 0;
LPWSTR *pArgs = CommandLineToArgvW(info.CommandLine.c_str(), &argc);
if (!pArgs)
return 0;
BazisLib::String exeName;
if (argc && pArgs[0])
exeName = pArgs[0];
LocalFree(pArgs);
pArgs = NULL;
if (wcsstr(exeName.c_str(), L"vmware-vmx.exe") || wcsstr(exeName.c_str(), L"vmware-vmx-debug.exe") || wcsstr(exeName.c_str(), L"vmware-vmx-stats.exe"))
return SessionNameFromVMWareCmdLineW(info.CommandLine.c_str(), pName, MaxNameLength);
else if ((wcsstr(exeName.c_str(), L"VirtualBox.exe") || wcsstr(info.EXEName.c_str(), L"VirtualBox.exe")))
return VBoxCmdLineToVMNameW(info, pName, MaxNameLength);
else
return 0;
}
#include "cmdline.h"
unsigned GetVMSessionNameW(unsigned PID, wchar_t *pName, size_t MaxNameLength)
{
#ifndef _WIN64
if (IsRundll64Required(PID))
{
return (unsigned)Call64BitKDCLIENT(kGetVMSessionName, PID, pName, MaxNameLength);
}
#endif
extern HMODULE g_hThisDll;
EnableDebugPrivilege();
if (!PID || !pName)
return 0;
return SessionNameFromVMCmdLineW(GetRemoteProcessInfo(PID), pName, MaxNameLength);
}
bool IsVMSessionPatched( unsigned PID )
{
#ifndef _WIN64
if (IsRundll64Required(PID))
{
return (Call64BitKDCLIENT(kIsSessionPatched, PID) == 1);
}
#endif
if (GetRemoteModuleHandle64Aware(PID, _T("VBoxKD.dll")) || GetRemoteModuleHandle64Aware(PID, _T("VBoxKD64.dll")))
return true;
RemoteDllLoader ldr(g_hThisDll, false);
return (ldr.FindLibraryInProcess(PID, true) != 0);
}
static bool s_bUserWarnedAboutVBox = false;
static bool s_bUserWarnedAboutVersion = false;
HANDLE StartPatcherThread( unsigned PID, DWORD *pPatcherThreadID = NULL)
{
EnableDebugPrivilege();
if (GetRemoteModuleHandle64Aware(PID, _T("VBoxDD.dll")))
{
//We are inside VirtualBox
#ifdef _WIN64
if (GetRemoteModuleHandle64Aware(PID, _T("kdclient64.dll")))
#else
if (GetRemoteModuleHandle64Aware(PID, _T("kdclient.dll")))
#endif
return 0;
if (!s_bUserWarnedAboutVBox)
{
s_bUserWarnedAboutVBox = true;
MessageBox(0, _T("VirtualKD cannot patch VirtualBox on-the-fly.\r\nPlease register the VirtualKD device for VirtualBox by running \"regsvr32 VBoxKD64.dll\". If this does not help, close all instances of VirtualBox and terminate VBoxSVC.exe and try again."),
_T("VirtualKD"),
MB_ICONWARNING | MB_TASKMODAL);
}
return INVALID_HANDLE_VALUE;
}
RemoteDllLoader ldr(g_hThisDll, false);
if (ldr.FindLibraryInProcess(PID))
return NULL;
return ldr.InitiateDLLLoading(PID, pPatcherThreadID);
}
HANDLE StartUnpatcherThread( unsigned PID, DWORD *pPatcherThreadID = NULL)
{
if (GetRemoteModuleHandle64Aware(PID, _T("VBoxDD0.dll")))
return INVALID_HANDLE_VALUE;
EnableDebugPrivilege();
RemoteDllLoader ldr(g_hThisDll, false);
if (!ldr.FindLibraryInProcess(PID))
return NULL;
return ldr.InitiateDLLUnloading(PID, true, pPatcherThreadID);
}
static bool DoSynchronousThreadOperation(HANDLE hThread)
{
if (hThread == NULL)
return true;
else if (hThread == INVALID_HANDLE_VALUE)
return false;
else
{
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
DWORD dwCode = 0;
GetExitCodeThread(hThread, &dwCode);
return (dwCode != 0);
}
}
bool PatchVMSessionIfNeeded(unsigned PID)
{
#ifndef _WIN64
if (IsRundll64Required(PID))
{
return (Call64BitKDCLIENT(kPatchAndWait, PID) != 0);
}
#endif
return DoSynchronousThreadOperation(StartPatcherThread(PID));
}
bool UnpatchVMSessionIfNeeded(unsigned PID)
{
#ifndef _WIN64
if (IsRundll64Required(PID))
{
return (Call64BitKDCLIENT(kUnpatchAndWait, PID) != 0);
}
#endif
return DoSynchronousThreadOperation(StartUnpatcherThread(PID));
}
HTHREAD StartVMSessionPatching(unsigned PID)
{
#ifndef _WIN64
if (IsRundll64Required(PID))
{
DWORD dwID = (DWORD)Call64BitKDCLIENT(kStartVMSessionPatching, PID);
EnableDebugPrivilege();
if(!dwID)
return 0;
else if (dwID == -1)
return INVALID_HANDLE_VALUE;
else
{
HANDLE h = OpenThread(THREAD_ALL_ACCESS, FALSE, dwID);
if (!h || (h == INVALID_HANDLE_VALUE)) //Thread already finished
return 0;
return h;
}
}
#endif
return StartPatcherThread(PID);
}
HTHREAD StartVMSessionUnpatching(unsigned PID)
{
#ifndef _WIN64
if (IsRundll64Required(PID))
{
DWORD dwID = (DWORD)Call64BitKDCLIENT(kStartVMSessionUnpatching, PID);
EnableDebugPrivilege();
if(!dwID)
return 0;
else if (dwID == -1)
return INVALID_HANDLE_VALUE;
else
{
HANDLE h = OpenThread(THREAD_ALL_ACCESS, FALSE, dwID);
if (!h || (h == INVALID_HANDLE_VALUE)) //Thread already finished
return 0;
return h;
}
}
#endif
return StartUnpatcherThread(PID);
}
int FindVMSessionByNameW( const wchar_t *pName )
{
if (!pName)
return 0;
wchar_t wsz[512] = {0,};
HANDLE hSnap = CreateVMSessionList();
if (hSnap == INVALID_HANDLE_VALUE)
return 0;
int PID = 0;
while (PID = GetNextVMSessionPID(hSnap))
{
if (!GetVMSessionNameW(PID, wsz, sizeof(wsz)/sizeof(wsz[0])))
continue;
if (!_wcsicmp(wsz, pName))
break;
}
CloseVMSessionList(hSnap);
return PID;
}
unsigned GetVMPipeNameW(unsigned PID, wchar_t *pName, size_t MaxNameLength, bool TryReconstructingIfNotAvailable)
{
if (!pName || !PID)
return 0;
pName[0] = 0;
TCHAR tszMappingName[MAX_PATH];
_sntprintf_s(tszMappingName, __countof(tszMappingName), _TRUNCATE, tszMappingNameFormat, PID);
//HANDLE hMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READONLY, 0, sizeof(KdClientStatus), tszMappingName);
HANDLE hMapping = OpenFileMapping(FILE_MAP_READ, FALSE, tszMappingName);
bool bOldVersion = false;
KdClientStatus *pStatus = (KdClientStatus *)MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, sizeof(KdClientStatus));
if (!pStatus)
{
bOldVersion = true;
pStatus = (KdClientStatus *)MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
}
BazisLib::DateTime startTime = BazisLib::DateTime::Now();
if ((hMapping == INVALID_HANDLE_VALUE) || !pStatus)
{
if (hMapping != INVALID_HANDLE_VALUE)
CloseHandle(hMapping);
if (!TryReconstructingIfNotAvailable)
return 0;
TCHAR tszSession[MAX_PATH] = {0,};
GetVMSessionNameW(PID, tszSession, __countof(tszSession));
if (!tszSession[0])
return 0;
unsigned len = _snwprintf(pName, MaxNameLength, L"\\\\.\\pipe\\kd_%s", tszSession);
for (int i = 0; pName[i]; i++)
if (pName[i] == ' ')
pName[i] = '_';
return len;
}
unsigned len = (unsigned)wcslen(pStatus->PipeName);
wcsncpy_s(pName, MaxNameLength, pStatus->PipeName, _TRUNCATE);
if ((bOldVersion || (pStatus->HostSideDLLVersion != VIRTUALKD_VER_INT)) && !s_bUserWarnedAboutVersion)
{
unsigned oldVersion = 0, newVersion = VIRTUALKD_VER_INT;
if (pStatus)
oldVersion = pStatus->HostSideDLLVersion;
oldVersion >>= 16;
newVersion >>= 16;
s_bUserWarnedAboutVersion = true;
MessageBox(0,
BazisLib::String::sFormat(_T("One of the virtual machines has an old version of KDCLIENT.DLL/VBOXDD.DLL loaded (%d.%d.%d expected, %d.%d.%d found). Please install the latest file versions, as described on VirtualKD website, and restart your virtual machines."),
(oldVersion >> 12) & 0x0F,
(oldVersion >> 8) & 0x0F,
(oldVersion >> 4) & 0x0F,
(newVersion >> 12) & 0x0F,
(newVersion >> 8) & 0x0F,
(newVersion >> 4) & 0x0F).c_str(),
_T("VirtualKD"),
MB_ICONWARNING | MB_TASKMODAL);
}
UnmapViewOfFile(pStatus);
CloseHandle(hMapping);
return len;
}
bool ForceInstantBreakInByPID(unsigned PID)
{
wchar_t wszName[512];
if (!GetVMPipeNameW(PID, wszName, _countof(wszName), true))
return false;
return ForceInstantBreakInByPipeNameW(wszName);
}
bool RevertVMToLastSnapshotByPID(unsigned PID)
{
wchar_t wszName[512];
if (!GetVMPipeNameW(PID, wszName, _countof(wszName), true))
return false;
return RevertVMToLastSnapshotByPipeNameW(wszName);
}
static HRESULT ExecuteServiceCommand(const wchar_t *pPipeName, ServiceProtocolCommand cmd)
{
wchar_t wszName[512];
_snwprintf(wszName, _countof(wszName), L"%s%s", pPipeName, VIRTUALKD_SERVICE_PROTOCOL_PIPE_SUFFIX);
ServiceProtocolPacket packet;
packet.Command = cmd;
ServiceProtocolReply reply;
DWORD dwDone = 0;
if (!CallNamedPipe(wszName, &packet, sizeof(packet), &reply, sizeof(reply), &dwDone, 100))
return E_FAIL;
if (dwDone != sizeof(reply))
return E_FAIL;
return reply.Status;
}
bool ForceInstantBreakInByPipeNameW(const wchar_t *pPipeName)
{
return SUCCEEDED(ExecuteServiceCommand(pPipeName, kInstantBreak));
}
bool RevertVMToLastSnapshotByPipeNameW(const wchar_t *pPipeName)
{
return SUCCEEDED(ExecuteServiceCommand(pPipeName, kRevertToLastSnapshot));
}