-
Notifications
You must be signed in to change notification settings - Fork 1
/
Process.cpp
551 lines (508 loc) · 16.3 KB
/
Process.cpp
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the LICENSE file distributed with
* this work for additional information regarding copyright ownership.
*
* Also, if exists, check the Licenses directory for information about
* third-party modules.
*
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Process.h"
#include "FileRoutines.h"
#include <Debug.h>
#include <WaitableObjects.h>
#include <VersionHelpers.h>
//-----------------------------------------------------------
#pragma pack(8)
typedef struct {
BYTE Revision;
BYTE SubAuthorityCount;
SID_IDENTIFIER_AUTHORITY IdentifierAuthority;
DWORD SubAuthority[8];
} MY_SID;
#pragma pack()
//-----------------------------------------------------------
static HRESULT QueryEnvironmentVariableInternal(_In_ LPCWSTR szVarNameW, _In_ SIZE_T nVarNameLen,
_In_opt_ MX::CStringW *lpStrDestW);
static BOOL IsWinVistaPlus();
//-----------------------------------------------------------
namespace MX {
namespace Process {
HRESULT ResolveChildProcessFileName(_Out_ CStringW &cStrFullNameW, _In_ LPCWSTR szApplicationNameW,
_In_ LPCWSTR szCommandLineW)
{
HRESULT hRes;
cStrFullNameW.Empty();
if (szApplicationNameW == NULL && szCommandLineW == NULL)
return E_INVALIDARG;
if (szApplicationNameW == NULL)
{
CStringW cStrSearchPathW, cStrExeNameW, cStrTempW;
LPCWSTR szNameStartW, szNameEndW;
SIZE_T nTempBufLen = 1024;
//NOTE: Assume szCommandLineW is the full command line
szNameStartW = szCommandLineW;
if (*szCommandLineW == L'"')
{
szNameEndW = ++szNameStartW;
while (*szNameEndW != 0 && *szNameEndW != L'"')
szNameEndW++;
}
else
{
szNameEndW = szNameStartW;
while (*((LPWORD)szNameEndW) > 32)
szNameEndW++;
}
//get the path list to check (based on https://msdn.microsoft.com/en-us/library/ms682425.aspx)
//1. The directory from which the application loaded.
hRes = FileRoutines::GetAppFolderPath(cStrSearchPathW);
//2. The current directory for the parent process.
if (SUCCEEDED(hRes))
{
RTL_OSVERSIONINFOW sOviW;
::MxMemSet(&sOviW, 0, sizeof(sOviW));
sOviW.dwOSVersionInfoSize = (DWORD)sizeof(sOviW);
::MxRtlGetVersion(&sOviW);
if (sOviW.dwMajorVersion >= 6)
{
if (FAILED(QueryEnvironmentVariableInternal(L"NoDefaultCurrentDirectoryInExePath", 34, NULL)))
{
if (cStrSearchPathW.ConcatN(L";.", 2) == FALSE)
hRes = E_OUTOFMEMORY;
}
}
}
//3. The 32-bit Windows system directory.Use the GetSystemDirectory function to get the path of this directory.
if (SUCCEEDED(hRes))
{
hRes = FileRoutines::GetWindowsSystemPath(cStrTempW);
if (SUCCEEDED(hRes))
{
if (cStrSearchPathW.ConcatN(L";", 1) == FALSE ||
cStrSearchPathW.Concat((LPCWSTR)cStrTempW) == FALSE)
{
hRes = E_OUTOFMEMORY;
}
}
}
//4. The 16-bit Windows system directory.There is no function that obtains the path of this directory, but it is
// searched.The name of this directory is System.
//5. The Windows directory.Use the GetWindowsDirectory function to get the path of this directory.
if (SUCCEEDED(hRes))
{
hRes = FileRoutines::GetWindowsPath(cStrTempW);
if (SUCCEEDED(hRes))
{
if (cStrSearchPathW.ConcatN(L";", 1) == FALSE ||
cStrSearchPathW.Concat((LPCWSTR)cStrTempW) == FALSE ||
cStrSearchPathW.ConcatN(L"\\System;", 8) == FALSE ||
cStrSearchPathW.Concat((LPCWSTR)cStrTempW) == FALSE)
{
hRes = E_OUTOFMEMORY;
}
}
}
//6. The directories that are listed in the PATH environment variable.Note that this function does not search the
// per-application path specified by the App Paths registry key.To include this per-application path in the
// search sequence, use the ShellExecute function.
if (SUCCEEDED(hRes))
{
hRes = QueryEnvironmentVariable(L"PATH", cStrTempW);
if (SUCCEEDED(hRes))
{
if (cStrSearchPathW.ConcatN(L";", 1) == FALSE ||
cStrSearchPathW.Concat((LPCWSTR)cStrTempW) == FALSE)
{
hRes = E_OUTOFMEMORY;
}
}
else if (hRes == MX_HRESULT_FROM_WIN32(ERROR_NOT_FOUND))
{
hRes = S_OK;
}
}
//alloc dest buffer
if (SUCCEEDED(hRes))
{
if (cStrTempW.EnsureBuffer(nTempBufLen + 1) == FALSE)
hRes = E_OUTOFMEMORY;
}
//process entries (based on https://msdn.microsoft.com/en-us/library/ms682425.aspx)
while (SUCCEEDED(hRes))
{
if (cStrExeNameW.CopyN(szNameStartW, (SIZE_T)(szNameEndW-szNameStartW)) != FALSE)
{
SIZE_T nRetLen;
DWORD dwAttr;
//check this entry
while (SUCCEEDED(hRes))
{
nRetLen = ::SearchPathW((LPCWSTR)cStrSearchPathW, (LPCWSTR)cStrExeNameW, L".exe", (DWORD)nTempBufLen,
(LPWSTR)cStrTempW, NULL);
if (nRetLen == 0 || nRetLen < nTempBufLen-2)
{
((LPWSTR)cStrTempW)[nRetLen] = 0;
break;
}
nTempBufLen = nRetLen + 256;
if (cStrTempW.EnsureBuffer(nTempBufLen + 1) == FALSE)
hRes = E_OUTOFMEMORY;
}
if (SUCCEEDED(hRes) && nRetLen > 0)
{
dwAttr = ::GetFileAttributesW((LPCWSTR)cStrTempW);
if (dwAttr != INVALID_FILE_ATTRIBUTES && (dwAttr & FILE_ATTRIBUTE_DIRECTORY) == 0)
{
cStrFullNameW.Attach(cStrTempW.Detach()); //GOT!
break;
}
}
}
else
{
hRes = E_OUTOFMEMORY;
}
//if we reach here, then no valid name was found and we must advance to next portion
if (SUCCEEDED(hRes))
{
if (*szNameEndW == 0 || (szApplicationNameW != NULL && *szApplicationNameW == L'"'))
{
hRes = MX_E_FileNotFound;
}
else
{
szNameEndW++;
while (*szNameEndW != 0 && *szNameEndW != L' ' && *szNameEndW != L'\t')
szNameEndW++;
}
}
}
//at this point we have a name or an error
}
else
{
HANDLE hFile;
//don't bother in checking if the passed name is a directory instead of a file, we don't care because the latter
//CreateProcess will fail
hFile = ::CreateFileW(szApplicationNameW, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != NULL && hFile != INVALID_HANDLE_VALUE)
{
hRes = FileRoutines::GetFileNameFromHandle(hFile, cStrFullNameW);
::MxNtClose(hFile);
}
else
{
hRes = MX_HRESULT_FROM_LASTERROR();
}
}
//convert NT paths to DOS
if (SUCCEEDED(hRes))
hRes = FileRoutines::ConvertToWin32(cStrFullNameW);
//convert to long path
if (SUCCEEDED(hRes))
hRes = FileRoutines::ConvertToLongPath(cStrFullNameW);
//done
return hRes;
}
HRESULT QueryEnvironmentVariable(_In_z_ LPCWSTR szVarNameW, _Inout_ CStringW &cStrDestW)
{
SIZE_T nVarNameLen;
cStrDestW.Empty();
if (szVarNameW == NULL)
return E_POINTER;
if (*szVarNameW == L'%')
szVarNameW++;
nVarNameLen = StrLenW(szVarNameW);
if (nVarNameLen > 0 && szVarNameW[nVarNameLen - 1] == L'%')
nVarNameLen--;
if (nVarNameLen == 0)
return E_INVALIDARG;
return QueryEnvironmentVariableInternal(szVarNameW, nVarNameLen, &cStrDestW);
}
HRESULT _ExpandEnvironmentStrings(_Inout_ CStringW &cStrW)
{
CStringW cStrTempW;
SIZE_T nOfs;
LPCWSTR sW, szStartW;
HRESULT hRes;
sW = (LPCWSTR)cStrW;
while (*sW != 0)
{
if (*sW == L'%')
{
szStartW = sW++;
while (*sW != 0 && *sW != L'%')
sW++;
if (*sW == L'%')
{
//replace
sW++;
hRes = QueryEnvironmentVariableInternal(szStartW + 1, (SIZE_T)(sW - szStartW) - 2, &cStrTempW);
if (SUCCEEDED(hRes))
{
nOfs = (SIZE_T)(szStartW - (LPCWSTR)cStrW);
cStrW.Delete(nOfs, (SIZE_T)(sW - szStartW));
if (cStrW.Insert((LPCWSTR)cStrTempW, nOfs) == FALSE)
return E_OUTOFMEMORY;
}
else if (FAILED(hRes) && hRes != MX_E_NotFound)
{
return hRes;
}
//if not found, leave the %VAR% as the original ExpandEnvironmentStrings API
}
}
else
{
sW++;
}
}
//done
return S_OK;
}
HRESULT GetProcessMembershipType(_Out_ Process::eTokenGetMembershipType &nType)
{
HANDLE hToken;
HRESULT hRes;
nType = eTokenGetMembershipType::LimitedUser;
if (::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY | TOKEN_DUPLICATE, &hToken) != FALSE)
{
hRes = GetTokenMembershipType(hToken, nType);
::CloseHandle(hToken);
}
else
{
hRes = MX_HRESULT_FROM_LASTERROR();
}
return hRes;
}
HRESULT GetThreadMembershipType(_Out_ Process::eTokenGetMembershipType &nType)
{
HANDLE hToken;
HRESULT hRes;
nType = eTokenGetMembershipType::LimitedUser;
if (::OpenThreadToken(::GetCurrentThread(), TOKEN_QUERY | TOKEN_DUPLICATE, TRUE, &hToken) != FALSE)
{
hRes = GetTokenMembershipType(hToken, nType);
::CloseHandle(hToken);
}
else
{
hRes = MX_HRESULT_FROM_LASTERROR();
}
return hRes;
}
HRESULT GetTokenMembershipType(_In_ HANDLE hToken, _Out_ Process::eTokenGetMembershipType &nType)
{
static const MY_SID sLocalSystemSID = {
SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_LOCAL_SYSTEM_RID }
};
static const MY_SID sAdminsSID = {
SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS }
};
BOOL b;
DWORD dw;
HANDLE hTokenToCheck = NULL;
HRESULT hRes;
nType = Process::eTokenGetMembershipType::LimitedUser;
if (::DuplicateToken(hToken, SecurityIdentification, &hTokenToCheck) == FALSE)
return MX_HRESULT_FROM_LASTERROR();
//check if system account
b = FALSE;
if (::CheckTokenMembership(hTokenToCheck, (PSID)&sLocalSystemSID, &b) != FALSE && b != FALSE)
{
nType = eTokenGetMembershipType::SystemAccount;
hRes = S_OK;
goto done;
}
//on Vista+, check if we are elevated
if (IsWinVistaPlus() != FALSE)
{
TOKEN_ELEVATION sTokElev;
TOKEN_ELEVATION_TYPE sTokElevType;
::MxMemSet(&sTokElev, 0, sizeof(sTokElev));
if (::GetTokenInformation(hTokenToCheck, TokenElevation, &sTokElev, (DWORD)sizeof(sTokElev), &dw) != FALSE &&
sTokElev.TokenIsElevated != 0)
{
nType = eTokenGetMembershipType::AdministratorsGroupAndElevated;
hRes = S_OK;
goto done;
}
//if we are not elevated, lookup for the linked token (if exists) and check if it belongs to administrators group
::MxMemSet(&sTokElevType, 0, sizeof(sTokElevType));
if (::GetTokenInformation(hToken, TokenElevationType, &sTokElevType, (DWORD)sizeof(sTokElevType), &dw) != FALSE &&
sTokElevType == TokenElevationTypeLimited)
{
HANDLE hLinkedToken;
hLinkedToken = NULL;
if (::GetTokenInformation(hToken, TokenLinkedToken, &hLinkedToken, (DWORD)sizeof(hLinkedToken), &dw) != FALSE &&
hLinkedToken != NULL)
{
::CloseHandle(hTokenToCheck);
hTokenToCheck = NULL;
if (::DuplicateToken(hLinkedToken, SecurityIdentification, &hTokenToCheck) == FALSE)
{
hRes = MX_HRESULT_FROM_LASTERROR();
::CloseHandle(hLinkedToken);
goto done;
}
::CloseHandle(hLinkedToken);
}
}
//check if token is member of the administrators group
b = FALSE;
if (::CheckTokenMembership(hTokenToCheck, (PSID)&sAdminsSID, &b) != FALSE && b != FALSE)
{
nType = eTokenGetMembershipType::AdministratorsGroup;
hRes = S_OK;
goto done;
}
}
else
{
//on XP, check if we are a member of the administrators group
b = FALSE;
if (::CheckTokenMembership(hTokenToCheck, (PSID)&sAdminsSID, &b) != FALSE && b != FALSE)
{
nType = eTokenGetMembershipType::AdministratorsGroupAndElevated;
hRes = S_OK;
goto done;
}
}
hRes = S_FALSE;
done:
if (hTokenToCheck != NULL)
::CloseHandle(hTokenToCheck);
return hRes;
}
HRESULT EnablePrivilege(_In_z_ LPCWSTR szPrivilegeW)
{
HANDLE hToken;
TOKEN_PRIVILEGES sPriv;
HRESULT hRes;
if (szPrivilegeW == NULL)
return E_POINTER;
if (*szPrivilegeW == 0)
return E_INVALIDARG;
hRes = S_OK;
if (::OpenProcessToken(::GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken) != FALSE)
{
::MxMemSet(&sPriv, 0, sizeof(sPriv));
if (::LookupPrivilegeValueW(NULL, szPrivilegeW, &(sPriv.Privileges[0].Luid)) != FALSE)
{
sPriv.PrivilegeCount = 1;
sPriv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (::AdjustTokenPrivileges(hToken, FALSE, &sPriv, (DWORD)sizeof(sPriv), NULL, NULL) == FALSE)
{
hRes = MX_HRESULT_FROM_LASTERROR();
//DebugPrint("EnableProcessPrivileges/AdjustTokenPrivileges 0x%08X\n", hRes);
}
}
else
{
hRes = MX_HRESULT_FROM_LASTERROR();
//DebugPrint("EnableProcessPrivileges/LookupPrivilegeValueW 0x%08X\n", hRes);
}
::CloseHandle(hToken);
}
else
{
hRes = MX_HRESULT_FROM_LASTERROR();
//DebugPrint("EnableProcessPrivileges/OpenProcessToken 0x%08X\n", hRes);
}
return hRes;
}
}; //Process
}; //MX
//-----------------------------------------------------------
static HRESULT QueryEnvironmentVariableInternal(_In_ LPCWSTR szVarNameW, _In_ SIZE_T nVarNameLen,
_In_opt_ MX::CStringW *lpStrDestW)
{
LPBYTE lpPeb, lpUserProcParams;
PRTL_CRITICAL_SECTION lpCS;
LPCWSTR szEnvW, szNameStartW;
HRESULT hRes;
MX_ASSERT(szVarNameW != NULL);
if (lpStrDestW != NULL)
lpStrDestW->Empty();
#if defined(_M_IX86)
lpPeb = (LPBYTE)__readfsdword(0x30); //get PEB from the TIB
lpUserProcParams = *((LPBYTE*)(lpPeb+0x10)); //PRTL_USER_PROCESS_PARAMETERS
lpCS = *((PRTL_CRITICAL_SECTION*)(lpPeb+0x1C)); //PEB's critical section
#elif defined(_M_X64)
LPBYTE lpPtr = (LPBYTE)__readgsqword(0x30); //get TEB
lpPeb = *((LPBYTE*)(lpPtr+0x60));
lpUserProcParams = *((LPBYTE*)(lpPeb+0x20)); //PRTL_USER_PROCESS_PARAMETERS
lpCS = *((PRTL_CRITICAL_SECTION*)(lpPeb+0x38)); //PEB's critical section
#endif
//lock PEB
if (lpCS != NULL)
::MxRtlEnterCriticalSection(lpCS);
//get environment variables string
hRes = MX_E_NotFound;
if (lpUserProcParams != NULL)
{
#if defined(_M_IX86)
szEnvW = *((LPCWSTR*)(lpUserProcParams+0x48));
#elif defined(_M_X64)
szEnvW = *((LPCWSTR*)(lpUserProcParams+0x80));
#endif
if (szEnvW != NULL)
{
//parse environment variables string
while (*szEnvW != 0)
{
szNameStartW = szEnvW;
while (*szEnvW != 0 && *szEnvW != L'=')
szEnvW++;
//check this name
if ((SIZE_T)(szEnvW-szNameStartW) == nVarNameLen &&
MX::StrNCompareW(szVarNameW, szNameStartW, nVarNameLen, TRUE) == 0)
{
hRes = S_OK;
if (*szEnvW == L'=' && lpStrDestW != NULL)
{
if (lpStrDestW->Copy(szEnvW+1) == FALSE)
hRes = E_OUTOFMEMORY;
}
break;
}
//skip until next
if (*szEnvW == L'=')
szEnvW++;
while (*szEnvW != 0)
szEnvW++;
szEnvW++; //skip end-of-var
}
}
}
//unlock PEB
if (lpCS != NULL)
::MxRtlLeaveCriticalSection(lpCS);
//done
return hRes;
}
static BOOL IsWinVistaPlus()
{
static LONG volatile nIsWinVistaPlus = -1;
LONG nIsWinVistaPlusLocal;
nIsWinVistaPlusLocal = __InterlockedRead(&nIsWinVistaPlus);
if (nIsWinVistaPlusLocal < 0)
{
nIsWinVistaPlusLocal = ::IsWindowsVistaOrGreater() ? 1 : 0;
_InterlockedCompareExchange(&nIsWinVistaPlus, nIsWinVistaPlusLocal, -1);
}
return (nIsWinVistaPlusLocal == 1) ? TRUE : FALSE;
}