You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ProcessEnvironment.cs 24 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. /* ***************************************************************************
  2. The component allows to read the environment variables of another process
  3. running in a Windows system.
  4. History:
  5. - v1.2.ss Add GetCommandLine for convenience.
  6. - v1.2: Added support for inspection of 64 bit processes from 32 bit host
  7. - v1.1: Fixed issue with environment block size detection
  8. - v1.0: Initial
  9. ******************************************************************************
  10. The MIT License (MIT)
  11. Copyright (c) 2011-2014 Oleksiy Gapotchenko
  12. Copyright (c) 2018 Shadowsocks Project
  13. Permission is hereby granted, free of charge, to any person obtaining a copy
  14. of this software and associated documentation files (the "Software"), to deal
  15. in the Software without restriction, including without limitation the rights
  16. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17. copies of the Software, and to permit persons to whom the Software is
  18. furnished to do so, subject to the following conditions:
  19. The above copyright notice and this permission notice shall be included in
  20. all copies or substantial portions of the Software.
  21. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. THE SOFTWARE.
  28. *************************************************************************** */
  29. using System;
  30. using System.Collections.Specialized;
  31. using System.Diagnostics;
  32. using System.Linq;
  33. using System.Management;
  34. using System.Runtime.CompilerServices;
  35. using System.Runtime.InteropServices;
  36. using System.Text;
  37. namespace Shadowsocks.Test
  38. {
  39. static class ProcessEnvironment
  40. {
  41. public static StringDictionary ReadEnvironmentVariables(this Process process)
  42. {
  43. return _GetEnvironmentVariablesCore(process.Handle);
  44. }
  45. public static StringDictionary TryReadEnvironmentVariables(this Process process)
  46. {
  47. try
  48. {
  49. return ReadEnvironmentVariables(process);
  50. }
  51. catch
  52. {
  53. return null;
  54. }
  55. }
  56. public static string GetCommandLine(this Process process)
  57. {
  58. using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + process.Id))
  59. using (ManagementObjectCollection objects = searcher.Get())
  60. {
  61. return objects.Cast<ManagementBaseObject>().SingleOrDefault()?["CommandLine"]?.ToString();
  62. }
  63. }
  64. /// <summary>
  65. /// Universal pointer.
  66. /// </summary>
  67. struct UniPtr
  68. {
  69. public UniPtr(IntPtr p)
  70. {
  71. Value = p.ToInt64();
  72. Size = IntPtr.Size;
  73. }
  74. public UniPtr(long p)
  75. {
  76. Value = p;
  77. Size = sizeof(long);
  78. }
  79. public long Value;
  80. public int Size;
  81. public static implicit operator IntPtr(UniPtr p)
  82. {
  83. return new IntPtr(p.Value);
  84. }
  85. public static implicit operator UniPtr(IntPtr p)
  86. {
  87. return new UniPtr(p);
  88. }
  89. public override string ToString()
  90. {
  91. return Value.ToString();
  92. }
  93. public bool FitsInNativePointer
  94. {
  95. get
  96. {
  97. return Size <= IntPtr.Size;
  98. }
  99. }
  100. public bool CanBeRepresentedByNativePointer
  101. {
  102. get
  103. {
  104. int actualSize = Size;
  105. if (actualSize == 8)
  106. {
  107. if (Value >> 32 == 0)
  108. actualSize = 4;
  109. }
  110. return actualSize <= IntPtr.Size;
  111. }
  112. }
  113. public long ToInt64()
  114. {
  115. return Value;
  116. }
  117. }
  118. static StringDictionary _GetEnvironmentVariablesCore(IntPtr hProcess)
  119. {
  120. var penv = _GetPenv(hProcess);
  121. const int maxEnvSize = 32767;
  122. byte[] envData;
  123. if (penv.CanBeRepresentedByNativePointer)
  124. {
  125. int dataSize;
  126. if (!_HasReadAccess(hProcess, penv, out dataSize))
  127. throw new Exception("Unable to read environment block.");
  128. if (dataSize > maxEnvSize)
  129. dataSize = maxEnvSize;
  130. envData = new byte[dataSize];
  131. var res_len = IntPtr.Zero;
  132. bool b = WindowsApi.ReadProcessMemory(
  133. hProcess,
  134. penv,
  135. envData,
  136. new IntPtr(dataSize),
  137. ref res_len);
  138. if (!b || (int)res_len != dataSize)
  139. throw new Exception("Unable to read environment block data.");
  140. }
  141. else if (penv.Size == 8 && IntPtr.Size == 4)
  142. {
  143. // Accessing 64 bit process under 32 bit host.
  144. int dataSize;
  145. if (!_HasReadAccessWow64(hProcess, penv.ToInt64(), out dataSize))
  146. throw new Exception("Unable to read environment block with WOW64 API.");
  147. if (dataSize > maxEnvSize)
  148. dataSize = maxEnvSize;
  149. envData = new byte[dataSize];
  150. long res_len = 0;
  151. int result = WindowsApi.NtWow64ReadVirtualMemory64(
  152. hProcess,
  153. penv.ToInt64(),
  154. envData,
  155. dataSize,
  156. ref res_len);
  157. if (result != WindowsApi.STATUS_SUCCESS || res_len != dataSize)
  158. throw new Exception("Unable to read environment block data with WOW64 API.");
  159. }
  160. else
  161. {
  162. throw new Exception("Unable to access process memory due to unsupported bitness cardinality.");
  163. }
  164. return _EnvToDictionary(envData);
  165. }
  166. static StringDictionary _EnvToDictionary(byte[] env)
  167. {
  168. var result = new StringDictionary();
  169. int len = env.Length;
  170. if (len < 4)
  171. return result;
  172. int n = len - 3;
  173. for (int i = 0; i < n; ++i)
  174. {
  175. byte c1 = env[i];
  176. byte c2 = env[i + 1];
  177. byte c3 = env[i + 2];
  178. byte c4 = env[i + 3];
  179. if (c1 == 0 && c2 == 0 && c3 == 0 && c4 == 0)
  180. {
  181. len = i + 3;
  182. break;
  183. }
  184. }
  185. char[] environmentCharArray = Encoding.Unicode.GetChars(env, 0, len);
  186. for (int i = 0; i < environmentCharArray.Length; i++)
  187. {
  188. int startIndex = i;
  189. while ((environmentCharArray[i] != '=') && (environmentCharArray[i] != '\0'))
  190. {
  191. i++;
  192. }
  193. if (environmentCharArray[i] != '\0')
  194. {
  195. if ((i - startIndex) == 0)
  196. {
  197. while (environmentCharArray[i] != '\0')
  198. {
  199. i++;
  200. }
  201. }
  202. else
  203. {
  204. string str = new string(environmentCharArray, startIndex, i - startIndex);
  205. i++;
  206. int num3 = i;
  207. while (environmentCharArray[i] != '\0')
  208. {
  209. i++;
  210. }
  211. string str2 = new string(environmentCharArray, num3, i - num3);
  212. result[str] = str2;
  213. }
  214. }
  215. }
  216. return result;
  217. }
  218. static bool _TryReadIntPtr32(IntPtr hProcess, IntPtr ptr, out IntPtr readPtr)
  219. {
  220. bool result;
  221. RuntimeHelpers.PrepareConstrainedRegions();
  222. try
  223. {
  224. }
  225. finally
  226. {
  227. int dataSize = sizeof(Int32);
  228. var data = Marshal.AllocHGlobal(dataSize);
  229. IntPtr res_len = IntPtr.Zero;
  230. bool b = WindowsApi.ReadProcessMemory(
  231. hProcess,
  232. ptr,
  233. data,
  234. new IntPtr(dataSize),
  235. ref res_len);
  236. readPtr = new IntPtr(Marshal.ReadInt32(data));
  237. Marshal.FreeHGlobal(data);
  238. if (!b || (int)res_len != dataSize)
  239. result = false;
  240. else
  241. result = true;
  242. }
  243. return result;
  244. }
  245. static bool _TryReadIntPtr(IntPtr hProcess, IntPtr ptr, out IntPtr readPtr)
  246. {
  247. bool result;
  248. RuntimeHelpers.PrepareConstrainedRegions();
  249. try
  250. {
  251. }
  252. finally
  253. {
  254. int dataSize = IntPtr.Size;
  255. var data = Marshal.AllocHGlobal(dataSize);
  256. IntPtr res_len = IntPtr.Zero;
  257. bool b = WindowsApi.ReadProcessMemory(
  258. hProcess,
  259. ptr,
  260. data,
  261. new IntPtr(dataSize),
  262. ref res_len);
  263. readPtr = Marshal.ReadIntPtr(data);
  264. Marshal.FreeHGlobal(data);
  265. if (!b || (int)res_len != dataSize)
  266. result = false;
  267. else
  268. result = true;
  269. }
  270. return result;
  271. }
  272. static bool _TryReadIntPtrWow64(IntPtr hProcess, long ptr, out long readPtr)
  273. {
  274. bool result;
  275. RuntimeHelpers.PrepareConstrainedRegions();
  276. try
  277. {
  278. }
  279. finally
  280. {
  281. int dataSize = sizeof(long);
  282. var data = Marshal.AllocHGlobal(dataSize);
  283. long res_len = 0;
  284. int status = WindowsApi.NtWow64ReadVirtualMemory64(
  285. hProcess,
  286. ptr,
  287. data,
  288. dataSize,
  289. ref res_len);
  290. readPtr = Marshal.ReadInt64(data);
  291. Marshal.FreeHGlobal(data);
  292. if (status != WindowsApi.STATUS_SUCCESS || res_len != dataSize)
  293. result = false;
  294. else
  295. result = true;
  296. }
  297. return result;
  298. }
  299. static UniPtr _GetPenv(IntPtr hProcess)
  300. {
  301. int processBitness = _GetProcessBitness(hProcess);
  302. if (processBitness == 64)
  303. {
  304. if (Environment.Is64BitProcess)
  305. {
  306. // Accessing 64 bit process under 64 bit host.
  307. IntPtr pPeb = _GetPeb64(hProcess);
  308. IntPtr ptr;
  309. if (!_TryReadIntPtr(hProcess, pPeb + 0x20, out ptr))
  310. throw new Exception("Unable to read PEB.");
  311. IntPtr penv;
  312. if (!_TryReadIntPtr(hProcess, ptr + 0x80, out penv))
  313. throw new Exception("Unable to read RTL_USER_PROCESS_PARAMETERS.");
  314. return penv;
  315. }
  316. else
  317. {
  318. // Accessing 64 bit process under 32 bit host.
  319. var pPeb = _GetPeb64(hProcess);
  320. long ptr;
  321. if (!_TryReadIntPtrWow64(hProcess, pPeb.ToInt64() + 0x20, out ptr))
  322. throw new Exception("Unable to read PEB.");
  323. long penv;
  324. if (!_TryReadIntPtrWow64(hProcess, ptr + 0x80, out penv))
  325. throw new Exception("Unable to read RTL_USER_PROCESS_PARAMETERS.");
  326. return new UniPtr(penv);
  327. }
  328. }
  329. else
  330. {
  331. // Accessing 32 bit process under 32 bit host.
  332. IntPtr pPeb = _GetPeb32(hProcess);
  333. IntPtr ptr;
  334. if (!_TryReadIntPtr32(hProcess, pPeb + 0x10, out ptr))
  335. throw new Exception("Unable to read PEB.");
  336. IntPtr penv;
  337. if (!_TryReadIntPtr32(hProcess, ptr + 0x48, out penv))
  338. throw new Exception("Unable to read RTL_USER_PROCESS_PARAMETERS.");
  339. return penv;
  340. }
  341. }
  342. static int _GetProcessBitness(IntPtr hProcess)
  343. {
  344. if (Environment.Is64BitOperatingSystem)
  345. {
  346. bool wow64;
  347. if (!WindowsApi.IsWow64Process(hProcess, out wow64))
  348. return 32;
  349. if (wow64)
  350. return 32;
  351. return 64;
  352. }
  353. else
  354. {
  355. return 32;
  356. }
  357. }
  358. static IntPtr _GetPeb32(IntPtr hProcess)
  359. {
  360. if (Environment.Is64BitProcess)
  361. {
  362. var ptr = IntPtr.Zero;
  363. int res_len = 0;
  364. int pbiSize = IntPtr.Size;
  365. int status = WindowsApi.NtQueryInformationProcess(
  366. hProcess,
  367. WindowsApi.ProcessWow64Information,
  368. ref ptr,
  369. pbiSize,
  370. ref res_len);
  371. if (res_len != pbiSize)
  372. throw new Exception("Unable to query process information.");
  373. return ptr;
  374. }
  375. else
  376. {
  377. return _GetPebNative(hProcess);
  378. }
  379. }
  380. static IntPtr _GetPebNative(IntPtr hProcess)
  381. {
  382. var pbi = new WindowsApi.PROCESS_BASIC_INFORMATION();
  383. int res_len = 0;
  384. int pbiSize = Marshal.SizeOf(pbi);
  385. int status = WindowsApi.NtQueryInformationProcess(
  386. hProcess,
  387. WindowsApi.ProcessBasicInformation,
  388. ref pbi,
  389. pbiSize,
  390. ref res_len);
  391. if (res_len != pbiSize)
  392. throw new Exception("Unable to query process information.");
  393. return pbi.PebBaseAddress;
  394. }
  395. static UniPtr _GetPeb64(IntPtr hProcess)
  396. {
  397. if (Environment.Is64BitProcess)
  398. {
  399. return _GetPebNative(hProcess);
  400. }
  401. else
  402. {
  403. // Get PEB via WOW64 API.
  404. var pbi = new WindowsApi.PROCESS_BASIC_INFORMATION_WOW64();
  405. int res_len = 0;
  406. int pbiSize = Marshal.SizeOf(pbi);
  407. int status = WindowsApi.NtWow64QueryInformationProcess64(
  408. hProcess,
  409. WindowsApi.ProcessBasicInformation,
  410. ref pbi,
  411. pbiSize,
  412. ref res_len);
  413. if (res_len != pbiSize)
  414. throw new Exception("Unable to query process information.");
  415. return new UniPtr(pbi.PebBaseAddress);
  416. }
  417. }
  418. static bool _HasReadAccess(IntPtr hProcess, IntPtr address, out int size)
  419. {
  420. size = 0;
  421. var memInfo = new WindowsApi.MEMORY_BASIC_INFORMATION();
  422. int result = WindowsApi.VirtualQueryEx(
  423. hProcess,
  424. address,
  425. ref memInfo,
  426. Marshal.SizeOf(memInfo));
  427. if (result == 0)
  428. return false;
  429. if (memInfo.Protect == WindowsApi.PAGE_NOACCESS || memInfo.Protect == WindowsApi.PAGE_EXECUTE)
  430. return false;
  431. try
  432. {
  433. size = Convert.ToInt32(memInfo.RegionSize.ToInt64() - (address.ToInt64() - memInfo.BaseAddress.ToInt64()));
  434. }
  435. catch (OverflowException)
  436. {
  437. return false;
  438. }
  439. if (size <= 0)
  440. return false;
  441. return true;
  442. }
  443. static bool _HasReadAccessWow64(IntPtr hProcess, long address, out int size)
  444. {
  445. size = 0;
  446. WindowsApi.MEMORY_BASIC_INFORMATION_WOW64 memInfo;
  447. var memInfoType = typeof(WindowsApi.MEMORY_BASIC_INFORMATION_WOW64);
  448. int memInfoLength = Marshal.SizeOf(memInfoType);
  449. const int memInfoAlign = 8;
  450. long resultLength = 0;
  451. int result;
  452. IntPtr hMemInfo = Marshal.AllocHGlobal(memInfoLength + memInfoAlign * 2);
  453. try
  454. {
  455. // Align to 64 bits.
  456. IntPtr hMemInfoAligned = new IntPtr(hMemInfo.ToInt64() & ~(memInfoAlign - 1L));
  457. result = WindowsApi.NtWow64QueryVirtualMemory64(
  458. hProcess,
  459. address,
  460. WindowsApi.MEMORY_INFORMATION_CLASS.MemoryBasicInformation,
  461. hMemInfoAligned,
  462. memInfoLength,
  463. ref resultLength);
  464. memInfo = (WindowsApi.MEMORY_BASIC_INFORMATION_WOW64)Marshal.PtrToStructure(hMemInfoAligned, memInfoType);
  465. }
  466. finally
  467. {
  468. Marshal.FreeHGlobal(hMemInfo);
  469. }
  470. if (result != WindowsApi.STATUS_SUCCESS)
  471. return false;
  472. if (memInfo.Protect == WindowsApi.PAGE_NOACCESS || memInfo.Protect == WindowsApi.PAGE_EXECUTE)
  473. return false;
  474. try
  475. {
  476. size = Convert.ToInt32(memInfo.RegionSize - (address - memInfo.BaseAddress));
  477. }
  478. catch (OverflowException)
  479. {
  480. return false;
  481. }
  482. if (size <= 0)
  483. return false;
  484. return true;
  485. }
  486. static class WindowsApi
  487. {
  488. [StructLayout(LayoutKind.Sequential, Pack = 1)]
  489. public struct PROCESS_BASIC_INFORMATION
  490. {
  491. public IntPtr Reserved1;
  492. public IntPtr PebBaseAddress;
  493. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
  494. public IntPtr[] Reserved2;
  495. public IntPtr UniqueProcessId;
  496. public IntPtr Reserved3;
  497. }
  498. public const int ProcessBasicInformation = 0;
  499. public const int ProcessWow64Information = 26;
  500. [DllImport("ntdll.dll", SetLastError = true)]
  501. public static extern int NtQueryInformationProcess(
  502. IntPtr hProcess,
  503. int pic,
  504. ref PROCESS_BASIC_INFORMATION pbi,
  505. int cb,
  506. ref int pSize);
  507. [DllImport("ntdll.dll", SetLastError = true)]
  508. public static extern int NtQueryInformationProcess(
  509. IntPtr hProcess,
  510. int pic,
  511. ref IntPtr pi,
  512. int cb,
  513. ref int pSize);
  514. [DllImport("ntdll.dll", SetLastError = true)]
  515. public static extern int NtQueryInformationProcess(
  516. IntPtr hProcess,
  517. int pic,
  518. ref long pi,
  519. int cb,
  520. ref int pSize);
  521. [StructLayout(LayoutKind.Sequential, Pack = 1)]
  522. public struct PROCESS_BASIC_INFORMATION_WOW64
  523. {
  524. public long Reserved1;
  525. public long PebBaseAddress;
  526. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
  527. public long[] Reserved2;
  528. public long UniqueProcessId;
  529. public long Reserved3;
  530. }
  531. [DllImport("ntdll.dll", SetLastError = true)]
  532. public static extern int NtWow64QueryInformationProcess64(
  533. IntPtr hProcess,
  534. int pic,
  535. ref PROCESS_BASIC_INFORMATION_WOW64 pbi,
  536. int cb,
  537. ref int pSize);
  538. [DllImport("kernel32.dll", SetLastError = true)]
  539. public static extern bool ReadProcessMemory(
  540. IntPtr hProcess,
  541. IntPtr lpBaseAddress,
  542. [Out] byte[] lpBuffer,
  543. IntPtr dwSize,
  544. ref IntPtr lpNumberOfBytesRead);
  545. [DllImport("kernel32.dll", SetLastError = true)]
  546. public static extern bool ReadProcessMemory(
  547. IntPtr hProcess,
  548. IntPtr lpBaseAddress,
  549. IntPtr lpBuffer,
  550. IntPtr dwSize,
  551. ref IntPtr lpNumberOfBytesRead);
  552. [DllImport("ntdll.dll", SetLastError = true)]
  553. public static extern int NtWow64ReadVirtualMemory64(
  554. IntPtr hProcess,
  555. long lpBaseAddress,
  556. IntPtr lpBuffer,
  557. long dwSize,
  558. ref long lpNumberOfBytesRead);
  559. [DllImport("ntdll.dll", SetLastError = true)]
  560. public static extern int NtWow64ReadVirtualMemory64(
  561. IntPtr hProcess,
  562. long lpBaseAddress,
  563. [Out] byte[] lpBuffer,
  564. long dwSize,
  565. ref long lpNumberOfBytesRead);
  566. public const int STATUS_SUCCESS = 0;
  567. public const int PAGE_NOACCESS = 0x01;
  568. public const int PAGE_EXECUTE = 0x10;
  569. [StructLayout(LayoutKind.Sequential)]
  570. public struct MEMORY_BASIC_INFORMATION
  571. {
  572. public IntPtr BaseAddress;
  573. public IntPtr AllocationBase;
  574. public int AllocationProtect;
  575. public IntPtr RegionSize;
  576. public int State;
  577. public int Protect;
  578. public int Type;
  579. }
  580. [DllImport("kernel32.dll")]
  581. public static extern int VirtualQueryEx(IntPtr hProcess, IntPtr lpAddress, ref MEMORY_BASIC_INFORMATION lpBuffer, int dwLength);
  582. [StructLayout(LayoutKind.Sequential)]
  583. public struct MEMORY_BASIC_INFORMATION_WOW64
  584. {
  585. public long BaseAddress;
  586. public long AllocationBase;
  587. public int AllocationProtect;
  588. public long RegionSize;
  589. public int State;
  590. public int Protect;
  591. public int Type;
  592. }
  593. public enum MEMORY_INFORMATION_CLASS
  594. {
  595. MemoryBasicInformation
  596. }
  597. [DllImport("ntdll.dll")]
  598. public static extern int NtWow64QueryVirtualMemory64(
  599. IntPtr hProcess,
  600. long lpAddress,
  601. MEMORY_INFORMATION_CLASS memoryInformationClass,
  602. IntPtr lpBuffer, // MEMORY_BASIC_INFORMATION_WOW64, pointer must be 64-bit aligned
  603. long memoryInformationLength,
  604. ref long returnLength);
  605. [DllImport("kernel32.dll")]
  606. public static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process);
  607. }
  608. }
  609. }