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

1720 lines
73 KiB

6 months ago
6 months ago
6 months ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. using System.Runtime.ConstrainedExecution;
  7. using System.Runtime.InteropServices;
  8. using System.Runtime.Versioning;
  9. using System.Security;
  10. using System.Security.Permissions;
  11. using System.Text;
  12. using Microsoft.Win32.SafeHandles;
  13. using TrustedUninstaller.Shared;
  14. using TrustedUninstaller.Shared.Actions;
  15. using TrustedUninstaller.Shared.Tasks;
  16. namespace TrustedUninstaller.Shared
  17. {
  18. public static class Win32
  19. {
  20. public static class Service
  21. {
  22. [DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Auto)]
  23. public static extern IntPtr CreateService(
  24. IntPtr hSCManager,
  25. string lpServiceName,
  26. string lpDisplayName,
  27. uint dwDesiredAccess,
  28. uint dwServiceType,
  29. uint dwStartType,
  30. uint dwErrorControl,
  31. string lpBinaryPathName,
  32. [Optional] string lpLoadOrderGroup,
  33. [Optional] string lpdwTagId, // only string so we can pass null
  34. [Optional] string lpDependencies,
  35. [Optional] string lpServiceStartName,
  36. [Optional] string lpPassword);
  37. [DllImport("advapi32.dll", SetLastError = true)]
  38. [return: MarshalAs(UnmanagedType.Bool)]
  39. public static extern bool DeleteService(IntPtr hService);
  40. [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  41. public static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, SERVICE_ACCESS dwDesiredAccess);
  42. [DllImport("advapi32.dll", EntryPoint = "OpenSCManagerW", ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]
  43. public static extern IntPtr OpenSCManager(string machineName, string databaseName, SCM_ACCESS dwDesiredAccess);
  44. [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
  45. public static extern bool QueryServiceStatusEx(IntPtr Service, int InfoLevel,
  46. ref SERVICE_STATUS_PROCESS ServiceStatus, int BufSize, out int BytesNeeded);
  47. [DllImport("advapi32.dll", SetLastError = true)]
  48. [return: MarshalAs(UnmanagedType.Bool)]
  49. public static extern bool CloseServiceHandle(IntPtr hSCObject);
  50. [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
  51. public static extern bool EnumServicesStatusEx(
  52. IntPtr hSCManager,
  53. uint InfoLevel,
  54. SERVICE_TYPE dwServiceType,
  55. uint dwServiceState,
  56. IntPtr lpServices,
  57. int cbBufSize,
  58. out int pcbBytesNeeded,
  59. out int lpServicesReturned,
  60. ref int lpResumeHandle,
  61. string pszGroupName
  62. );
  63. public struct ENUM_SERVICE_STATUS_PROCESS {
  64. [MarshalAs(UnmanagedType.LPWStr)]
  65. public string lpServiceName;
  66. [MarshalAs(UnmanagedType.LPWStr)]
  67. public string lpDisplayName;
  68. public SERVICE_STATUS_PROCESS ServiceStatusProcess;
  69. }
  70. [StructLayout(LayoutKind.Sequential)]
  71. public struct SERVICE_STATUS_PROCESS
  72. {
  73. public SERVICE_TYPE ServiceType;
  74. public SERVICE_STATE CurrentState;
  75. public SERVICE_ACCEPT ControlsAccepted;
  76. public int Win32ExitCode;
  77. public int ServiceSpecificExitCode;
  78. public int CheckPoint;
  79. public int WaitHint;
  80. public int ProcessID;
  81. public SERVICE_FLAGS ServiceFlags;
  82. }
  83. public enum SERVICE_STATE : int
  84. {
  85. ContinuePending = 0x5,
  86. PausePending = 0x6,
  87. Paused = 0x7,
  88. Running = 0x4,
  89. StartPending = 0x2,
  90. StopPending = 0x3,
  91. Stopped = 0x1
  92. }
  93. public enum SERVICE_ACCEPT : int
  94. {
  95. NetBindChange = 0x10,
  96. ParamChange = 0x8,
  97. PauseContinue = 0x2,
  98. PreShutdown = 0x100,
  99. Shutdown = 0x4,
  100. Stop = 0x1,
  101. HardwareProfileChange = 0x20,
  102. PowerEvent = 0x40,
  103. SessionChange = 0x80
  104. }
  105. public enum SERVICE_FLAGS : int
  106. {
  107. None = 0,
  108. RunsInSystemProcess = 0x1
  109. }
  110. /// <summary>
  111. /// Service types.
  112. /// </summary>
  113. [Flags]
  114. public enum SERVICE_TYPE : uint
  115. {
  116. /// <summary>
  117. /// Driver service.
  118. /// </summary>
  119. SERVICE_KERNEL_DRIVER = 0x00000001,
  120. /// <summary>
  121. /// File system driver service.
  122. /// </summary>
  123. SERVICE_FILE_SYSTEM_DRIVER = 0x00000002,
  124. /// <summary>
  125. /// Service that runs in its own process.
  126. /// </summary>
  127. SERVICE_WIN32_OWN_PROCESS = 0x00000010,
  128. /// <summary>
  129. /// Service that shares a process with one or more other services.
  130. /// </summary>
  131. SERVICE_WIN32_SHARE_PROCESS = 0x00000020,
  132. /// <summary>
  133. /// The service can interact with the desktop.
  134. /// </summary>
  135. SERVICE_INTERACTIVE_PROCESS = 0x00000100,
  136. }
  137. /// <summary>
  138. /// Service start options
  139. /// </summary>
  140. public enum SERVICE_START : uint
  141. {
  142. /// <summary>
  143. /// A device driver started by the system loader. This value is valid
  144. /// only for driver services.
  145. /// </summary>
  146. SERVICE_BOOT_START = 0x00000000,
  147. /// <summary>
  148. /// A device driver started by the IoInitSystem function. This value
  149. /// is valid only for driver services.
  150. /// </summary>
  151. SERVICE_SYSTEM_START = 0x00000001,
  152. /// <summary>
  153. /// A service started automatically by the service control manager
  154. /// during system startup. For more information, see Automatically
  155. /// Starting Services.
  156. /// </summary>
  157. SERVICE_AUTO_START = 0x00000002,
  158. /// <summary>
  159. /// A service started by the service control manager when a process
  160. /// calls the StartService function. For more information, see
  161. /// Starting Services on Demand.
  162. /// </summary>
  163. SERVICE_DEMAND_START = 0x00000003,
  164. /// <summary>
  165. /// A service that cannot be started. Attempts to start the service
  166. /// result in the error code ERROR_SERVICE_DISABLED.
  167. /// </summary>
  168. SERVICE_DISABLED = 0x00000004,
  169. }
  170. /// <summary>
  171. /// Severity of the error, and action taken, if this service fails
  172. /// to start.
  173. /// </summary>
  174. public enum SERVICE_ERROR
  175. {
  176. /// <summary>
  177. /// The startup program ignores the error and continues the startup
  178. /// operation.
  179. /// </summary>
  180. SERVICE_ERROR_IGNORE = 0x00000000,
  181. /// <summary>
  182. /// The startup program logs the error in the event log but continues
  183. /// the startup operation.
  184. /// </summary>
  185. SERVICE_ERROR_NORMAL = 0x00000001,
  186. /// <summary>
  187. /// The startup program logs the error in the event log. If the
  188. /// last-known-good configuration is being started, the startup
  189. /// operation continues. Otherwise, the system is restarted with
  190. /// the last-known-good configuration.
  191. /// </summary>
  192. SERVICE_ERROR_SEVERE = 0x00000002,
  193. /// <summary>
  194. /// The startup program logs the error in the event log, if possible.
  195. /// If the last-known-good configuration is being started, the startup
  196. /// operation fails. Otherwise, the system is restarted with the
  197. /// last-known good configuration.
  198. /// </summary>
  199. SERVICE_ERROR_CRITICAL = 0x00000003,
  200. }
  201. [Flags]
  202. public enum SERVICE_ACCESS : uint
  203. {
  204. STANDARD_RIGHTS_REQUIRED = 0xF0000,
  205. SERVICE_QUERY_CONFIG = 0x00001,
  206. SERVICE_CHANGE_CONFIG = 0x00002,
  207. SERVICE_QUERY_STATUS = 0x00004,
  208. SERVICE_ENUMERATE_DEPENDENTS = 0x00008,
  209. SERVICE_START = 0x00010,
  210. SERVICE_STOP = 0x00020,
  211. SERVICE_PAUSE_CONTINUE = 0x00040,
  212. SERVICE_INTERROGATE = 0x00080,
  213. SERVICE_USER_DEFINED_CONTROL = 0x00100,
  214. SERVICE_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_ENUMERATE_DEPENDENTS | SERVICE_START | SERVICE_STOP |
  215. SERVICE_PAUSE_CONTINUE | SERVICE_INTERROGATE | SERVICE_USER_DEFINED_CONTROL)
  216. }
  217. [Flags]
  218. public enum SCM_ACCESS : uint
  219. {
  220. STANDARD_RIGHTS_REQUIRED = 0xF0000,
  221. SC_MANAGER_CONNECT = 0x00001,
  222. SC_MANAGER_CREATE_SERVICE = 0x00002,
  223. SC_MANAGER_ENUMERATE_SERVICE = 0x00004,
  224. SC_MANAGER_LOCK = 0x00008,
  225. SC_MANAGER_QUERY_LOCK_STATUS = 0x00010,
  226. SC_MANAGER_MODIFY_BOOT_CONFIG = 0x00020,
  227. SC_MANAGER_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE | SC_MANAGER_ENUMERATE_SERVICE | SC_MANAGER_LOCK | SC_MANAGER_QUERY_LOCK_STATUS |
  228. SC_MANAGER_MODIFY_BOOT_CONFIG
  229. }
  230. }
  231. public static class ServiceEx {
  232. public static bool IsPendingDeleteOrDeleted(string serviceName)
  233. {
  234. var manager = Service.OpenSCManager(null, null, Service.SCM_ACCESS.SC_MANAGER_ALL_ACCESS);
  235. if (manager == IntPtr.Zero)
  236. return new RegistryValueAction() { KeyName = @"HKLM\SYSTEM\CurrentControlSet\Services\" + serviceName, Value = "DeleteFlag", Type = RegistryValueType.REG_DWORD, Data = 1 }.GetStatus() == UninstallTaskStatus.Completed ||
  237. new RegistryKeyAction() { KeyName = @"HKLM\SYSTEM\CurrentControlSet\Services\" + serviceName, Operation = RegistryKeyOperation.Delete }.GetStatus() == UninstallTaskStatus.Completed;
  238. var handle = Service.CreateService(manager, serviceName, "AME Deletion Check",
  239. (uint)Service.SERVICE_ACCESS.SERVICE_ALL_ACCESS,
  240. (uint)Service.SERVICE_TYPE.SERVICE_WIN32_OWN_PROCESS, (uint)Service.SERVICE_START.SERVICE_DISABLED,
  241. (uint)Service.SERVICE_ERROR.SERVICE_ERROR_IGNORE, @"ame-deletion-check");
  242. if (handle == IntPtr.Zero)
  243. {
  244. if (Marshal.GetLastWin32Error() == 0x00000430)
  245. {
  246. return true;
  247. }
  248. return new RegistryValueAction() { KeyName = @"HKLM\SYSTEM\CurrentControlSet\Services\" + serviceName, Value = "DeleteFlag", Type = RegistryValueType.REG_DWORD, Data = 1 }.GetStatus() == UninstallTaskStatus.Completed ||
  249. new RegistryKeyAction() { KeyName = @"HKLM\SYSTEM\CurrentControlSet\Services\" + serviceName, Operation = RegistryKeyOperation.Delete }.GetStatus() == UninstallTaskStatus.Completed;
  250. }
  251. Service.DeleteService(handle);
  252. Service.CloseServiceHandle(handle);
  253. Service.CloseServiceHandle(manager);
  254. return true;
  255. }
  256. public static bool IsPendingStopOrStopped(string serviceName, out bool pending)
  257. {
  258. pending = false;
  259. var manager = Service.OpenSCManager(null, null, Service.SCM_ACCESS.SC_MANAGER_ENUMERATE_SERVICE);
  260. if (manager == IntPtr.Zero)
  261. return false;
  262. var handle = Service.OpenService(manager, serviceName,
  263. Service.SERVICE_ACCESS.SERVICE_QUERY_STATUS);
  264. if (handle == IntPtr.Zero)
  265. return true;
  266. Service.SERVICE_STATUS_PROCESS status = new Service.SERVICE_STATUS_PROCESS();
  267. if (!Service.QueryServiceStatusEx(handle, 0, ref status, Marshal.SizeOf(status), out int retLen))
  268. {
  269. Service.CloseServiceHandle(handle);
  270. Service.CloseServiceHandle(manager);
  271. return false;
  272. }
  273. Service.CloseServiceHandle(handle);
  274. Service.CloseServiceHandle(manager);
  275. pending = status.CurrentState == Service.SERVICE_STATE.StopPending;
  276. return pending || status.CurrentState == Service.SERVICE_STATE.Stopped;
  277. }
  278. public static int GetServiceProcessId(string serviceName)
  279. {
  280. var manager = Service.OpenSCManager(null, null, Service.SCM_ACCESS.SC_MANAGER_ENUMERATE_SERVICE);
  281. if (manager == IntPtr.Zero)
  282. throw new Exception("Error opening service manager.");
  283. var handle = Service.OpenService(manager, serviceName,
  284. Service.SERVICE_ACCESS.SERVICE_QUERY_STATUS);
  285. Service.SERVICE_STATUS_PROCESS status = new Service.SERVICE_STATUS_PROCESS();
  286. if (!Service.QueryServiceStatusEx(handle, 0, ref status, Marshal.SizeOf(status), out int retLen))
  287. {
  288. Service.CloseServiceHandle(handle);
  289. Service.CloseServiceHandle(manager);
  290. throw new Exception("Error querying service ProcessId: " + Marshal.GetLastWin32Error());
  291. }
  292. Service.CloseServiceHandle(handle);
  293. Service.CloseServiceHandle(manager);
  294. return status.ProcessID == 0 ? -1 : status.ProcessID;
  295. }
  296. public static IEnumerable<string> GetServicesFromProcessId(int processId)
  297. {
  298. return GetServices(Service.SERVICE_TYPE.SERVICE_WIN32_OWN_PROCESS |
  299. Service.SERVICE_TYPE.SERVICE_WIN32_SHARE_PROCESS).Where(x => x.ServiceStatusProcess.ProcessID == processId).Select(x => x.lpServiceName);
  300. }
  301. private static Service.ENUM_SERVICE_STATUS_PROCESS[] GetServices(Service.SERVICE_TYPE serviceTypes)
  302. {
  303. IntPtr handle = Service.OpenSCManager(null, null, Service.SCM_ACCESS.SC_MANAGER_ENUMERATE_SERVICE);
  304. if (handle == IntPtr.Zero)
  305. throw new Exception("Could not open service manager.");
  306. int iBytesNeeded = 0;
  307. int iServicesReturned = 0;
  308. int iResumeHandle = 0;
  309. Service.EnumServicesStatusEx(handle,
  310. 0,
  311. Service.SERVICE_TYPE.SERVICE_WIN32_OWN_PROCESS | Service.SERVICE_TYPE.SERVICE_WIN32_SHARE_PROCESS,
  312. 1,
  313. IntPtr.Zero,
  314. 0,
  315. out iBytesNeeded,
  316. out iServicesReturned,
  317. ref iResumeHandle,
  318. null);
  319. IntPtr buffer = Marshal.AllocHGlobal((int)iBytesNeeded);
  320. Service.EnumServicesStatusEx(handle,
  321. 0,
  322. Service.SERVICE_TYPE.SERVICE_WIN32_OWN_PROCESS | Service.SERVICE_TYPE.SERVICE_WIN32_SHARE_PROCESS,
  323. 1,
  324. buffer,
  325. iBytesNeeded,
  326. out iBytesNeeded,
  327. out iServicesReturned,
  328. ref iResumeHandle,
  329. null);
  330. var services = new Service.ENUM_SERVICE_STATUS_PROCESS[iServicesReturned];
  331. var serviceSize = Marshal.SizeOf(typeof(Service.ENUM_SERVICE_STATUS_PROCESS));
  332. for (int i = 0; i < iServicesReturned; i++)
  333. {
  334. var servicePtr = new IntPtr(buffer.ToInt64() + i * serviceSize);
  335. services[i] = Marshal.PtrToStructure<Service.ENUM_SERVICE_STATUS_PROCESS>(servicePtr);
  336. }
  337. Marshal.FreeHGlobal(buffer);
  338. return services;
  339. }
  340. }
  341. public static class Tokens
  342. {
  343. [DllImport("advapi32.dll", SetLastError = true)]
  344. public static extern bool OpenProcessToken(IntPtr hProcess, TokenAccessFlags DesiredAccess,
  345. out TokensEx.SafeTokenHandle hToken);
  346. [DllImport("advapi32.dll", SetLastError = true)]
  347. public static extern bool GetTokenInformation(TokensEx.SafeTokenHandle TokenHandle,
  348. TOKEN_INFORMATION_CLASS TokenInformationClass, IntPtr TokenInformation, int TokenInformationLength,
  349. out int ReturnLength);
  350. [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  351. [return: MarshalAs(UnmanagedType.Bool)]
  352. public static extern bool SetTokenInformation(
  353. TokensEx.SafeTokenHandle hToken,
  354. TOKEN_INFORMATION_CLASS tokenInfoClass,
  355. IntPtr pTokenInfo,
  356. int tokenInfoLength);
  357. [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  358. [return: MarshalAs(UnmanagedType.Bool)]
  359. public static extern bool SetTokenInformation(
  360. TokensEx.SafeTokenHandle hToken,
  361. TOKEN_INFORMATION_CLASS tokenInfoClass,
  362. ref uint pTokenInfo,
  363. int tokenInfoLength);
  364. [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  365. public static extern bool DuplicateTokenEx(TokensEx.SafeTokenHandle hExistingToken, TokenAccessFlags dwDesiredAccess,
  366. IntPtr lpTokenAttributes, SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, TOKEN_TYPE TokenType,
  367. out TokensEx.SafeTokenHandle phNewToken);
  368. [DllImport("advapi32.dll", SetLastError = true)]
  369. public static extern bool ImpersonateLoggedOnUser(TokensEx.SafeTokenHandle hToken);
  370. [DllImport("advapi32.dll", SetLastError = true)]
  371. public static extern bool LookupPrivilegeValue(IntPtr lpSystemName, string lpName, out LUID lpLuid);
  372. [DllImport("ntdll.dll", SetLastError = true)]
  373. public static extern IntPtr RtlAdjustPrivilege(LUID privilege, bool bEnablePrivilege, bool isThreadPrivilege,
  374. out bool previousValue);
  375. [DllImport("ntdll.dll")]
  376. public static extern int ZwCreateToken(out TokensEx.SafeTokenHandle TokenHandle, TokenAccessFlags DesiredAccess,
  377. ref OBJECT_ATTRIBUTES ObjectAttributes, TOKEN_TYPE TokenType, ref LUID AuthenticationId,
  378. ref LARGE_INTEGER ExpirationTime, ref TOKEN_USER TokenUser, ref TOKEN_GROUPS TokenGroups,
  379. ref TOKEN_PRIVILEGES TokenPrivileges, ref TOKEN_OWNER TokenOwner,
  380. ref TOKEN_PRIMARY_GROUP TokenPrimaryGroup, ref TOKEN_DEFAULT_DACL TokenDefaultDacl,
  381. ref TOKEN_SOURCE TokenSource);
  382. [StructLayout(LayoutKind.Sequential)]
  383. public struct OBJECT_ATTRIBUTES : IDisposable
  384. {
  385. public int Length;
  386. public IntPtr RootDirectory;
  387. private IntPtr objectName;
  388. public uint Attributes;
  389. public IntPtr SecurityDescriptor;
  390. public IntPtr SecurityQualityOfService;
  391. public OBJECT_ATTRIBUTES(string name, uint attrs)
  392. {
  393. Length = 0;
  394. RootDirectory = IntPtr.Zero;
  395. objectName = IntPtr.Zero;
  396. Attributes = attrs;
  397. SecurityDescriptor = IntPtr.Zero;
  398. SecurityQualityOfService = IntPtr.Zero;
  399. Length = Marshal.SizeOf(this);
  400. ObjectName = new UNICODE_STRING(name);
  401. }
  402. public UNICODE_STRING ObjectName
  403. {
  404. get => (UNICODE_STRING)Marshal.PtrToStructure(objectName, typeof(UNICODE_STRING));
  405. set
  406. {
  407. var fDeleteOld = objectName != IntPtr.Zero;
  408. if (!fDeleteOld) objectName = Marshal.AllocHGlobal(Marshal.SizeOf(value));
  409. Marshal.StructureToPtr(value, objectName, fDeleteOld);
  410. }
  411. }
  412. public void Dispose()
  413. {
  414. if (objectName != IntPtr.Zero)
  415. {
  416. Marshal.DestroyStructure(objectName, typeof(UNICODE_STRING));
  417. Marshal.FreeHGlobal(objectName);
  418. objectName = IntPtr.Zero;
  419. }
  420. }
  421. }
  422. [Flags]
  423. public enum TokenAccessFlags : uint
  424. {
  425. TOKEN_ADJUST_DEFAULT = 0x0080,
  426. TOKEN_ADJUST_GROUPS = 0x0040,
  427. TOKEN_ADJUST_PRIVILEGES = 0x0020,
  428. TOKEN_ADJUST_SESSIONID = 0x0100,
  429. TOKEN_ASSIGN_PRIMARY = 0x0001,
  430. TOKEN_DUPLICATE = 0x0002,
  431. TOKEN_EXECUTE = 0x00020000,
  432. TOKEN_IMPERSONATE = 0x0004,
  433. TOKEN_QUERY = 0x0008,
  434. TOKEN_QUERY_SOURCE = 0x0010,
  435. TOKEN_READ = 0x00020008,
  436. TOKEN_WRITE = 0x000200E0,
  437. TOKEN_ALL_ACCESS = 0x000F01FF,
  438. MAXIMUM_ALLOWED = 0x02000000
  439. }
  440. public enum TOKEN_TYPE
  441. {
  442. TokenPrimary = 1,
  443. TokenImpersonation
  444. }
  445. public enum TOKEN_INFORMATION_CLASS
  446. {
  447. /// <summary>
  448. /// The buffer receives a TOKEN_USER structure that contains the user account of the token.
  449. /// </summary>
  450. TokenUser = 1,
  451. /// <summary>
  452. /// The buffer receives a TOKEN_GROUPS structure that contains the group accounts associated with the token.
  453. /// </summary>
  454. TokenGroups,
  455. /// <summary>
  456. /// The buffer receives a TOKEN_PRIVILEGES structure that contains the privileges of the token.
  457. /// </summary>
  458. TokenPrivileges,
  459. /// <summary>
  460. /// The buffer receives a TOKEN_OWNER structure that contains the default owner security identifier (SID) for newly created objects.
  461. /// </summary>
  462. TokenOwner,
  463. /// <summary>
  464. /// The buffer receives a TOKEN_PRIMARY_GROUP structure that contains the default primary group SID for newly created objects.
  465. /// </summary>
  466. TokenPrimaryGroup,
  467. /// <summary>
  468. /// The buffer receives a TOKEN_DEFAULT_DACL structure that contains the default DACL for newly created objects.
  469. /// </summary>
  470. TokenDefaultDacl,
  471. /// <summary>
  472. /// The buffer receives a TOKEN_SOURCE structure that contains the source of the token. TOKEN_QUERY_SOURCE access is needed to retrieve this information.
  473. /// </summary>
  474. TokenSource,
  475. /// <summary>
  476. /// The buffer receives a TOKEN_TYPE value that indicates whether the token is a primary or impersonation token.
  477. /// </summary>
  478. TokenType,
  479. /// <summary>
  480. /// The buffer receives a SECURITY_IMPERSONATION_LEVEL value that indicates the impersonation level of the token. If the access token is not an impersonation token, the function fails.
  481. /// </summary>
  482. TokenImpersonationLevel,
  483. /// <summary>
  484. /// The buffer receives a TOKEN_STATISTICS structure that contains various token statistics.
  485. /// </summary>
  486. TokenStatistics,
  487. /// <summary>
  488. /// The buffer receives a TOKEN_GROUPS structure that contains the list of restricting SIDs in a restricted token.
  489. /// </summary>
  490. TokenRestrictedSids,
  491. /// <summary>
  492. /// The buffer receives a DWORD value that indicates the Terminal Services session identifier that is associated with the token.
  493. /// </summary>
  494. TokenSessionId,
  495. /// <summary>
  496. /// The buffer receives a TOKEN_GROUPS_AND_PRIVILEGES structure that contains the user SID, the group accounts, the restricted SIDs, and the authentication ID associated with the token.
  497. /// </summary>
  498. TokenGroupsAndPrivileges,
  499. /// <summary>
  500. /// Reserved.
  501. /// </summary>
  502. TokenSessionReference,
  503. /// <summary>
  504. /// The buffer receives a DWORD value that is nonzero if the token includes the SANDBOX_INERT flag.
  505. /// </summary>
  506. TokenSandBoxInert,
  507. /// <summary>
  508. /// Reserved.
  509. /// </summary>
  510. TokenAuditPolicy,
  511. /// <summary>
  512. /// The buffer receives a TOKEN_ORIGIN value.
  513. /// </summary>
  514. TokenOrigin,
  515. /// <summary>
  516. /// The buffer receives a TOKEN_ELEVATION_TYPE value that specifies the elevation level of the token.
  517. /// </summary>
  518. TokenElevationType,
  519. /// <summary>
  520. /// The buffer receives a TOKEN_LINKED_TOKEN structure that contains a handle to another token that is linked to this token.
  521. /// </summary>
  522. TokenLinkedToken,
  523. /// <summary>
  524. /// The buffer receives a TOKEN_ELEVATION structure that specifies whether the token is elevated.
  525. /// </summary>
  526. TokenElevation,
  527. /// <summary>
  528. /// The buffer receives a DWORD value that is nonzero if the token has ever been filtered.
  529. /// </summary>
  530. TokenHasRestrictions,
  531. /// <summary>
  532. /// The buffer receives a TOKEN_ACCESS_INFORMATION structure that specifies security information contained in the token.
  533. /// </summary>
  534. TokenAccessInformation,
  535. /// <summary>
  536. /// The buffer receives a DWORD value that is nonzero if virtualization is allowed for the token.
  537. /// </summary>
  538. TokenVirtualizationAllowed,
  539. /// <summary>
  540. /// The buffer receives a DWORD value that is nonzero if virtualization is enabled for the token.
  541. /// </summary>
  542. TokenVirtualizationEnabled,
  543. /// <summary>
  544. /// The buffer receives a TOKEN_MANDATORY_LABEL structure that specifies the token's integrity level.
  545. /// </summary>
  546. TokenIntegrityLevel,
  547. /// <summary>
  548. /// The buffer receives a DWORD value that is nonzero if the token has the UIAccess flag set.
  549. /// </summary>
  550. TokenUIAccess,
  551. /// <summary>
  552. /// The buffer receives a TOKEN_MANDATORY_POLICY structure that specifies the token's mandatory integrity policy.
  553. /// </summary>
  554. TokenMandatoryPolicy,
  555. /// <summary>
  556. /// The buffer receives the token's logon security identifier (SID).
  557. /// </summary>
  558. TokenLogonSid,
  559. /// <summary>
  560. /// The maximum value for this enumeration
  561. /// </summary>
  562. MaxTokenInfoClass
  563. }
  564. [StructLayout(LayoutKind.Sequential)]
  565. public struct TOKEN_GROUPS
  566. {
  567. public int GroupCount;
  568. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
  569. public SID.SID_AND_ATTRIBUTES[] Groups;
  570. public TOKEN_GROUPS(int privilegeCount)
  571. {
  572. GroupCount = privilegeCount;
  573. Groups = new SID.SID_AND_ATTRIBUTES[32];
  574. }
  575. }
  576. public struct TOKEN_PRIMARY_GROUP
  577. {
  578. public IntPtr PrimaryGroup; // PSID
  579. public TOKEN_PRIMARY_GROUP(IntPtr _sid)
  580. {
  581. PrimaryGroup = _sid;
  582. }
  583. }
  584. [StructLayout(LayoutKind.Sequential)]
  585. public struct TOKEN_SOURCE
  586. {
  587. public TOKEN_SOURCE(string name)
  588. {
  589. SourceName = new byte[8];
  590. Encoding.GetEncoding(1252).GetBytes(name, 0, name.Length, SourceName, 0);
  591. if (!SID.AllocateLocallyUniqueId(out SourceIdentifier)) throw new Win32Exception();
  592. }
  593. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
  594. public byte[] SourceName;
  595. public LUID SourceIdentifier;
  596. }
  597. [StructLayout(LayoutKind.Sequential)]
  598. public struct TOKEN_USER
  599. {
  600. public SID.SID_AND_ATTRIBUTES User;
  601. public TOKEN_USER(IntPtr _sid)
  602. {
  603. User = new SID.SID_AND_ATTRIBUTES { Sid = _sid, Attributes = 0 };
  604. }
  605. }
  606. [StructLayout(LayoutKind.Sequential)]
  607. public struct TOKEN_OWNER
  608. {
  609. public IntPtr Owner; // PSID
  610. public TOKEN_OWNER(IntPtr _owner)
  611. {
  612. Owner = _owner;
  613. }
  614. }
  615. [StructLayout(LayoutKind.Sequential)]
  616. public struct TOKEN_DEFAULT_DACL
  617. {
  618. public IntPtr DefaultDacl; // PACL
  619. }
  620. [StructLayout(LayoutKind.Sequential)]
  621. public struct TOKEN_PRIVILEGES
  622. {
  623. public int PrivilegeCount;
  624. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 36)]
  625. public LUID_AND_ATTRIBUTES[] Privileges;
  626. public TOKEN_PRIVILEGES(int privilegeCount)
  627. {
  628. PrivilegeCount = privilegeCount;
  629. Privileges = new LUID_AND_ATTRIBUTES[36];
  630. }
  631. }
  632. public enum SECURITY_IMPERSONATION_LEVEL
  633. {
  634. SecurityAnonymous,
  635. SecurityIdentification,
  636. SecurityImpersonation,
  637. SecurityDelegation
  638. }
  639. [StructLayout(LayoutKind.Sequential)]
  640. public struct SECURITY_QUALITY_OF_SERVICE
  641. {
  642. public int Length;
  643. public SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;
  644. public byte ContextTrackingMode;
  645. public byte EffectiveOnly;
  646. public SECURITY_QUALITY_OF_SERVICE(SECURITY_IMPERSONATION_LEVEL _impersonationLevel,
  647. byte _contextTrackingMode, byte _effectiveOnly)
  648. {
  649. Length = 0;
  650. ImpersonationLevel = _impersonationLevel;
  651. ContextTrackingMode = _contextTrackingMode;
  652. EffectiveOnly = _effectiveOnly;
  653. Length = Marshal.SizeOf(this);
  654. }
  655. }
  656. [Flags]
  657. public enum SE_PRIVILEGE_ATTRIBUTES : uint
  658. {
  659. SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001,
  660. SE_PRIVILEGE_ENABLED = 0x00000002,
  661. SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000
  662. }
  663. [Flags]
  664. public enum SE_GROUP_ATTRIBUTES : uint
  665. {
  666. SE_GROUP_MANDATORY = 0x00000001,
  667. SE_GROUP_ENABLED_BY_DEFAULT = 0x00000002,
  668. SE_GROUP_ENABLED = 0x00000004,
  669. SE_GROUP_OWNER = 0x00000008,
  670. SE_GROUP_USE_FOR_DENY_ONLY = 0x00000010,
  671. SE_GROUP_INTEGRITY = 0x00000020,
  672. SE_GROUP_INTEGRITY_ENABLED = 0x00000040,
  673. SE_GROUP_RESOURCE = 0x20000000,
  674. SE_GROUP_LOGON_ID = 0xC0000000,
  675. }
  676. [StructLayout(LayoutKind.Sequential)]
  677. public struct TOKEN_MANDATORY_LABEL
  678. {
  679. public SID.SID_AND_ATTRIBUTES Label;
  680. }
  681. public const byte SECURITY_STATIC_TRACKING = 0;
  682. public static readonly LUID ANONYMOUS_LOGON_LUID = new LUID { LowPart = 0x3e6, HighPart = 0 };
  683. public static readonly LUID SYSTEM_LUID = new LUID { LowPart = 0x3e7, HighPart = 0 };
  684. public const string SE_CREATE_TOKEN_NAME = "SeCreateTokenPrivilege";
  685. public const string SE_ASSIGNPRIMARYTOKEN_NAME = "SeAssignPrimaryTokenPrivilege";
  686. public const string SE_LOCK_MEMORY_NAME = "SeLockMemoryPrivilege";
  687. public const string SE_INCREASE_QUOTA_NAME = "SeIncreaseQuotaPrivilege";
  688. public const string SE_MACHINE_ACCOUNT_NAME = "SeMachineAccountPrivilege";
  689. public const string SE_TCB_NAME = "SeTcbPrivilege";
  690. public const string SE_SECURITY_NAME = "SeSecurityPrivilege";
  691. public const string SE_TAKE_OWNERSHIP_NAME = "SeTakeOwnershipPrivilege";
  692. public const string SE_LOAD_DRIVER_NAME = "SeLoadDriverPrivilege";
  693. public const string SE_SYSTEM_PROFILE_NAME = "SeSystemProfilePrivilege";
  694. public const string SE_SYSTEMTIME_NAME = "SeSystemtimePrivilege";
  695. public const string SE_PROFILE_SINGLE_PROCESS_NAME = "SeProfileSingleProcessPrivilege";
  696. public const string SE_INCREASE_BASE_PRIORITY_NAME = "SeIncreaseBasePriorityPrivilege";
  697. public const string SE_CREATE_PAGEFILE_NAME = "SeCreatePagefilePrivilege";
  698. public const string SE_CREATE_PERMANENT_NAME = "SeCreatePermanentPrivilege";
  699. public const string SE_BACKUP_NAME = "SeBackupPrivilege";
  700. public const string SE_RESTORE_NAME = "SeRestorePrivilege";
  701. public const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
  702. public const string SE_DEBUG_NAME = "SeDebugPrivilege";
  703. public const string SE_AUDIT_NAME = "SeAuditPrivilege";
  704. public const string SE_SYSTEM_ENVIRONMENT_NAME = "SeSystemEnvironmentPrivilege";
  705. public const string SE_CHANGE_NOTIFY_NAME = "SeChangeNotifyPrivilege";
  706. public const string SE_REMOTE_SHUTDOWN_NAME = "SeRemoteShutdownPrivilege";
  707. public const string SE_UNDOCK_NAME = "SeUndockPrivilege";
  708. public const string SE_SYNC_AGENT_NAME = "SeSyncAgentPrivilege";
  709. public const string SE_ENABLE_DELEGATION_NAME = "SeEnableDelegationPrivilege";
  710. public const string SE_MANAGE_VOLUME_NAME = "SeManageVolumePrivilege";
  711. public const string SE_IMPERSONATE_NAME = "SeImpersonatePrivilege";
  712. public const string SE_CREATE_GLOBAL_NAME = "SeCreateGlobalPrivilege";
  713. public const string SE_TRUSTED_CREDMAN_ACCESS_NAME = "SeTrustedCredManAccessPrivilege";
  714. public const string SE_RELABEL_NAME = "SeRelabelPrivilege";
  715. public const string SE_INCREASE_WORKING_SET_NAME = "SeIncreaseWorkingSetPrivilege";
  716. public const string SE_TIME_ZONE_NAME = "SeTimeZonePrivilege";
  717. public const string SE_CREATE_SYMBOLIC_LINK_NAME = "SeCreateSymbolicLinkPrivilege";
  718. public const string SE_DELEGATE_SESSION_USER_IMPERSONATE_NAME =
  719. "SeDelegateSessionUserImpersonatePrivilege";
  720. }
  721. public static class TokensEx
  722. {
  723. public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
  724. {
  725. // A default constructor is required for P/Invoke to instantiate the class
  726. public SafeTokenHandle(IntPtr preexistingHandle)
  727. : base(ownsHandle: true)
  728. {
  729. this.SetHandle(preexistingHandle);
  730. }
  731. public SafeTokenHandle()
  732. : base(ownsHandle: true)
  733. {
  734. }
  735. protected override bool ReleaseHandle()
  736. {
  737. return Win32.CloseHandle(handle);
  738. }
  739. }
  740. public static bool CreateTokenPrivileges(string[] privs, out Tokens.TOKEN_PRIVILEGES tokenPrivileges)
  741. {
  742. var sizeOfStruct = Marshal.SizeOf(typeof(Tokens.TOKEN_PRIVILEGES));
  743. var pPrivileges = Marshal.AllocHGlobal(sizeOfStruct);
  744. tokenPrivileges = (Tokens.TOKEN_PRIVILEGES)Marshal.PtrToStructure(
  745. pPrivileges, typeof(Tokens.TOKEN_PRIVILEGES));
  746. tokenPrivileges.PrivilegeCount = privs.Length;
  747. for (var idx = 0; idx < tokenPrivileges.PrivilegeCount; idx++)
  748. {
  749. if (!Win32.Tokens.LookupPrivilegeValue(IntPtr.Zero, privs[idx], out var luid)) return false;
  750. tokenPrivileges.Privileges[idx].Attributes =
  751. (uint)(Tokens.SE_PRIVILEGE_ATTRIBUTES.SE_PRIVILEGE_ENABLED |
  752. Tokens.SE_PRIVILEGE_ATTRIBUTES.SE_PRIVILEGE_ENABLED_BY_DEFAULT);
  753. tokenPrivileges.Privileges[idx].Luid = luid;
  754. }
  755. return true;
  756. }
  757. public static void AdjustCurrentPrivilege(string privilege)
  758. {
  759. Win32.Tokens.LookupPrivilegeValue(IntPtr.Zero, privilege, out LUID luid);
  760. Win32.Tokens.RtlAdjustPrivilege(luid, true, true, out _);
  761. }
  762. public static IntPtr GetInfoFromToken(SafeTokenHandle token, Win32.Tokens.TOKEN_INFORMATION_CLASS information)
  763. {
  764. Win32.Tokens.GetTokenInformation(token, information, IntPtr.Zero, 0, out int length);
  765. var result = Marshal.AllocHGlobal(length);
  766. Win32.Tokens.GetTokenInformation(token, information, result, length, out length);
  767. return result;
  768. }
  769. }
  770. public static class Process
  771. {
  772. [DllImport("kernel32.dll", SetLastError = true)]
  773. public static extern IntPtr GetCurrentProcess();
  774. [DllImport("kernel32.dll", SetLastError = true)]
  775. [return: MarshalAs(UnmanagedType.Bool)]
  776. public static extern bool GetExitCodeProcess(IntPtr hProcess, out uint lpExitCode);
  777. [DllImport("kernel32.dll", SetLastError = true)]
  778. public static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds);
  779. [DllImport("userenv.dll", SetLastError = true)]
  780. public static extern bool CreateEnvironmentBlock(out IntPtr lpEnvironment, TokensEx.SafeTokenHandle hToken, bool bInherit);
  781. [DllImport("userenv.dll", SetLastError = true)]
  782. public static extern bool DestroyEnvironmentBlock(IntPtr lpEnvironment);
  783. [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
  784. public static extern bool CreateProcessAsUser(Win32.TokensEx.SafeTokenHandle hToken, string lpApplicationName, StringBuilder lpCommandLine, SECURITY_ATTRIBUTES lpProcessAttributes, SECURITY_ATTRIBUTES lpThreadAttributes,
  785. bool bInheritHandles, int dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, STARTUPINFO lpStartupInfo, PROCESS_INFORMATION lpProcessInformation);
  786. [DllImport("advapi32", SetLastError = true, CharSet = CharSet.Auto)]
  787. public static extern bool CreateProcessWithToken(TokensEx.SafeTokenHandle hToken, LogonFlags dwLogonFlags,
  788. string lpApplicationName, string lpCommandLine, ProcessCreationFlags dwCreationFlags,
  789. IntPtr lpEnvironment, string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo,
  790. out PROCESS_INFORMATION lpProcessInformation);
  791. [DllImport("kernel32.dll", SetLastError = true)]
  792. internal static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess,
  793. bool bInheritHandle, int dwProcessId);
  794. [Flags]
  795. internal enum ProcessAccessFlags : uint
  796. {
  797. All = 0x001F0FFF,
  798. Terminate = 0x00000001,
  799. CreateThread = 0x00000002,
  800. VirtualMemoryOperation = 0x00000008,
  801. VirtualMemoryRead = 0x00000010,
  802. VirtualMemoryWrite = 0x00000020,
  803. DuplicateHandle = 0x00000040,
  804. CreateProcess = 0x000000080,
  805. SetQuota = 0x00000100,
  806. SetInformation = 0x00000200,
  807. QueryInformation = 0x00000400,
  808. QueryLimitedInformation = 0x00001000,
  809. Synchronize = 0x00100000
  810. }
  811. public enum LogonFlags
  812. {
  813. WithProfile = 1,
  814. NetCredentialsOnly
  815. }
  816. [StructLayout(LayoutKind.Sequential)]
  817. public struct PROCESS_INFORMATION
  818. {
  819. public IntPtr hProcess;
  820. public IntPtr hThread;
  821. public int dwProcessId;
  822. public int dwThreadId;
  823. }
  824. [Flags]
  825. public enum ProcessCreationFlags : uint
  826. {
  827. DEBUG_PROCESS = 0x00000001,
  828. DEBUG_ONLY_THIS_PROCESS = 0x00000002,
  829. CREATE_SUSPENDED = 0x00000004,
  830. DETACHED_PROCESS = 0x00000008,
  831. CREATE_NEW_CONSOLE = 0x00000010,
  832. CREATE_NEW_PROCESS_GROUP = 0x00000200,
  833. CREATE_UNICODE_ENVIRONMENT = 0x00000400,
  834. CREATE_SEPARATE_WOW_VDM = 0x00000800,
  835. CREATE_SHARED_WOW_VDM = 0x00001000,
  836. INHERIT_PARENT_AFFINITY = 0x00010000,
  837. CREATE_PROTECTED_PROCESS = 0x00040000,
  838. EXTENDED_STARTUPINFO_PRESENT = 0x00080000,
  839. CREATE_BREAKAWAY_FROM_JOB = 0x01000000,
  840. CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000,
  841. CREATE_DEFAULT_ERROR_MODE = 0x04000000,
  842. CREATE_NO_WINDOW = 0x08000000
  843. }
  844. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  845. public struct STARTUPINFO
  846. {
  847. public int cb;
  848. public string lpReserved;
  849. public string lpDesktop;
  850. public string lpTitle;
  851. public int dwX;
  852. public int dwY;
  853. public int dwXSize;
  854. public int dwYSize;
  855. public int dwXCountChars;
  856. public int dwYCountChars;
  857. public int dwFillAttribute;
  858. public int dwFlags;
  859. public short wShowWindow;
  860. public short cbReserved2;
  861. public IntPtr lpReserved2;
  862. public IntPtr hStdInput;
  863. public IntPtr hStdOutput;
  864. public IntPtr hStdError;
  865. }
  866. }
  867. public static class IO
  868. {
  869. [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  870. public static extern IntPtr CreateFile([MarshalAs(UnmanagedType.LPTStr)] string filename,
  871. [MarshalAs(UnmanagedType.U4)] FileAccess access, [MarshalAs(UnmanagedType.U4)] FileShare share,
  872. IntPtr securityAttributes, // optional SECURITY_ATTRIBUTES struct or IntPtr.Zero
  873. [MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
  874. [MarshalAs(UnmanagedType.U4)] FileAttributes flagsAndAttributes, IntPtr templateFile);
  875. [Flags]
  876. public enum FileAccess : uint
  877. {
  878. AccessSystemSecurity = 0x1000000,
  879. MaximumAllowed = 0x2000000,
  880. Delete = 0x10000,
  881. ReadControl = 0x20000,
  882. WriteDAC = 0x40000,
  883. WriteOwner = 0x80000,
  884. Synchronize = 0x100000,
  885. StandardRightsRequired = 0xF0000,
  886. StandardRightsRead = ReadControl,
  887. StandardRightsWrite = ReadControl,
  888. StandardRightsExecute = ReadControl,
  889. StandardRightsAll = 0x1F0000,
  890. SpecificRightsAll = 0xFFFF,
  891. FILE_READ_DATA = 0x0001, // file & pipe
  892. FILE_LIST_DIRECTORY = 0x0001, // directory
  893. FILE_WRITE_DATA = 0x0002, // file & pipe
  894. FILE_ADD_FILE = 0x0002, // directory
  895. FILE_APPEND_DATA = 0x0004, // file
  896. FILE_ADD_SUBDIRECTORY = 0x0004, // directory
  897. FILE_CREATE_PIPE_INSTANCE = 0x0004, // named pipe
  898. FILE_READ_EA = 0x0008, // file & directory
  899. FILE_WRITE_EA = 0x0010, // file & directory
  900. FILE_EXECUTE = 0x0020, // file
  901. FILE_TRAVERSE = 0x0020, // directory
  902. FILE_DELETE_CHILD = 0x0040, // directory
  903. FILE_READ_ATTRIBUTES = 0x0080, // all
  904. FILE_WRITE_ATTRIBUTES = 0x0100, // all
  905. //
  906. // Generic Section
  907. //
  908. GenericRead = 0x80000000,
  909. GenericWrite = 0x40000000,
  910. GenericExecute = 0x20000000,
  911. GenericAll = 0x10000000,
  912. SPECIFIC_RIGHTS_ALL = 0x00FFFF,
  913. FILE_ALL_ACCESS = StandardRightsRequired | Synchronize | 0x1FF,
  914. FILE_GENERIC_READ = StandardRightsRead | FILE_READ_DATA | FILE_READ_ATTRIBUTES | FILE_READ_EA |
  915. Synchronize,
  916. FILE_GENERIC_WRITE = StandardRightsWrite | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA |
  917. FILE_APPEND_DATA | Synchronize,
  918. FILE_GENERIC_EXECUTE = StandardRightsExecute | FILE_READ_ATTRIBUTES | FILE_EXECUTE | Synchronize
  919. }
  920. [Flags]
  921. public enum FileShare : uint
  922. {
  923. None = 0x00000000,
  924. Read = 0x00000001,
  925. Write = 0x00000002,
  926. Delete = 0x00000004
  927. }
  928. public enum FileMode : uint
  929. {
  930. New = 1,
  931. CreateAlways = 2,
  932. OpenExisting = 3,
  933. OpenAlways = 4,
  934. TruncateExisting = 5
  935. }
  936. [Flags]
  937. public enum FileAttributes : uint
  938. {
  939. Readonly = 0x00000001,
  940. Hidden = 0x00000002,
  941. System = 0x00000004,
  942. Directory = 0x00000010,
  943. Archive = 0x00000020,
  944. Device = 0x00000040,
  945. Normal = 0x00000080,
  946. Temporary = 0x00000100,
  947. SparseFile = 0x00000200,
  948. ReparsePoint = 0x00000400,
  949. Compressed = 0x00000800,
  950. Offline = 0x00001000,
  951. NotContentIndexed = 0x00002000,
  952. Encrypted = 0x00004000,
  953. Write_Through = 0x80000000,
  954. Overlapped = 0x40000000,
  955. NoBuffering = 0x20000000,
  956. RandomAccess = 0x10000000,
  957. SequentialScan = 0x08000000,
  958. DeleteOnClose = 0x04000000,
  959. BackupSemantics = 0x02000000,
  960. PosixSemantics = 0x01000000,
  961. OpenReparsePoint = 0x00200000,
  962. OpenNoRecall = 0x00100000,
  963. FirstPipeInstance = 0x00080000
  964. }
  965. }
  966. public static class SID
  967. {
  968. [DllImport("advapi32.dll", SetLastError = true)]
  969. public static extern bool AllocateAndInitializeSid(ref SID_IDENTIFIER_AUTHORITY pIdentifierAuthority,
  970. byte nSubAuthorityCount, int dwSubAuthority0, int dwSubAuthority1, int dwSubAuthority2,
  971. int dwSubAuthority3, int dwSubAuthority4, int dwSubAuthority5, int dwSubAuthority6, int dwSubAuthority7,
  972. out IntPtr pSid);
  973. [DllImport("advapi32.dll")]
  974. public static extern bool AllocateLocallyUniqueId(out LUID allocated);
  975. [DllImport("advapi32", CharSet = CharSet.Auto, SetLastError = true)]
  976. public static extern bool ConvertSidToStringSid(IntPtr pSid, out string strSid);
  977. [DllImport("advapi32.dll", SetLastError = true)]
  978. public static extern bool ConvertStringSidToSid(string StringSid, out IntPtr ptrSid);
  979. [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  980. public static extern int GetLengthSid(IntPtr pSid);
  981. [DllImport("advapi32.dll")]
  982. public static extern IntPtr FreeSid(IntPtr pSid);
  983. [StructLayout(LayoutKind.Sequential)]
  984. public struct SID_AND_ATTRIBUTES
  985. {
  986. public IntPtr Sid;
  987. public uint Attributes;
  988. }
  989. [StructLayout(LayoutKind.Sequential)]
  990. public struct SID_IDENTIFIER_AUTHORITY
  991. {
  992. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.I1)]
  993. public byte[] Value;
  994. public SID_IDENTIFIER_AUTHORITY(byte[] value)
  995. {
  996. this.Value = value;
  997. }
  998. }
  999. public enum SECURITY_MANDATORY_LABEL
  1000. {
  1001. Untrusted = 0x00000000,
  1002. Low = 0x00001000,
  1003. Medium = 0x00002000,
  1004. MediumPlus = 0x00002100,
  1005. High = 0x00003000,
  1006. System = 0x00004000,
  1007. }
  1008. public static SID_IDENTIFIER_AUTHORITY SECURITY_MANDATORY_LABEL_AUTHORITY =
  1009. new SID_IDENTIFIER_AUTHORITY(new byte[] { 0, 0, 0, 0, 0, 16 });
  1010. public const int NtSecurityAuthority = 5;
  1011. public const int AuthenticatedUser = 11;
  1012. public const string DOMAIN_ALIAS_RID_ADMINS = "S-1-5-32-544";
  1013. public const string DOMAIN_ALIAS_RID_LOCAL_AND_ADMIN_GROUP = "S-1-5-114";
  1014. public const string TRUSTED_INSTALLER_RID =
  1015. "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";
  1016. public const string INTEGRITY_UNTRUSTED_SID = "S-1-16-0";
  1017. public const string INTEGRITY_LOW_SID = "S-1-16-4096";
  1018. public const string INTEGRITY_MEDIUM_SID = "S-1-16-8192";
  1019. public const string INTEGRITY_MEDIUMPLUS_SID = "S-1-16-8448";
  1020. public const string INTEGRITY_HIGH_SID = "S-1-16-12288";
  1021. public const string INTEGRITY_SYSTEM_SID = "S-1-16-16384";
  1022. public const string INTEGRITY_PROTECTEDPROCESS_SID = "S-1-16-20480";
  1023. }
  1024. public static class WTS
  1025. {
  1026. [DllImport("wtsapi32.dll", SetLastError = true)]
  1027. public static extern int WTSEnumerateSessions(IntPtr hServer, int Reserved, int Version,
  1028. ref IntPtr ppSessionInfo, ref int pCount);
  1029. [DllImport("wtsapi32.dll", SetLastError = true)]
  1030. public static extern bool WTSEnumerateProcesses(IntPtr serverHandle, Int32 reserved, Int32 version,
  1031. ref IntPtr ppProcessInfo, ref Int32 pCount);
  1032. [DllImport("kernel32.dll")]
  1033. public static extern uint WTSGetActiveConsoleSessionId();
  1034. [DllImport("wtsapi32.dll", SetLastError = true)]
  1035. public static extern bool WTSQueryUserToken(UInt32 sessionId, out TokensEx.SafeTokenHandle Token);
  1036. [DllImport("wtsapi32.dll")]
  1037. public static extern void WTSFreeMemory(IntPtr pMemory);
  1038. [StructLayout(LayoutKind.Sequential)]
  1039. public struct WTS_SESSION_INFO
  1040. {
  1041. public Int32 SessionID;
  1042. [MarshalAs(UnmanagedType.LPStr)]
  1043. public String pWinStationName;
  1044. public WTS_CONNECTSTATE_CLASS State;
  1045. }
  1046. public enum WTS_CONNECTSTATE_CLASS
  1047. {
  1048. WTSActive,
  1049. WTSConnected,
  1050. WTSConnectQuery,
  1051. WTSShadow,
  1052. WTSDisconnected,
  1053. WTSIdle,
  1054. WTSListen,
  1055. WTSReset,
  1056. WTSDown,
  1057. WTSInit
  1058. }
  1059. public struct WTS_PROCESS_INFO
  1060. {
  1061. public int SessionID;
  1062. public int ProcessID;
  1063. public IntPtr ProcessName;
  1064. public IntPtr UserSid;
  1065. }
  1066. }
  1067. public static class LSA
  1068. {
  1069. [DllImport("secur32.dll", SetLastError = false)]
  1070. public static extern uint LsaFreeReturnBuffer(IntPtr buffer);
  1071. [DllImport("secur32.dll", SetLastError = false)]
  1072. public static extern uint LsaEnumerateLogonSessions(out ulong LogonSessionCount,
  1073. out IntPtr LogonSessionList);
  1074. [DllImport("secur32.dll", SetLastError = false)]
  1075. public static extern uint LsaGetLogonSessionData(IntPtr luid, out IntPtr ppLogonSessionData);
  1076. [StructLayout(LayoutKind.Sequential)]
  1077. public struct LSA_UNICODE_STRING
  1078. {
  1079. public UInt16 Length;
  1080. public UInt16 MaximumLength;
  1081. public IntPtr buffer;
  1082. }
  1083. [StructLayout(LayoutKind.Sequential)]
  1084. public struct SECURITY_LOGON_SESSION_DATA
  1085. {
  1086. public UInt32 Size;
  1087. public LUID LoginID;
  1088. public LSA_UNICODE_STRING Username;
  1089. public LSA_UNICODE_STRING LoginDomain;
  1090. public LSA_UNICODE_STRING AuthenticationPackage;
  1091. public UInt32 LogonType;
  1092. public UInt32 Session;
  1093. public IntPtr PSiD;
  1094. public UInt64 LoginTime;
  1095. public LSA_UNICODE_STRING LogonServer;
  1096. public LSA_UNICODE_STRING DnsDomainName;
  1097. public LSA_UNICODE_STRING Upn;
  1098. }
  1099. public enum SECURITY_LOGON_TYPE : uint
  1100. {
  1101. Interactive = 2, //The security principal is logging on interactively.
  1102. Network, //The security principal is logging using a network.
  1103. Batch, //The logon is for a batch process.
  1104. Service, //The logon is for a service account.
  1105. Proxy, //Not supported.
  1106. Unlock, //The logon is an attempt to unlock a workstation.
  1107. NetworkCleartext, //The logon is a network logon with cleartext credentials.
  1108. NewCredentials, // Allows the caller to clone its current token and specify new credentials for outbound connections.
  1109. RemoteInteractive, // A terminal server session that is both remote and interactive.
  1110. CachedInteractive, // Attempt to use the cached credentials without going out across the network.
  1111. CachedRemoteInteractive, // Same as RemoteInteractive, except used publicly for auditing purposes.
  1112. CachedUnlock // The logon is an attempt to unlock a workstation.
  1113. }
  1114. }
  1115. [DllImport("kernel32.dll", SetLastError = true)]
  1116. public static extern IntPtr LocalFree(IntPtr hMem);
  1117. [DllImport("kernel32.dll", SetLastError = true)]
  1118. [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  1119. [SuppressUnmanagedCodeSecurity]
  1120. [return: MarshalAs(UnmanagedType.Bool)]
  1121. public static extern bool CloseHandle(IntPtr hObject);
  1122. [StructLayout(LayoutKind.Sequential)]
  1123. public struct LUID
  1124. {
  1125. public UInt32 LowPart;
  1126. public UInt32 HighPart;
  1127. }
  1128. [StructLayout(LayoutKind.Sequential, Pack = 4)]
  1129. public struct LUID_AND_ATTRIBUTES
  1130. {
  1131. public LUID Luid;
  1132. public UInt32 Attributes;
  1133. }
  1134. [StructLayout(LayoutKind.Sequential)]
  1135. public class SECURITY_ATTRIBUTES
  1136. {
  1137. public int nLength = 12;
  1138. public SafeLocalMemHandle lpSecurityDescriptor = new SafeLocalMemHandle(IntPtr.Zero, false);
  1139. public bool bInheritHandle;
  1140. }
  1141. [HostProtection(MayLeakOnAbort = true)]
  1142. [SuppressUnmanagedCodeSecurityAttribute]
  1143. public sealed class SafeLocalMemHandle : SafeHandleZeroOrMinusOneIsInvalid
  1144. {
  1145. [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
  1146. internal SafeLocalMemHandle(IntPtr existingHandle, bool ownsHandle) : base(ownsHandle)
  1147. {
  1148. SetHandle(existingHandle);
  1149. }
  1150. [DllImport("kernel32.dll")]
  1151. [ResourceExposure(ResourceScope.None)]
  1152. [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  1153. private static extern IntPtr LocalFree(IntPtr hMem);
  1154. override protected bool ReleaseHandle()
  1155. {
  1156. return LocalFree(handle) == IntPtr.Zero;
  1157. }
  1158. }
  1159. [StructLayout(LayoutKind.Explicit, Size = 8)]
  1160. public struct LARGE_INTEGER
  1161. {
  1162. [FieldOffset(0)] public int Low;
  1163. [FieldOffset(4)] public int High;
  1164. [FieldOffset(0)] public long QuadPart;
  1165. public LARGE_INTEGER(long _quad)
  1166. {
  1167. Low = 0;
  1168. High = 0;
  1169. QuadPart = _quad;
  1170. }
  1171. public long ToInt64()
  1172. {
  1173. return ((long)High << 32) | (uint)Low;
  1174. }
  1175. public static LARGE_INTEGER FromInt64(long value)
  1176. {
  1177. return new LARGE_INTEGER { Low = (int)value, High = (int)(value >> 32) };
  1178. }
  1179. }
  1180. [StructLayout(LayoutKind.Sequential)]
  1181. public struct UNICODE_STRING : IDisposable
  1182. {
  1183. public ushort Length;
  1184. public ushort MaximumLength;
  1185. private IntPtr buffer;
  1186. public UNICODE_STRING(string s)
  1187. {
  1188. Length = (ushort)(s.Length * 2);
  1189. MaximumLength = (ushort)(Length + 2);
  1190. buffer = Marshal.StringToHGlobalUni(s);
  1191. }
  1192. public void Dispose()
  1193. {
  1194. Marshal.FreeHGlobal(buffer);
  1195. buffer = IntPtr.Zero;
  1196. }
  1197. public override string ToString()
  1198. {
  1199. return Marshal.PtrToStringUni(buffer);
  1200. }
  1201. }
  1202. public const int STATUS_SUCCESS = 0;
  1203. public static readonly int STATUS_INFO_LENGTH_MISMATCH = Convert.ToInt32("0xC0000004", 16);
  1204. public const int ERROR_BAD_LENGTH = 0x00000018;
  1205. public const int ERROR_INSUFFICIENT_BUFFER = 0x0000007A;
  1206. public static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
  1207. public enum NtStatus : uint
  1208. {
  1209. // Success
  1210. Success = 0x00000000,
  1211. Wait0 = 0x00000000,
  1212. Wait1 = 0x00000001,
  1213. Wait2 = 0x00000002,
  1214. Wait3 = 0x00000003,
  1215. Wait63 = 0x0000003f,
  1216. Abandoned = 0x00000080,
  1217. AbandonedWait0 = 0x00000080,
  1218. AbandonedWait1 = 0x00000081,
  1219. AbandonedWait2 = 0x00000082,
  1220. AbandonedWait3 = 0x00000083,
  1221. AbandonedWait63 = 0x000000bf,
  1222. UserApc = 0x000000c0,
  1223. KernelApc = 0x00000100,
  1224. Alerted = 0x00000101,
  1225. Timeout = 0x00000102,
  1226. Pending = 0x00000103,
  1227. Reparse = 0x00000104,
  1228. MoreEntries = 0x00000105,
  1229. NotAllAssigned = 0x00000106,
  1230. SomeNotMapped = 0x00000107,
  1231. OpLockBreakInProgress = 0x00000108,
  1232. VolumeMounted = 0x00000109,
  1233. RxActCommitted = 0x0000010a,
  1234. NotifyCleanup = 0x0000010b,
  1235. NotifyEnumDir = 0x0000010c,
  1236. NoQuotasForAccount = 0x0000010d,
  1237. PrimaryTransportConnectFailed = 0x0000010e,
  1238. PageFaultTransition = 0x00000110,
  1239. PageFaultDemandZero = 0x00000111,
  1240. PageFaultCopyOnWrite = 0x00000112,
  1241. PageFaultGuardPage = 0x00000113,
  1242. PageFaultPagingFile = 0x00000114,
  1243. CrashDump = 0x00000116,
  1244. ReparseObject = 0x00000118,
  1245. NothingToTerminate = 0x00000122,
  1246. ProcessNotInJob = 0x00000123,
  1247. ProcessInJob = 0x00000124,
  1248. ProcessCloned = 0x00000129,
  1249. FileLockedWithOnlyReaders = 0x0000012a,
  1250. FileLockedWithWriters = 0x0000012b,
  1251. // Informational
  1252. Informational = 0x40000000,
  1253. ObjectNameExists = 0x40000000,
  1254. ThreadWasSuspended = 0x40000001,
  1255. WorkingSetLimitRange = 0x40000002,
  1256. ImageNotAtBase = 0x40000003,
  1257. RegistryRecovered = 0x40000009,
  1258. // Warning
  1259. Warning = 0x80000000,
  1260. GuardPageViolation = 0x80000001,
  1261. DatatypeMisalignment = 0x80000002,
  1262. Breakpoint = 0x80000003,
  1263. SingleStep = 0x80000004,
  1264. BufferOverflow = 0x80000005,
  1265. NoMoreFiles = 0x80000006,
  1266. HandlesClosed = 0x8000000a,
  1267. PartialCopy = 0x8000000d,
  1268. DeviceBusy = 0x80000011,
  1269. InvalidEaName = 0x80000013,
  1270. EaListInconsistent = 0x80000014,
  1271. NoMoreEntries = 0x8000001a,
  1272. LongJump = 0x80000026,
  1273. DllMightBeInsecure = 0x8000002b,
  1274. // Error
  1275. Error = 0xc0000000,
  1276. Unsuccessful = 0xc0000001,
  1277. NotImplemented = 0xc0000002,
  1278. InvalidInfoClass = 0xc0000003,
  1279. InfoLengthMismatch = 0xc0000004,
  1280. AccessViolation = 0xc0000005,
  1281. InPageError = 0xc0000006,
  1282. PagefileQuota = 0xc0000007,
  1283. InvalidHandle = 0xc0000008,
  1284. BadInitialStack = 0xc0000009,
  1285. BadInitialPc = 0xc000000a,
  1286. InvalidCid = 0xc000000b,
  1287. TimerNotCanceled = 0xc000000c,
  1288. InvalidParameter = 0xc000000d,
  1289. NoSuchDevice = 0xc000000e,
  1290. NoSuchFile = 0xc000000f,
  1291. InvalidDeviceRequest = 0xc0000010,
  1292. EndOfFile = 0xc0000011,
  1293. WrongVolume = 0xc0000012,
  1294. NoMediaInDevice = 0xc0000013,
  1295. NoMemory = 0xc0000017,
  1296. NotMappedView = 0xc0000019,
  1297. UnableToFreeVm = 0xc000001a,
  1298. UnableToDeleteSection = 0xc000001b,
  1299. IllegalInstruction = 0xc000001d,
  1300. AlreadyCommitted = 0xc0000021,
  1301. AccessDenied = 0xc0000022,
  1302. BufferTooSmall = 0xc0000023,
  1303. ObjectTypeMismatch = 0xc0000024,
  1304. NonContinuableException = 0xc0000025,
  1305. BadStack = 0xc0000028,
  1306. NotLocked = 0xc000002a,
  1307. NotCommitted = 0xc000002d,
  1308. InvalidParameterMix = 0xc0000030,
  1309. ObjectNameInvalid = 0xc0000033,
  1310. ObjectNameNotFound = 0xc0000034,
  1311. ObjectNameCollision = 0xc0000035,
  1312. ObjectPathInvalid = 0xc0000039,
  1313. ObjectPathNotFound = 0xc000003a,
  1314. ObjectPathSyntaxBad = 0xc000003b,
  1315. DataOverrun = 0xc000003c,
  1316. DataLate = 0xc000003d,
  1317. DataError = 0xc000003e,
  1318. CrcError = 0xc000003f,
  1319. SectionTooBig = 0xc0000040,
  1320. PortConnectionRefused = 0xc0000041,
  1321. InvalidPortHandle = 0xc0000042,
  1322. SharingViolation = 0xc0000043,
  1323. QuotaExceeded = 0xc0000044,
  1324. InvalidPageProtection = 0xc0000045,
  1325. MutantNotOwned = 0xc0000046,
  1326. SemaphoreLimitExceeded = 0xc0000047,
  1327. PortAlreadySet = 0xc0000048,
  1328. SectionNotImage = 0xc0000049,
  1329. SuspendCountExceeded = 0xc000004a,
  1330. ThreadIsTerminating = 0xc000004b,
  1331. BadWorkingSetLimit = 0xc000004c,
  1332. IncompatibleFileMap = 0xc000004d,
  1333. SectionProtection = 0xc000004e,
  1334. EasNotSupported = 0xc000004f,
  1335. EaTooLarge = 0xc0000050,
  1336. NonExistentEaEntry = 0xc0000051,
  1337. NoEasOnFile = 0xc0000052,
  1338. EaCorruptError = 0xc0000053,
  1339. FileLockConflict = 0xc0000054,
  1340. LockNotGranted = 0xc0000055,
  1341. DeletePending = 0xc0000056,
  1342. CtlFileNotSupported = 0xc0000057,
  1343. UnknownRevision = 0xc0000058,
  1344. RevisionMismatch = 0xc0000059,
  1345. InvalidOwner = 0xc000005a,
  1346. InvalidPrimaryGroup = 0xc000005b,
  1347. NoImpersonationToken = 0xc000005c,
  1348. CantDisableMandatory = 0xc000005d,
  1349. NoLogonServers = 0xc000005e,
  1350. NoSuchLogonSession = 0xc000005f,
  1351. NoSuchPrivilege = 0xc0000060,
  1352. PrivilegeNotHeld = 0xc0000061,
  1353. InvalidAccountName = 0xc0000062,
  1354. UserExists = 0xc0000063,
  1355. NoSuchUser = 0xc0000064,
  1356. GroupExists = 0xc0000065,
  1357. NoSuchGroup = 0xc0000066,
  1358. MemberInGroup = 0xc0000067,
  1359. MemberNotInGroup = 0xc0000068,
  1360. LastAdmin = 0xc0000069,
  1361. WrongPassword = 0xc000006a,
  1362. IllFormedPassword = 0xc000006b,
  1363. PasswordRestriction = 0xc000006c,
  1364. LogonFailure = 0xc000006d,
  1365. AccountRestriction = 0xc000006e,
  1366. InvalidLogonHours = 0xc000006f,
  1367. InvalidWorkstation = 0xc0000070,
  1368. PasswordExpired = 0xc0000071,
  1369. AccountDisabled = 0xc0000072,
  1370. NoneMapped = 0xc0000073,
  1371. TooManyLuidsRequested = 0xc0000074,
  1372. LuidsExhausted = 0xc0000075,
  1373. InvalidSubAuthority = 0xc0000076,
  1374. InvalidAcl = 0xc0000077,
  1375. InvalidSid = 0xc0000078,
  1376. InvalidSecurityDescr = 0xc0000079,
  1377. ProcedureNotFound = 0xc000007a,
  1378. InvalidImageFormat = 0xc000007b,
  1379. NoToken = 0xc000007c,
  1380. BadInheritanceAcl = 0xc000007d,
  1381. RangeNotLocked = 0xc000007e,
  1382. DiskFull = 0xc000007f,
  1383. ServerDisabled = 0xc0000080,
  1384. ServerNotDisabled = 0xc0000081,
  1385. TooManyGuidsRequested = 0xc0000082,
  1386. GuidsExhausted = 0xc0000083,
  1387. InvalidIdAuthority = 0xc0000084,
  1388. AgentsExhausted = 0xc0000085,
  1389. InvalidVolumeLabel = 0xc0000086,
  1390. SectionNotExtended = 0xc0000087,
  1391. NotMappedData = 0xc0000088,
  1392. ResourceDataNotFound = 0xc0000089,
  1393. ResourceTypeNotFound = 0xc000008a,
  1394. ResourceNameNotFound = 0xc000008b,
  1395. ArrayBoundsExceeded = 0xc000008c,
  1396. FloatDenormalOperand = 0xc000008d,
  1397. FloatDivideByZero = 0xc000008e,
  1398. FloatInexactResult = 0xc000008f,
  1399. FloatInvalidOperation = 0xc0000090,
  1400. FloatOverflow = 0xc0000091,
  1401. FloatStackCheck = 0xc0000092,
  1402. FloatUnderflow = 0xc0000093,
  1403. IntegerDivideByZero = 0xc0000094,
  1404. IntegerOverflow = 0xc0000095,
  1405. PrivilegedInstruction = 0xc0000096,
  1406. TooManyPagingFiles = 0xc0000097,
  1407. FileInvalid = 0xc0000098,
  1408. InstanceNotAvailable = 0xc00000ab,
  1409. PipeNotAvailable = 0xc00000ac,
  1410. InvalidPipeState = 0xc00000ad,
  1411. PipeBusy = 0xc00000ae,
  1412. IllegalFunction = 0xc00000af,
  1413. PipeDisconnected = 0xc00000b0,
  1414. PipeClosing = 0xc00000b1,
  1415. PipeConnected = 0xc00000b2,
  1416. PipeListening = 0xc00000b3,
  1417. InvalidReadMode = 0xc00000b4,
  1418. IoTimeout = 0xc00000b5,
  1419. FileForcedClosed = 0xc00000b6,
  1420. ProfilingNotStarted = 0xc00000b7,
  1421. ProfilingNotStopped = 0xc00000b8,
  1422. NotSameDevice = 0xc00000d4,
  1423. FileRenamed = 0xc00000d5,
  1424. CantWait = 0xc00000d8,
  1425. PipeEmpty = 0xc00000d9,
  1426. CantTerminateSelf = 0xc00000db,
  1427. InternalError = 0xc00000e5,
  1428. InvalidParameter1 = 0xc00000ef,
  1429. InvalidParameter2 = 0xc00000f0,
  1430. InvalidParameter3 = 0xc00000f1,
  1431. InvalidParameter4 = 0xc00000f2,
  1432. InvalidParameter5 = 0xc00000f3,
  1433. InvalidParameter6 = 0xc00000f4,
  1434. InvalidParameter7 = 0xc00000f5,
  1435. InvalidParameter8 = 0xc00000f6,
  1436. InvalidParameter9 = 0xc00000f7,
  1437. InvalidParameter10 = 0xc00000f8,
  1438. InvalidParameter11 = 0xc00000f9,
  1439. InvalidParameter12 = 0xc00000fa,
  1440. MappedFileSizeZero = 0xc000011e,
  1441. TooManyOpenedFiles = 0xc000011f,
  1442. Cancelled = 0xc0000120,
  1443. CannotDelete = 0xc0000121,
  1444. InvalidComputerName = 0xc0000122,
  1445. FileDeleted = 0xc0000123,
  1446. SpecialAccount = 0xc0000124,
  1447. SpecialGroup = 0xc0000125,
  1448. SpecialUser = 0xc0000126,
  1449. MembersPrimaryGroup = 0xc0000127,
  1450. FileClosed = 0xc0000128,
  1451. TooManyThreads = 0xc0000129,
  1452. ThreadNotInProcess = 0xc000012a,
  1453. TokenAlreadyInUse = 0xc000012b,
  1454. PagefileQuotaExceeded = 0xc000012c,
  1455. CommitmentLimit = 0xc000012d,
  1456. InvalidImageLeFormat = 0xc000012e,
  1457. InvalidImageNotMz = 0xc000012f,
  1458. InvalidImageProtect = 0xc0000130,
  1459. InvalidImageWin16 = 0xc0000131,
  1460. LogonServer = 0xc0000132,
  1461. DifferenceAtDc = 0xc0000133,
  1462. SynchronizationRequired = 0xc0000134,
  1463. DllNotFound = 0xc0000135,
  1464. IoPrivilegeFailed = 0xc0000137,
  1465. OrdinalNotFound = 0xc0000138,
  1466. EntryPointNotFound = 0xc0000139,
  1467. ControlCExit = 0xc000013a,
  1468. PortNotSet = 0xc0000353,
  1469. DebuggerInactive = 0xc0000354,
  1470. CallbackBypass = 0xc0000503,
  1471. PortClosed = 0xc0000700,
  1472. MessageLost = 0xc0000701,
  1473. InvalidMessage = 0xc0000702,
  1474. RequestCanceled = 0xc0000703,
  1475. RecursiveDispatch = 0xc0000704,
  1476. LpcReceiveBufferExpected = 0xc0000705,
  1477. LpcInvalidConnectionUsage = 0xc0000706,
  1478. LpcRequestsNotAllowed = 0xc0000707,
  1479. ResourceInUse = 0xc0000708,
  1480. ProcessIsProtected = 0xc0000712,
  1481. VolumeDirty = 0xc0000806,
  1482. FileCheckedOut = 0xc0000901,
  1483. CheckOutRequired = 0xc0000902,
  1484. BadFileType = 0xc0000903,
  1485. FileTooLarge = 0xc0000904,
  1486. FormsAuthRequired = 0xc0000905,
  1487. VirusInfected = 0xc0000906,
  1488. VirusDeleted = 0xc0000907,
  1489. TransactionalConflict = 0xc0190001,
  1490. InvalidTransaction = 0xc0190002,
  1491. TransactionNotActive = 0xc0190003,
  1492. TmInitializationFailed = 0xc0190004,
  1493. RmNotActive = 0xc0190005,
  1494. RmMetadataCorrupt = 0xc0190006,
  1495. TransactionNotJoined = 0xc0190007,
  1496. DirectoryNotRm = 0xc0190008,
  1497. CouldNotResizeLog = 0xc0190009,
  1498. TransactionsUnsupportedRemote = 0xc019000a,
  1499. LogResizeInvalidSize = 0xc019000b,
  1500. RemoteFileVersionMismatch = 0xc019000c,
  1501. CrmProtocolAlreadyExists = 0xc019000f,
  1502. TransactionPropagationFailed = 0xc0190010,
  1503. CrmProtocolNotFound = 0xc0190011,
  1504. TransactionSuperiorExists = 0xc0190012,
  1505. TransactionRequestNotValid = 0xc0190013,
  1506. TransactionNotRequested = 0xc0190014,
  1507. TransactionAlreadyAborted = 0xc0190015,
  1508. TransactionAlreadyCommitted = 0xc0190016,
  1509. TransactionInvalidMarshallBuffer = 0xc0190017,
  1510. CurrentTransactionNotValid = 0xc0190018,
  1511. LogGrowthFailed = 0xc0190019,
  1512. ObjectNoLongerExists = 0xc0190021,
  1513. StreamMiniversionNotFound = 0xc0190022,
  1514. StreamMiniversionNotValid = 0xc0190023,
  1515. MiniversionInaccessibleFromSpecifiedTransaction = 0xc0190024,
  1516. CantOpenMiniversionWithModifyIntent = 0xc0190025,
  1517. CantCreateMoreStreamMiniversions = 0xc0190026,
  1518. HandleNoLongerValid = 0xc0190028,
  1519. NoTxfMetadata = 0xc0190029,
  1520. LogCorruptionDetected = 0xc0190030,
  1521. CantRecoverWithHandleOpen = 0xc0190031,
  1522. RmDisconnected = 0xc0190032,
  1523. EnlistmentNotSuperior = 0xc0190033,
  1524. RecoveryNotNeeded = 0xc0190034,
  1525. RmAlreadyStarted = 0xc0190035,
  1526. FileIdentityNotPersistent = 0xc0190036,
  1527. CantBreakTransactionalDependency = 0xc0190037,
  1528. CantCrossRmBoundary = 0xc0190038,
  1529. TxfDirNotEmpty = 0xc0190039,
  1530. IndoubtTransactionsExist = 0xc019003a,
  1531. TmVolatile = 0xc019003b,
  1532. RollbackTimerExpired = 0xc019003c,
  1533. TxfAttributeCorrupt = 0xc019003d,
  1534. EfsNotAllowedInTransaction = 0xc019003e,
  1535. TransactionalOpenNotAllowed = 0xc019003f,
  1536. TransactedMappingUnsupportedRemote = 0xc0190040,
  1537. TxfMetadataAlreadyPresent = 0xc0190041,
  1538. TransactionScopeCallbacksNotSet = 0xc0190042,
  1539. TransactionRequiredPromotion = 0xc0190043,
  1540. CannotExecuteFileInTransaction = 0xc0190044,
  1541. TransactionsNotFrozen = 0xc0190045,
  1542. MaximumNtStatus = 0xffffffff
  1543. }
  1544. }
  1545. }