forked from shadowsocks/shadowsocks-windows
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProcessEnvironment.cs
713 lines (609 loc) · 23.1 KB
/
ProcessEnvironment.cs
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
/* ***************************************************************************
The component allows to read the environment variables of another process
running in a Windows system.
History:
- v1.2.ss Add GetCommandLine for convenience.
- v1.2: Added support for inspection of 64 bit processes from 32 bit host
- v1.1: Fixed issue with environment block size detection
- v1.0: Initial
******************************************************************************
The MIT License (MIT)
Copyright (c) 2011-2014 Oleksiy Gapotchenko
Copyright (c) 2018 Shadowsocks Project
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*************************************************************************** */
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace Shadowsocks.Test
{
static class ProcessEnvironment
{
public static StringDictionary ReadEnvironmentVariables(this Process process)
{
return _GetEnvironmentVariablesCore(process.Handle);
}
public static StringDictionary TryReadEnvironmentVariables(this Process process)
{
try
{
return ReadEnvironmentVariables(process);
}
catch
{
return null;
}
}
public static string GetCommandLine(this Process process)
{
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + process.Id))
using (ManagementObjectCollection objects = searcher.Get())
{
return objects.Cast<ManagementBaseObject>().SingleOrDefault()?["CommandLine"]?.ToString();
}
}
/// <summary>
/// Universal pointer.
/// </summary>
struct UniPtr
{
public UniPtr(IntPtr p)
{
Value = p.ToInt64();
Size = IntPtr.Size;
}
public UniPtr(long p)
{
Value = p;
Size = sizeof(long);
}
public long Value;
public int Size;
public static implicit operator IntPtr(UniPtr p)
{
return new IntPtr(p.Value);
}
public static implicit operator UniPtr(IntPtr p)
{
return new UniPtr(p);
}
public override string ToString()
{
return Value.ToString();
}
public bool FitsInNativePointer
{
get
{
return Size <= IntPtr.Size;
}
}
public bool CanBeRepresentedByNativePointer
{
get
{
int actualSize = Size;
if (actualSize == 8)
{
if (Value >> 32 == 0)
actualSize = 4;
}
return actualSize <= IntPtr.Size;
}
}
public long ToInt64()
{
return Value;
}
}
static StringDictionary _GetEnvironmentVariablesCore(IntPtr hProcess)
{
var penv = _GetPenv(hProcess);
const int maxEnvSize = 32767;
byte[] envData;
if (penv.CanBeRepresentedByNativePointer)
{
int dataSize;
if (!_HasReadAccess(hProcess, penv, out dataSize))
throw new Exception("Unable to read environment block.");
if (dataSize > maxEnvSize)
dataSize = maxEnvSize;
envData = new byte[dataSize];
var res_len = IntPtr.Zero;
bool b = WindowsApi.ReadProcessMemory(
hProcess,
penv,
envData,
new IntPtr(dataSize),
ref res_len);
if (!b || (int)res_len != dataSize)
throw new Exception("Unable to read environment block data.");
}
else if (penv.Size == 8 && IntPtr.Size == 4)
{
// Accessing 64 bit process under 32 bit host.
int dataSize;
if (!_HasReadAccessWow64(hProcess, penv.ToInt64(), out dataSize))
throw new Exception("Unable to read environment block with WOW64 API.");
if (dataSize > maxEnvSize)
dataSize = maxEnvSize;
envData = new byte[dataSize];
long res_len = 0;
int result = WindowsApi.NtWow64ReadVirtualMemory64(
hProcess,
penv.ToInt64(),
envData,
dataSize,
ref res_len);
if (result != WindowsApi.STATUS_SUCCESS || res_len != dataSize)
throw new Exception("Unable to read environment block data with WOW64 API.");
}
else
{
throw new Exception("Unable to access process memory due to unsupported bitness cardinality.");
}
return _EnvToDictionary(envData);
}
static StringDictionary _EnvToDictionary(byte[] env)
{
var result = new StringDictionary();
int len = env.Length;
if (len < 4)
return result;
int n = len - 3;
for (int i = 0; i < n; ++i)
{
byte c1 = env[i];
byte c2 = env[i + 1];
byte c3 = env[i + 2];
byte c4 = env[i + 3];
if (c1 == 0 && c2 == 0 && c3 == 0 && c4 == 0)
{
len = i + 3;
break;
}
}
char[] environmentCharArray = Encoding.Unicode.GetChars(env, 0, len);
for (int i = 0; i < environmentCharArray.Length; i++)
{
int startIndex = i;
while ((environmentCharArray[i] != '=') && (environmentCharArray[i] != '\0'))
{
i++;
}
if (environmentCharArray[i] != '\0')
{
if ((i - startIndex) == 0)
{
while (environmentCharArray[i] != '\0')
{
i++;
}
}
else
{
string str = new string(environmentCharArray, startIndex, i - startIndex);
i++;
int num3 = i;
while (environmentCharArray[i] != '\0')
{
i++;
}
string str2 = new string(environmentCharArray, num3, i - num3);
result[str] = str2;
}
}
}
return result;
}
static bool _TryReadIntPtr32(IntPtr hProcess, IntPtr ptr, out IntPtr readPtr)
{
bool result;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
}
finally
{
int dataSize = sizeof(Int32);
var data = Marshal.AllocHGlobal(dataSize);
IntPtr res_len = IntPtr.Zero;
bool b = WindowsApi.ReadProcessMemory(
hProcess,
ptr,
data,
new IntPtr(dataSize),
ref res_len);
readPtr = new IntPtr(Marshal.ReadInt32(data));
Marshal.FreeHGlobal(data);
if (!b || (int)res_len != dataSize)
result = false;
else
result = true;
}
return result;
}
static bool _TryReadIntPtr(IntPtr hProcess, IntPtr ptr, out IntPtr readPtr)
{
bool result;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
}
finally
{
int dataSize = IntPtr.Size;
var data = Marshal.AllocHGlobal(dataSize);
IntPtr res_len = IntPtr.Zero;
bool b = WindowsApi.ReadProcessMemory(
hProcess,
ptr,
data,
new IntPtr(dataSize),
ref res_len);
readPtr = Marshal.ReadIntPtr(data);
Marshal.FreeHGlobal(data);
if (!b || (int)res_len != dataSize)
result = false;
else
result = true;
}
return result;
}
static bool _TryReadIntPtrWow64(IntPtr hProcess, long ptr, out long readPtr)
{
bool result;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
}
finally
{
int dataSize = sizeof(long);
var data = Marshal.AllocHGlobal(dataSize);
long res_len = 0;
int status = WindowsApi.NtWow64ReadVirtualMemory64(
hProcess,
ptr,
data,
dataSize,
ref res_len);
readPtr = Marshal.ReadInt64(data);
Marshal.FreeHGlobal(data);
if (status != WindowsApi.STATUS_SUCCESS || res_len != dataSize)
result = false;
else
result = true;
}
return result;
}
static UniPtr _GetPenv(IntPtr hProcess)
{
int processBitness = _GetProcessBitness(hProcess);
if (processBitness == 64)
{
if (Environment.Is64BitProcess)
{
// Accessing 64 bit process under 64 bit host.
IntPtr pPeb = _GetPeb64(hProcess);
IntPtr ptr;
if (!_TryReadIntPtr(hProcess, pPeb + 0x20, out ptr))
throw new Exception("Unable to read PEB.");
IntPtr penv;
if (!_TryReadIntPtr(hProcess, ptr + 0x80, out penv))
throw new Exception("Unable to read RTL_USER_PROCESS_PARAMETERS.");
return penv;
}
else
{
// Accessing 64 bit process under 32 bit host.
var pPeb = _GetPeb64(hProcess);
long ptr;
if (!_TryReadIntPtrWow64(hProcess, pPeb.ToInt64() + 0x20, out ptr))
throw new Exception("Unable to read PEB.");
long penv;
if (!_TryReadIntPtrWow64(hProcess, ptr + 0x80, out penv))
throw new Exception("Unable to read RTL_USER_PROCESS_PARAMETERS.");
return new UniPtr(penv);
}
}
else
{
// Accessing 32 bit process under 32 bit host.
IntPtr pPeb = _GetPeb32(hProcess);
IntPtr ptr;
if (!_TryReadIntPtr32(hProcess, pPeb + 0x10, out ptr))
throw new Exception("Unable to read PEB.");
IntPtr penv;
if (!_TryReadIntPtr32(hProcess, ptr + 0x48, out penv))
throw new Exception("Unable to read RTL_USER_PROCESS_PARAMETERS.");
return penv;
}
}
static int _GetProcessBitness(IntPtr hProcess)
{
if (Environment.Is64BitOperatingSystem)
{
bool wow64;
if (!WindowsApi.IsWow64Process(hProcess, out wow64))
return 32;
if (wow64)
return 32;
return 64;
}
else
{
return 32;
}
}
static IntPtr _GetPeb32(IntPtr hProcess)
{
if (Environment.Is64BitProcess)
{
var ptr = IntPtr.Zero;
int res_len = 0;
int pbiSize = IntPtr.Size;
int status = WindowsApi.NtQueryInformationProcess(
hProcess,
WindowsApi.ProcessWow64Information,
ref ptr,
pbiSize,
ref res_len);
if (res_len != pbiSize)
throw new Exception("Unable to query process information.");
return ptr;
}
else
{
return _GetPebNative(hProcess);
}
}
static IntPtr _GetPebNative(IntPtr hProcess)
{
var pbi = new WindowsApi.PROCESS_BASIC_INFORMATION();
int res_len = 0;
int pbiSize = Marshal.SizeOf(pbi);
int status = WindowsApi.NtQueryInformationProcess(
hProcess,
WindowsApi.ProcessBasicInformation,
ref pbi,
pbiSize,
ref res_len);
if (res_len != pbiSize)
throw new Exception("Unable to query process information.");
return pbi.PebBaseAddress;
}
static UniPtr _GetPeb64(IntPtr hProcess)
{
if (Environment.Is64BitProcess)
{
return _GetPebNative(hProcess);
}
else
{
// Get PEB via WOW64 API.
var pbi = new WindowsApi.PROCESS_BASIC_INFORMATION_WOW64();
int res_len = 0;
int pbiSize = Marshal.SizeOf(pbi);
int status = WindowsApi.NtWow64QueryInformationProcess64(
hProcess,
WindowsApi.ProcessBasicInformation,
ref pbi,
pbiSize,
ref res_len);
if (res_len != pbiSize)
throw new Exception("Unable to query process information.");
return new UniPtr(pbi.PebBaseAddress);
}
}
static bool _HasReadAccess(IntPtr hProcess, IntPtr address, out int size)
{
size = 0;
var memInfo = new WindowsApi.MEMORY_BASIC_INFORMATION();
int result = WindowsApi.VirtualQueryEx(
hProcess,
address,
ref memInfo,
Marshal.SizeOf(memInfo));
if (result == 0)
return false;
if (memInfo.Protect == WindowsApi.PAGE_NOACCESS || memInfo.Protect == WindowsApi.PAGE_EXECUTE)
return false;
try
{
size = Convert.ToInt32(memInfo.RegionSize.ToInt64() - (address.ToInt64() - memInfo.BaseAddress.ToInt64()));
}
catch (OverflowException)
{
return false;
}
if (size <= 0)
return false;
return true;
}
static bool _HasReadAccessWow64(IntPtr hProcess, long address, out int size)
{
size = 0;
WindowsApi.MEMORY_BASIC_INFORMATION_WOW64 memInfo;
var memInfoType = typeof(WindowsApi.MEMORY_BASIC_INFORMATION_WOW64);
int memInfoLength = Marshal.SizeOf(memInfoType);
const int memInfoAlign = 8;
long resultLength = 0;
int result;
IntPtr hMemInfo = Marshal.AllocHGlobal(memInfoLength + memInfoAlign * 2);
try
{
// Align to 64 bits.
IntPtr hMemInfoAligned = new IntPtr(hMemInfo.ToInt64() & ~(memInfoAlign - 1L));
result = WindowsApi.NtWow64QueryVirtualMemory64(
hProcess,
address,
WindowsApi.MEMORY_INFORMATION_CLASS.MemoryBasicInformation,
hMemInfoAligned,
memInfoLength,
ref resultLength);
memInfo = (WindowsApi.MEMORY_BASIC_INFORMATION_WOW64)Marshal.PtrToStructure(hMemInfoAligned, memInfoType);
}
finally
{
Marshal.FreeHGlobal(hMemInfo);
}
if (result != WindowsApi.STATUS_SUCCESS)
return false;
if (memInfo.Protect == WindowsApi.PAGE_NOACCESS || memInfo.Protect == WindowsApi.PAGE_EXECUTE)
return false;
try
{
size = Convert.ToInt32(memInfo.RegionSize - (address - memInfo.BaseAddress));
}
catch (OverflowException)
{
return false;
}
if (size <= 0)
return false;
return true;
}
static class WindowsApi
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct PROCESS_BASIC_INFORMATION
{
public IntPtr Reserved1;
public IntPtr PebBaseAddress;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public IntPtr[] Reserved2;
public IntPtr UniqueProcessId;
public IntPtr Reserved3;
}
public const int ProcessBasicInformation = 0;
public const int ProcessWow64Information = 26;
[DllImport("ntdll.dll", SetLastError = true)]
public static extern int NtQueryInformationProcess(
IntPtr hProcess,
int pic,
ref PROCESS_BASIC_INFORMATION pbi,
int cb,
ref int pSize);
[DllImport("ntdll.dll", SetLastError = true)]
public static extern int NtQueryInformationProcess(
IntPtr hProcess,
int pic,
ref IntPtr pi,
int cb,
ref int pSize);
[DllImport("ntdll.dll", SetLastError = true)]
public static extern int NtQueryInformationProcess(
IntPtr hProcess,
int pic,
ref long pi,
int cb,
ref int pSize);
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct PROCESS_BASIC_INFORMATION_WOW64
{
public long Reserved1;
public long PebBaseAddress;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public long[] Reserved2;
public long UniqueProcessId;
public long Reserved3;
}
[DllImport("ntdll.dll", SetLastError = true)]
public static extern int NtWow64QueryInformationProcess64(
IntPtr hProcess,
int pic,
ref PROCESS_BASIC_INFORMATION_WOW64 pbi,
int cb,
ref int pSize);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool ReadProcessMemory(
IntPtr hProcess,
IntPtr lpBaseAddress,
[Out] byte[] lpBuffer,
IntPtr dwSize,
ref IntPtr lpNumberOfBytesRead);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool ReadProcessMemory(
IntPtr hProcess,
IntPtr lpBaseAddress,
IntPtr lpBuffer,
IntPtr dwSize,
ref IntPtr lpNumberOfBytesRead);
[DllImport("ntdll.dll", SetLastError = true)]
public static extern int NtWow64ReadVirtualMemory64(
IntPtr hProcess,
long lpBaseAddress,
IntPtr lpBuffer,
long dwSize,
ref long lpNumberOfBytesRead);
[DllImport("ntdll.dll", SetLastError = true)]
public static extern int NtWow64ReadVirtualMemory64(
IntPtr hProcess,
long lpBaseAddress,
[Out] byte[] lpBuffer,
long dwSize,
ref long lpNumberOfBytesRead);
public const int STATUS_SUCCESS = 0;
public const int PAGE_NOACCESS = 0x01;
public const int PAGE_EXECUTE = 0x10;
[StructLayout(LayoutKind.Sequential)]
public struct MEMORY_BASIC_INFORMATION
{
public IntPtr BaseAddress;
public IntPtr AllocationBase;
public int AllocationProtect;
public IntPtr RegionSize;
public int State;
public int Protect;
public int Type;
}
[DllImport("kernel32.dll")]
public static extern int VirtualQueryEx(IntPtr hProcess, IntPtr lpAddress, ref MEMORY_BASIC_INFORMATION lpBuffer, int dwLength);
[StructLayout(LayoutKind.Sequential)]
public struct MEMORY_BASIC_INFORMATION_WOW64
{
public long BaseAddress;
public long AllocationBase;
public int AllocationProtect;
public long RegionSize;
public int State;
public int Protect;
public int Type;
}
public enum MEMORY_INFORMATION_CLASS
{
MemoryBasicInformation
}
[DllImport("ntdll.dll")]
public static extern int NtWow64QueryVirtualMemory64(
IntPtr hProcess,
long lpAddress,
MEMORY_INFORMATION_CLASS memoryInformationClass,
IntPtr lpBuffer, // MEMORY_BASIC_INFORMATION_WOW64, pointer must be 64-bit aligned
long memoryInformationLength,
ref long returnLength);
[DllImport("kernel32.dll")]
public static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process);
}
}
}