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.

1638 lines
74 KiB

9 months ago
6 months ago
9 months ago
6 months ago
9 months ago
6 months ago
9 months ago
6 months ago
9 months ago
6 months ago
9 months ago
6 months ago
9 months ago
6 months ago
9 months ago
6 months ago
9 months ago
6 months ago
9 months ago
6 months ago
9 months ago
6 months ago
9 months ago
  1. using System.IO;
  2. using System.Windows;
  3. using TrustedUninstaller.Shared.Actions;
  4. using TrustedUninstaller.Shared.Tasks;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.Linq;
  9. using System.Runtime.InteropServices;
  10. using System.Security.Principal;
  11. using System.ServiceProcess;
  12. using System.Text;
  13. using System.Threading;
  14. using Microsoft.Win32;
  15. namespace TrustedUninstaller.Shared
  16. {
  17. public static class Defender
  18. {
  19. private static KeyValuePair<string, ProcessType>[] DefenderItems =
  20. {
  21. new KeyValuePair<string, ProcessType>("CompatTelRunner", ProcessType.Exe),
  22. new KeyValuePair<string, ProcessType>("DWWIN", ProcessType.Exe),
  23. new KeyValuePair<string, ProcessType>("DeviceCensus", ProcessType.Exe),
  24. new KeyValuePair<string, ProcessType>("GameBarPresenceWriter", ProcessType.Exe),
  25. new KeyValuePair<string, ProcessType>("SecurityHealthHost", ProcessType.Exe),
  26. new KeyValuePair<string, ProcessType>("SecurityHealthService", ProcessType.Exe), // SecurityHealthService
  27. new KeyValuePair<string, ProcessType>("SecurityHealthSystray", ProcessType.Exe),
  28. new KeyValuePair<string, ProcessType>("smartscreen", ProcessType.Exe),
  29. //new KeyValuePair<string, ProcessType>("MpCmdRun", ProcessType.Exe),
  30. new KeyValuePair<string, ProcessType>("NisSrv", ProcessType.Exe),
  31. new KeyValuePair<string, ProcessType>("wscsvc", ProcessType.Service), // Windows Security Center
  32. new KeyValuePair<string, ProcessType>("WinDefend", ProcessType.Service), // Microsoft Defender Antivirus Service
  33. new KeyValuePair<string, ProcessType>("Sense", ProcessType.Service), // Windows Defender Advanced Threat Protection Service
  34. new KeyValuePair<string, ProcessType>("WdNisSvc", ProcessType.Service), // Microsoft Defender Antivirus Network Inspection Service
  35. new KeyValuePair<string, ProcessType>("WdNisDrv", ProcessType.Device), // Microsoft Defender Antivirus Network Inspection Driver
  36. //new KeyValuePair<string, ProcessType>("WdFilter", ProcessType.Device), // Windows Defender Disk inspection Minifilter,
  37. };
  38. //[DllImport("Unlocker.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
  39. //private static extern bool EzUnlockFileW(string path);
  40. private static readonly string[] defenderDirs =
  41. {
  42. Environment.ExpandEnvironmentVariables(@"%ProgramData%\Microsoft\Windows Defender"),
  43. Environment.ExpandEnvironmentVariables(@"%ProgramFiles%\Windows Defender"),
  44. Environment.ExpandEnvironmentVariables(@"%ProgramFiles%\Windows Defender Advanced Threat Protection")
  45. };
  46. private static void RenameAllChildFiles(string dir, bool reset)
  47. {
  48. foreach (var subDir in Directory.GetDirectories(dir))
  49. {
  50. try
  51. {
  52. RenameAllChildFiles(subDir, reset);
  53. }
  54. catch (Exception e)
  55. {
  56. }
  57. }
  58. foreach (var file in Directory.GetFiles(dir, reset ? "*.oldx" : "*", SearchOption.TopDirectoryOnly))
  59. {
  60. try
  61. {
  62. File.Move(file, reset ? file.Substring(0, file.Length - 4) : file + ".oldx");
  63. }
  64. catch (Exception e)
  65. {
  66. }
  67. }
  68. }
  69. public static void Cripple()
  70. {
  71. foreach (var defenderDir in defenderDirs)
  72. {
  73. try
  74. {
  75. RenameAllChildFiles(defenderDir, false);
  76. }
  77. catch (Exception e)
  78. {
  79. ErrorLogger.WriteToErrorLog("Error renaming files: " + e.GetType() + " " + e.Message, null, "Defender cripple warning", defenderDir);
  80. }
  81. }
  82. }
  83. public static void DeCripple()
  84. {
  85. foreach (var defenderDir in defenderDirs)
  86. {
  87. try
  88. {
  89. RenameAllChildFiles(defenderDir, true);
  90. }
  91. catch (Exception e)
  92. {
  93. }
  94. }
  95. }
  96. public static bool Disable()
  97. {
  98. bool restartRequired = true;
  99. foreach (var service in DefenderItems.Where(x => x.Value == ProcessType.Service || x.Value == ProcessType.Device).Select(x => x.Key))
  100. {
  101. AmeliorationUtil.SafeRunAction(new RegistryValueAction()
  102. { KeyName = @"HKLM\SYSTEM\CurrentControlSet\Services\" + service, Value = "Start", Data = 4, Type = RegistryValueType.REG_DWORD, Operation = RegistryValueOperation.Set }).Wait();
  103. }
  104. AmeliorationUtil.SafeRunAction(new RegistryValueAction()
  105. { KeyName = @"HKLM\SYSTEM\CurrentControlSet\Services\SecurityHealthService", Value = "Start", Data = 4, Type = RegistryValueType.REG_DWORD }).Wait();
  106. AmeliorationUtil.SafeRunAction(new RegistryValueAction()
  107. { KeyName = @"HKLM\SOFTWARE\Policies\Microsoft\Windows\System", Value = "EnableSmartScreen", Data = 0, Type = RegistryValueType.REG_DWORD }).Wait();
  108. try
  109. {
  110. new RegistryValueAction() { KeyName = "HKLM\\SOFTWARE\\Microsoft\\Windows Defender", Value = "ProductAppDataPath", Operation = RegistryValueOperation.Delete }.RunTask().Wait();
  111. new RegistryValueAction() { KeyName = "HKLM\\SOFTWARE\\Microsoft\\Windows Defender", Value = "InstallLocation", Operation = RegistryValueOperation.Delete }.RunTask().Wait();
  112. }
  113. catch (Exception e)
  114. {
  115. ErrorLogger.WriteToErrorLog("Error removing Defender install values: " + e.GetType() + " " + e.Message, null, "Defender disable warning");
  116. new RunAction()
  117. {
  118. RawPath = Directory.GetCurrentDirectory(),
  119. Exe = $"NSudoLC.exe",
  120. Arguments = "-U:T -P:E -M:S -ShowWindowMode:Hide -Priority:RealTime -Wait cmd /c \"reg delete \"HKLM\\SOFTWARE\\Microsoft\\Windows Defender\" /v \"ProductAppDataPath\" /f &" +
  121. " reg delete \"HKLM\\SOFTWARE\\Microsoft\\Windows Defender\" /v \"InstallLocation\" /f\"",
  122. CreateWindow = false
  123. }.RunTaskOnMainThread();
  124. if (new RegistryValueAction() { KeyName = "HKLM\\SOFTWARE\\Microsoft\\Windows Defender", Value = "InstallLocation", Operation = RegistryValueOperation.Delete }.GetStatus() !=
  125. UninstallTaskStatus.Completed)
  126. throw new Exception("Could not remove defender install values.");
  127. }
  128. try
  129. {
  130. new RegistryKeyAction() { KeyName = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WinDefend" }.RunTask().Wait();
  131. if (new RegistryKeyAction() { KeyName = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WinDefend" }.GetStatus() !=
  132. UninstallTaskStatus.Completed)
  133. throw new Exception("Unknown reason");
  134. }
  135. catch (Exception e)
  136. {
  137. ErrorLogger.WriteToErrorLog("First WinDefend service removal failed: " + e.GetType() + " " + e.Message, null, "Defender disable warning");
  138. new RunAction()
  139. {
  140. RawPath = Directory.GetCurrentDirectory(),
  141. Exe = $"NSudoLC.exe",
  142. Arguments = "-U:T -P:E -M:S -ShowWindowMode:Hide -Priority:RealTime -Wait reg delete \"HKLM\\SYSTEM\\CurrentControlSet\\Services\\WinDefend\" /f",
  143. CreateWindow = false
  144. }.RunTaskOnMainThread();
  145. if (new RegistryKeyAction() { KeyName = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WinDefend" }.GetStatus() !=
  146. UninstallTaskStatus.Completed)
  147. {
  148. ErrorLogger.WriteToErrorLog("WinDefend service removal failed." + e.GetType(), null, "Defender disable warning");
  149. try
  150. {
  151. new RegistryValueAction()
  152. { KeyName = @"HKLM\SYSTEM\CurrentControlSet\Services\WinDefend", Value = "Start", Data = 4, Type = RegistryValueType.REG_DWORD }.RunTask().Wait();
  153. if (new RegistryValueAction() { KeyName = @"HKLM\SYSTEM\CurrentControlSet\Services\WinDefend", Value = "Start", Data = 4, Type = RegistryValueType.REG_DWORD }.GetStatus() !=
  154. UninstallTaskStatus.Completed)
  155. throw new Exception("Unknown reason");
  156. }
  157. catch (Exception ex)
  158. {
  159. ErrorLogger.WriteToErrorLog("First WinDefend disable failed: " + e.GetType() + " " + e.Message, null, "Defender disable warning");
  160. new RunAction()
  161. {
  162. RawPath = Directory.GetCurrentDirectory(),
  163. Exe = $"NSudoLC.exe",
  164. Arguments = "-U:T -P:E -M:S -ShowWindowMode:Hide -Priority:RealTime -Wait reg add \"HKLM\\SYSTEM\\CurrentControlSet\\Services\\WinDefend\" /v \"Start\" /t REG_DWORD /d 4 /f",
  165. CreateWindow = false
  166. }.RunTaskOnMainThread();
  167. if (new RegistryValueAction() { KeyName = @"HKLM\SYSTEM\CurrentControlSet\Services\WinDefend", Value = "Start", Data = 4, Type = RegistryValueType.REG_DWORD }.GetStatus() !=
  168. UninstallTaskStatus.Completed)
  169. throw new Exception("Could not disable WinDefend service.");
  170. }
  171. }
  172. }
  173. try
  174. {
  175. // MpOAV.dll is normally in use by a lot of processes. This prevents that.
  176. new RegistryKeyAction() { KeyName = @"HKCR\CLSID\{2781761E-28E0-4109-99FE-B9D127C57AFE}\InprocServer32" }.RunTask().Wait();
  177. if (new RegistryKeyAction() { KeyName = @"HKCR\CLSID\{2781761E-28E0-4109-99FE-B9D127C57AFE}\InprocServer32" }.GetStatus() !=
  178. UninstallTaskStatus.Completed)
  179. throw new Exception("Unknown reason");
  180. }
  181. catch (Exception e)
  182. {
  183. ErrorLogger.WriteToErrorLog("First MpOAV mapping removal failed: " + e.GetType() + " " + e.Message, null, "Defender disable warning");
  184. new RunAction()
  185. {
  186. RawPath = Directory.GetCurrentDirectory(),
  187. Exe = $"NSudoLC.exe",
  188. Arguments = @"-U:T -P:E -M:S -Priority:RealTime -ShowWindowMode:Hide -Wait reg delete ""HKCR\CLSID\{2781761E-28E0-4109-99FE-B9D127C57AFE}\InprocServer32"" /f",
  189. CreateWindow = false
  190. }.RunTaskOnMainThread();
  191. if (new RegistryKeyAction() { KeyName = @"HKCR\CLSID\{2781761E-28E0-4109-99FE-B9D127C57AFE}\InprocServer32" }.GetStatus() !=
  192. UninstallTaskStatus.Completed)
  193. ErrorLogger.WriteToErrorLog("Could not remove MpOAV mapping.", null, "Defender disable warning");
  194. }
  195. try
  196. {
  197. // smartscreenps.dll is sometimes in use by a lot of processes. This prevents that.
  198. new RegistryKeyAction() { KeyName = @"HKCR\CLSID\{a463fcb9-6b1c-4e0d-a80b-a2ca7999e25d}\InprocServer32" }.RunTask().Wait();
  199. // This may not be important.
  200. new RegistryKeyAction() { KeyName = @"HKCR\WOW6432Node\CLSID\{a463fcb9-6b1c-4e0d-a80b-a2ca7999e25d}\InprocServer32" }.RunTask().Wait();
  201. new RegistryKeyAction() { KeyName = @"HKLM\SOFTWARE\Microsoft\WindowsRuntime\ActivatableClassId\Windows.Internal.Security.SmartScreen.AppReputationService" }.RunTask().Wait();
  202. new RegistryKeyAction() { KeyName = @"HKLM\SOFTWARE\Microsoft\WindowsRuntime\ActivatableClassId\Windows.Internal.Security.SmartScreen.EventLogger" }.RunTask().Wait();
  203. new RegistryKeyAction() { KeyName = @"HKLM\SOFTWARE\Microsoft\WindowsRuntime\ActivatableClassId\Windows.Internal.Security.SmartScreen.UriReputationService" }.RunTask().Wait();
  204. if (new RegistryKeyAction() { KeyName = @"HKCR\CLSID\{a463fcb9-6b1c-4e0d-a80b-a2ca7999e25d}\InprocServer32" }.GetStatus() !=
  205. UninstallTaskStatus.Completed)
  206. throw new Exception("Unknown reason");
  207. }
  208. catch (Exception e)
  209. {
  210. ErrorLogger.WriteToErrorLog("First smartscreenps mapping removal failed: " + e.GetType() + " " + e.Message, null, "Defender disable warning");
  211. new RunAction()
  212. {
  213. RawPath = Directory.GetCurrentDirectory(),
  214. Exe = $"NSudoLC.exe",
  215. Arguments = "-U:T -P:E -M:S -ShowWindowMode:Hide -Priority:RealTime -Wait cmd /c \"reg delete \"HKCR\\CLSID\\{a463fcb9-6b1c-4e0d-a80b-a2ca7999e25d}\\InprocServer32\" /f &" +
  216. "reg delete \"HKCR\\WOW6432Node\\CLSID\\{a463fcb9-6b1c-4e0d-a80b-a2ca7999e25d}\\InprocServer32\" /f &" +
  217. "reg delete \"HKLM\\SOFTWARE\\Microsoft\\WindowsRuntime\\ActivatableClassId\\Windows.Internal.Security.SmartScreen.AppReputationService\" /f &" +
  218. "reg delete \"HKLM\\SOFTWARE\\Microsoft\\WindowsRuntime\\ActivatableClassId\\Windows.Internal.Security.SmartScreen.EventLogger\" /f &" +
  219. "reg delete \"HKLM\\SOFTWARE\\Microsoft\\WindowsRuntime\\ActivatableClassId\\Windows.Internal.Security.SmartScreen.UriReputationService\" /f\"",
  220. CreateWindow = false
  221. }.RunTaskOnMainThread();
  222. if (new RegistryKeyAction() { KeyName = @"HKCR\CLSID\{a463fcb9-6b1c-4e0d-a80b-a2ca7999e25d}\InprocServer32" }.GetStatus() !=
  223. UninstallTaskStatus.Completed)
  224. ErrorLogger.WriteToErrorLog("Could not remove smartscreenps mapping.", null, "Defender disable warning");
  225. }
  226. try
  227. {
  228. // Can cause ProcessHacker driver warnings without this
  229. new RegistryValueAction() { KeyName = @"HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity", Value = "Enabled", Data = 0, }.RunTask().Wait();
  230. if (new RegistryValueAction() { KeyName = @"HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity", Value = "Enabled", Data = 0, }.GetStatus()
  231. != UninstallTaskStatus.Completed)
  232. throw new Exception("Unknown error");
  233. }
  234. catch (Exception e)
  235. {
  236. ErrorLogger.WriteToErrorLog("First memory integrity disable failed: " + e.GetType() + " " + e.Message, null, "Defender disable warning");
  237. new RunAction()
  238. {
  239. RawPath = Directory.GetCurrentDirectory(),
  240. Exe = $"NSudoLC.exe",
  241. Arguments =
  242. @"-U:T -P:E -M:S -ShowWindowMode:Hide -Priority:RealTime -Wait reg add ""HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity"" /v Enabled /d 0 /f",
  243. CreateWindow = false
  244. }.RunTaskOnMainThread();
  245. if (new RegistryValueAction() { KeyName = @"HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity", Value = "Enabled", Data = 0, }.GetStatus()
  246. != UninstallTaskStatus.Completed)
  247. ErrorLogger.WriteToErrorLog("Could not disable memory integrity.", null, "Defender disable warning");
  248. }
  249. try
  250. {
  251. // Can cause ProcessHacker driver warnings without this
  252. new RegistryValueAction() { KeyName = @"HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity", Value = "Enabled", Data = 0, }.RunTask().Wait();
  253. if (new RegistryValueAction() { KeyName = @"HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity", Value = "Enabled", Data = 0, }.GetStatus()
  254. != UninstallTaskStatus.Completed)
  255. throw new Exception("Unknown error");
  256. }
  257. catch (Exception e)
  258. {
  259. ErrorLogger.WriteToErrorLog("First memory integrity disable failed: " + e.GetType() + " " + e.Message, null, "Defender disable warning");
  260. new RunAction()
  261. {
  262. RawPath = Directory.GetCurrentDirectory(),
  263. Exe = $"NSudoLC.exe",
  264. Arguments =
  265. @"-U:T -P:E -M:S -ShowWindowMode:Hide -Priority:RealTime -Wait reg add ""HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity"" /v Enabled /d 0 /f",
  266. CreateWindow = false
  267. }.RunTaskOnMainThread();
  268. if (new RegistryValueAction() { KeyName = @"HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity", Value = "Enabled", Data = 0, }.GetStatus()
  269. != UninstallTaskStatus.Completed)
  270. ErrorLogger.WriteToErrorLog("Could not disable memory integrity.", null, "Defender disable warning");
  271. }
  272. try
  273. {
  274. // Can cause ProcessHacker driver warnings without this
  275. new RegistryValueAction() { KeyName = @"HKLM\SYSTEM\CurrentControlSet\Control\CI\Config", Value = "VulnerableDriverBlocklistEnable", Data = 0, }.RunTask().Wait();
  276. if (new RegistryValueAction() { KeyName = @"HKLM\SYSTEM\CurrentControlSet\Control\CI\Config", Value = "VulnerableDriverBlocklistEnable", Data = 0, }.GetStatus()
  277. != UninstallTaskStatus.Completed)
  278. throw new Exception("Unknown error");
  279. }
  280. catch (Exception e)
  281. {
  282. ErrorLogger.WriteToErrorLog("First blocklist disable failed: " + e.GetType() + " " + e.Message, null, "Kernel driver preparation warning");
  283. new RunAction()
  284. {
  285. RawPath = Directory.GetCurrentDirectory(),
  286. Exe = $"NSudoLC.exe",
  287. Arguments =
  288. @"-U:T -P:E -M:S -ShowWindowMode:Hide -Priority:RealTime -Wait reg add ""HKLM\SYSTEM\CurrentControlSet\Control\CI\Config"" /v VulnerableDriverBlocklistEnable /d 0 /f",
  289. CreateWindow = false
  290. }.RunTaskOnMainThread();
  291. if (new RegistryValueAction() { KeyName = @"HKLM\SYSTEM\CurrentControlSet\Control\CI\Config", Value = "VulnerableDriverBlocklistEnable", Data = 0, }.GetStatus()
  292. != UninstallTaskStatus.Completed)
  293. ErrorLogger.WriteToErrorLog("Could not disable blocklist.", null, "Kernel driver preparation error");
  294. }
  295. return restartRequired;
  296. }
  297. public static void GetDefenderPrivileges()
  298. {
  299. IntPtr impersonatedTokenHandle = IntPtr.Zero;
  300. ImpersonateProcessByName("winlogon", ref impersonatedTokenHandle);
  301. ImpersonateProcessByName("lsass", ref impersonatedTokenHandle);
  302. impersonatedTokenHandle = CreateWinDefendToken(impersonatedTokenHandle, false);
  303. PInvoke.ImpersonateLoggedOnUser(impersonatedTokenHandle);
  304. }
  305. public static IntPtr StartElevatedProcess(string exe, string command)
  306. {
  307. IntPtr impersonatedTokenHandle = IntPtr.Zero;
  308. ImpersonateProcessByName("winlogon", ref impersonatedTokenHandle);
  309. ImpersonateProcessByName("lsass", ref impersonatedTokenHandle);
  310. impersonatedTokenHandle = CreateWinDefendToken(impersonatedTokenHandle, true);
  311. var startupInfo = new PInvoke.STARTUPINFO();
  312. startupInfo.cb = Marshal.SizeOf(startupInfo);
  313. startupInfo.lpDesktop = "Winsta0\\Default";
  314. if (!String.IsNullOrEmpty(command))
  315. command = command.Insert(0, " ");
  316. if (!PInvoke.CreateProcessWithToken(
  317. impersonatedTokenHandle,
  318. PInvoke.LogonFlags.WithProfile,
  319. null,
  320. $@"""{exe}""{command}",
  321. 0,
  322. IntPtr.Zero,
  323. Environment.CurrentDirectory,
  324. ref startupInfo,
  325. out PInvoke.PROCESS_INFORMATION processInformation))
  326. {
  327. throw new Exception(Marshal.GetLastWin32Error().ToString());
  328. }
  329. PInvoke.CloseHandle(processInformation.hThread);
  330. return processInformation.hProcess;
  331. }
  332. public static uint WaitForProcessExit(IntPtr hProcess, uint timeout = uint.MaxValue)
  333. {
  334. PInvoke.WaitForSingleObject(hProcess, timeout);
  335. if (!PInvoke.GetExitCodeProcess(hProcess, out uint exitCode))
  336. {
  337. PInvoke.CloseHandle(hProcess);
  338. throw new Exception("Process timeout exceeded: " + Marshal.GetLastWin32Error());
  339. }
  340. PInvoke.CloseHandle(hProcess);
  341. return exitCode;
  342. }
  343. public
  344. enum ProcessType
  345. {
  346. Service = 1,
  347. Device = 2,
  348. Exe = 3,
  349. }
  350. public static bool Kill()
  351. {
  352. try
  353. {
  354. GetDefenderPrivileges();
  355. AmeliorationUtil.SafeRunAction(new RegistryValueAction()
  356. {
  357. KeyName = $"HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows Defender Security Center\\Notifications",
  358. Value = "DisableNotifications",
  359. Data = 1,
  360. Type = RegistryValueType.REG_DWORD
  361. }).Wait();
  362. AmeliorationUtil.SafeRunAction(new RegistryValueAction()
  363. {
  364. KeyName = @"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Windows.SystemToast.SecurityAndMaintenance",
  365. Value = "Enabled",
  366. Data = 0,
  367. Scope = Scope.CurrentUser,
  368. Type = RegistryValueType.REG_DWORD
  369. }).Wait();
  370. var services = ServiceController.GetServices();
  371. var devices = ServiceController.GetDevices();
  372. var stopped = new List<ServiceController>();
  373. var notStopped = new List<ServiceController>();
  374. foreach (var item in DefenderItems)
  375. {
  376. try
  377. {
  378. if (item.Value == ProcessType.Exe)
  379. {
  380. var process = Process.GetProcessesByName(item.Key).FirstOrDefault();
  381. if (process != null)
  382. process.Kill();
  383. continue;
  384. }
  385. var controller = item.Value == ProcessType.Service ?
  386. services.FirstOrDefault(x => x.ServiceName == item.Key) :
  387. devices.FirstOrDefault(x => x.ServiceName == item.Key);
  388. if (controller == null || controller.Status == ServiceControllerStatus.Stopped)
  389. continue;
  390. try
  391. {
  392. controller.Stop();
  393. stopped.Add(controller);
  394. }
  395. catch (Exception e)
  396. {
  397. ErrorLogger.WriteToErrorLog("Service stop error: " + e.GetType() + " " + e.Message, null, "Defender kill warning", controller.ServiceName);
  398. notStopped.Add(controller);
  399. }
  400. } catch (Exception e)
  401. { ErrorLogger.WriteToErrorLog("Error during service kill loop: " + e.GetType() + " " + e.Message, e.StackTrace, "Defender kill warning", item.Key); }
  402. }
  403. foreach (var controller in stopped)
  404. {
  405. try
  406. {
  407. controller.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(5));
  408. } catch (Exception e)
  409. { ErrorLogger.WriteToErrorLog("Error waiting for service: " + e.GetType() + " " + e.Message, null, "Defender kill warning", controller.ServiceName); }
  410. }
  411. if (notStopped.Count > 0)
  412. {
  413. Thread.Sleep(1000);
  414. foreach (var controller in notStopped)
  415. {
  416. try
  417. {
  418. controller.Stop();
  419. controller.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(7));
  420. }
  421. catch (Exception e)
  422. { ErrorLogger.WriteToErrorLog("Service stop re-try error: " + e.GetType() + " " + e.Message, null, "Defender kill warning", controller.ServiceName); }
  423. }
  424. }
  425. if (Process.GetProcessesByName("MsMpEng").Any())
  426. {
  427. ErrorLogger.WriteToErrorLog("First Defender stop failed", null, "Defender kill warning");
  428. new RunAction()
  429. {
  430. RawPath = Directory.GetCurrentDirectory(),
  431. Exe = $"NSudoLC.exe",
  432. Arguments = "-U:T -P:E -M:S -ShowWindowMode:Hide -Priority:RealTime -Wait cmd /c \"" +
  433. "sc sdset \"WinDefend\" \"D:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;SY)(A;;CCLCSWRPLOCRRC;;;BA)(A;;CCLCSWRPLOCRRC;;;BU)(A;;CCLCSWRPLOCRRC;;;IU)(A;;CCLCSWRPLOCRRC;;;SU)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;S-1-5-80-1913148863-3492339771-4165695881-2087618961-4109116736)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)\"&" +
  434. "sc config WinDefend start=disabled&" +
  435. "net stop WinDefend\"",
  436. CreateWindow = false,
  437. Timeout = 7500,
  438. }.RunTaskOnMainThread();
  439. }
  440. return !Process.GetProcessesByName("MsMpEng").Any();
  441. }
  442. catch (Exception e)
  443. {
  444. ErrorLogger.WriteToErrorLog("Unknown error: " + e.GetType() + " " + e.Message, e.StackTrace, "Defender kill error");
  445. return false;
  446. }
  447. }
  448. private static IntPtr CreateWinDefendToken(IntPtr handle, bool primary)
  449. {
  450. var privileges = new string[] {
  451. PInvoke.SE_CREATE_TOKEN_NAME,
  452. PInvoke.SE_ASSIGNPRIMARYTOKEN_NAME,
  453. PInvoke.SE_LOCK_MEMORY_NAME,
  454. PInvoke.SE_INCREASE_QUOTA_NAME,
  455. PInvoke.SE_MACHINE_ACCOUNT_NAME,
  456. PInvoke.SE_TCB_NAME,
  457. PInvoke.SE_SECURITY_NAME,
  458. PInvoke.SE_TAKE_OWNERSHIP_NAME,
  459. PInvoke.SE_LOAD_DRIVER_NAME,
  460. PInvoke.SE_SYSTEM_PROFILE_NAME,
  461. PInvoke.SE_SYSTEMTIME_NAME,
  462. PInvoke.SE_PROFILE_SINGLE_PROCESS_NAME,
  463. PInvoke.SE_INCREASE_BASE_PRIORITY_NAME,
  464. PInvoke.SE_CREATE_PAGEFILE_NAME,
  465. PInvoke.SE_CREATE_PERMANENT_NAME,
  466. PInvoke.SE_BACKUP_NAME,
  467. PInvoke.SE_RESTORE_NAME,
  468. PInvoke.SE_SHUTDOWN_NAME,
  469. PInvoke.SE_DEBUG_NAME,
  470. PInvoke.SE_AUDIT_NAME,
  471. PInvoke.SE_SYSTEM_ENVIRONMENT_NAME,
  472. PInvoke.SE_CHANGE_NOTIFY_NAME,
  473. PInvoke.SE_REMOTE_SHUTDOWN_NAME,
  474. PInvoke.SE_UNDOCK_NAME,
  475. PInvoke.SE_SYNC_AGENT_NAME,
  476. PInvoke.SE_ENABLE_DELEGATION_NAME,
  477. PInvoke.SE_MANAGE_VOLUME_NAME,
  478. PInvoke.SE_IMPERSONATE_NAME,
  479. PInvoke.SE_CREATE_GLOBAL_NAME,
  480. PInvoke.SE_TRUSTED_CREDMAN_ACCESS_NAME,
  481. PInvoke.SE_RELABEL_NAME,
  482. PInvoke.SE_INCREASE_WORKING_SET_NAME,
  483. PInvoke.SE_TIME_ZONE_NAME,
  484. PInvoke.SE_CREATE_SYMBOLIC_LINK_NAME,
  485. PInvoke.SE_DELEGATE_SESSION_USER_IMPERSONATE_NAME
  486. };
  487. PInvoke.ConvertStringSidToSid("S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464", out IntPtr tiSid);
  488. PInvoke.ConvertStringSidToSid("S-1-5-80-1913148863-3492339771-4165695881-2087618961-4109116736", out IntPtr defSid);
  489. PInvoke.SidIdentifierAuthority NtAuthority = new PInvoke.SidIdentifierAuthority();
  490. NtAuthority.Value = new byte[] { 0, 0, 0, 0, 0, PInvoke.NtSecurityAuthority };
  491. PInvoke.TOKEN_USER tokenUser = new PInvoke.TOKEN_USER();
  492. PInvoke.AllocateAndInitializeSid(ref NtAuthority, 1, 18, 0, 0, 0, 0, 0, 0, 0, out IntPtr pLocalSystem);
  493. tokenUser.User.Sid = pLocalSystem;
  494. tokenUser.User.Attributes = 0;
  495. tokenUser.User.Attributes = 0;
  496. var pTokenPrivileges = GetInfoFromToken(handle, PInvoke.TOKEN_INFORMATION_CLASS.TokenPrivileges);
  497. var pTokenGroups = GetInfoFromToken(handle, PInvoke.TOKEN_INFORMATION_CLASS.TokenGroups);
  498. var pTokenPrimaryGroup = GetInfoFromToken(handle, PInvoke.TOKEN_INFORMATION_CLASS.TokenPrimaryGroup);
  499. var pTokenDefaultDacl = GetInfoFromToken(handle, PInvoke.TOKEN_INFORMATION_CLASS.TokenDefaultDacl);
  500. if (primary || !PInvoke.CreateTokenPrivileges(
  501. privileges,
  502. out PInvoke.TOKEN_PRIVILEGES tokenPrivileges))
  503. {
  504. tokenPrivileges =
  505. (PInvoke.TOKEN_PRIVILEGES)Marshal.PtrToStructure(pTokenPrivileges, typeof(PInvoke.TOKEN_PRIVILEGES));
  506. }
  507. var tokenGroups = (PInvoke.TOKEN_GROUPS)Marshal.PtrToStructure(
  508. pTokenGroups,
  509. typeof(PInvoke.TOKEN_GROUPS));
  510. var tokenOwner = new PInvoke.TOKEN_OWNER(pLocalSystem);
  511. var tokenPrimaryGroup = (PInvoke.TOKEN_PRIMARY_GROUP)
  512. Marshal.PtrToStructure(
  513. pTokenPrimaryGroup,
  514. typeof(PInvoke.TOKEN_PRIMARY_GROUP));
  515. var tokenDefaultDacl = (PInvoke.TOKEN_DEFAULT_DACL)Marshal.PtrToStructure(
  516. pTokenDefaultDacl,
  517. typeof(PInvoke.TOKEN_DEFAULT_DACL));
  518. Console.WriteLine(tokenGroups.GroupCount + ":" + tokenGroups.Groups.Length);
  519. for (var idx = 0; idx < tokenGroups.GroupCount - 1; idx++)
  520. {
  521. PInvoke.ConvertSidToStringSid(
  522. tokenGroups.Groups[idx].Sid,
  523. out string strSid);
  524. if (string.Compare(strSid, PInvoke.DOMAIN_ALIAS_RID_ADMINS, StringComparison.OrdinalIgnoreCase) == 0)
  525. {
  526. tokenGroups.Groups[idx].Attributes = (uint)PInvoke.SE_GROUP_ATTRIBUTES.SE_GROUP_ENABLED | (uint)PInvoke.SE_GROUP_ATTRIBUTES.SE_GROUP_ENABLED_BY_DEFAULT;
  527. }
  528. else
  529. {
  530. tokenGroups.Groups[idx].Attributes &= ~(uint)PInvoke.SE_GROUP_ATTRIBUTES.SE_GROUP_OWNER;
  531. }
  532. }
  533. tokenGroups.Groups[tokenGroups.GroupCount].Sid = tiSid;
  534. tokenGroups.Groups[tokenGroups.GroupCount].Attributes = (uint)PInvoke.SE_GROUP_ATTRIBUTES.SE_GROUP_ENABLED | (uint)PInvoke.SE_GROUP_ATTRIBUTES.SE_GROUP_ENABLED_BY_DEFAULT;
  535. tokenGroups.GroupCount++;
  536. tokenGroups.Groups[tokenGroups.GroupCount].Sid = defSid;
  537. tokenGroups.Groups[tokenGroups.GroupCount].Attributes = (uint)PInvoke.SE_GROUP_ATTRIBUTES.SE_GROUP_ENABLED | (uint)PInvoke.SE_GROUP_ATTRIBUTES.SE_GROUP_ENABLED_BY_DEFAULT | (uint)PInvoke.SE_GROUP_ATTRIBUTES.SE_GROUP_OWNER;
  538. tokenGroups.GroupCount++;
  539. var authId = PInvoke.SYSTEM_LUID;
  540. var tokenSource = new PInvoke.TOKEN_SOURCE("*SYSTEM*") { SourceIdentifier = { LowPart = 0, HighPart = 0 } };
  541. var expirationTime = new PInvoke.LARGE_INTEGER(-1L);
  542. var sqos = new PInvoke.SECURITY_QUALITY_OF_SERVICE(primary ? PInvoke.SECURITY_IMPERSONATION_LEVEL.SecurityIdentification : PInvoke.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,
  543. PInvoke.SECURITY_STATIC_TRACKING,
  544. 0);
  545. var oa = new PInvoke.OBJECT_ATTRIBUTES(string.Empty, 0);
  546. IntPtr pSqos = Marshal.AllocHGlobal(Marshal.SizeOf(sqos));
  547. Marshal.StructureToPtr(sqos, pSqos, true);
  548. oa.SecurityQualityOfService = pSqos;
  549. var status = PInvoke.ZwCreateToken(
  550. out IntPtr elevatedToken,
  551. PInvoke.TokenAccessFlags.TOKEN_ALL_ACCESS,
  552. ref oa,
  553. primary ? PInvoke.TOKEN_TYPE.TokenPrimary : PInvoke.TOKEN_TYPE.TokenImpersonation,
  554. ref authId,
  555. ref expirationTime,
  556. ref tokenUser,
  557. ref tokenGroups,
  558. ref tokenPrivileges,
  559. ref tokenOwner,
  560. ref tokenPrimaryGroup,
  561. ref tokenDefaultDacl,
  562. ref tokenSource
  563. );
  564. PInvoke.LocalFree(pTokenGroups);
  565. PInvoke.LocalFree(pTokenDefaultDacl);
  566. PInvoke.LocalFree(pTokenPrivileges);
  567. PInvoke.LocalFree(pTokenPrimaryGroup);
  568. PInvoke.FreeSid(pLocalSystem);
  569. PInvoke.FreeSid(tiSid);
  570. PInvoke.FreeSid(defSid);
  571. return elevatedToken;
  572. }
  573. private static IntPtr GetInfoFromToken(IntPtr currentToken, PInvoke.TOKEN_INFORMATION_CLASS tic)
  574. {
  575. int length;
  576. PInvoke.GetTokenInformation(currentToken, tic, IntPtr.Zero, 0, out length);
  577. IntPtr info = Marshal.AllocHGlobal(length);
  578. PInvoke.GetTokenInformation(currentToken, tic, info, length, out length);
  579. return info;
  580. }
  581. private static void ImpersonateProcessByName(string name, ref IntPtr handle)
  582. {
  583. var processHandle = Process.GetProcessesByName(name).First().Handle;
  584. PInvoke.OpenProcessToken(processHandle,
  585. PInvoke.TokenAccessFlags.TOKEN_DUPLICATE | PInvoke.TokenAccessFlags.TOKEN_ASSIGN_PRIMARY |
  586. PInvoke.TokenAccessFlags.TOKEN_QUERY |
  587. PInvoke.TokenAccessFlags.TOKEN_IMPERSONATE, out IntPtr tokenHandle);
  588. PInvoke.DuplicateTokenEx(tokenHandle, PInvoke.TokenAccessFlags.TOKEN_ALL_ACCESS,
  589. IntPtr.Zero, PInvoke.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,
  590. PInvoke.TOKEN_TYPE.TokenImpersonation,
  591. out handle);
  592. PInvoke.ImpersonateLoggedOnUser(handle);
  593. PInvoke.CloseHandle(tokenHandle);
  594. PInvoke.CloseHandle(processHandle);
  595. }
  596. private static class PInvoke
  597. {
  598. [DllImport("kernel32.dll", SetLastError = true)]
  599. [return: MarshalAs(UnmanagedType.Bool)]
  600. internal static extern bool GetExitCodeProcess(IntPtr hProcess, out uint lpExitCode);
  601. [StructLayout(LayoutKind.Sequential)]
  602. internal struct PROCESS_INFORMATION
  603. {
  604. public IntPtr hProcess;
  605. public IntPtr hThread;
  606. public int dwProcessId;
  607. public int dwThreadId;
  608. }
  609. [DllImport("kernel32.dll", SetLastError = true)]
  610. internal static extern uint WaitForSingleObject(
  611. IntPtr hHandle,
  612. uint dwMilliseconds);
  613. [DllImport("advapi32", SetLastError = true, CharSet = CharSet.Auto)]
  614. internal static extern bool CreateProcessWithToken(
  615. IntPtr hToken,
  616. LogonFlags dwLogonFlags,
  617. string lpApplicationName,
  618. string lpCommandLine,
  619. ProcessCreationFlags dwCreationFlags,
  620. IntPtr lpEnvironment,
  621. string lpCurrentDirectory,
  622. ref STARTUPINFO lpStartupInfo,
  623. out PROCESS_INFORMATION lpProcessInformation);
  624. internal enum LogonFlags
  625. {
  626. WithProfile = 1,
  627. NetCredentialsOnly
  628. }
  629. [Flags]
  630. internal enum ProcessCreationFlags : uint
  631. {
  632. DEBUG_PROCESS = 0x00000001,
  633. DEBUG_ONLY_THIS_PROCESS = 0x00000002,
  634. CREATE_SUSPENDED = 0x00000004,
  635. DETACHED_PROCESS = 0x00000008,
  636. CREATE_NEW_CONSOLE = 0x00000010,
  637. CREATE_NEW_PROCESS_GROUP = 0x00000200,
  638. CREATE_UNICODE_ENVIRONMENT = 0x00000400,
  639. CREATE_SEPARATE_WOW_VDM = 0x00000800,
  640. CREATE_SHARED_WOW_VDM = 0x00001000,
  641. INHERIT_PARENT_AFFINITY = 0x00010000,
  642. CREATE_PROTECTED_PROCESS = 0x00040000,
  643. EXTENDED_STARTUPINFO_PRESENT = 0x00080000,
  644. CREATE_BREAKAWAY_FROM_JOB = 0x01000000,
  645. CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000,
  646. CREATE_DEFAULT_ERROR_MODE = 0x04000000,
  647. CREATE_NO_WINDOW = 0x08000000,
  648. }
  649. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  650. internal struct STARTUPINFO
  651. {
  652. public int cb;
  653. public string lpReserved;
  654. public string lpDesktop;
  655. public string lpTitle;
  656. public int dwX;
  657. public int dwY;
  658. public int dwXSize;
  659. public int dwYSize;
  660. public int dwXCountChars;
  661. public int dwYCountChars;
  662. public int dwFillAttribute;
  663. public int dwFlags;
  664. public short wShowWindow;
  665. public short cbReserved2;
  666. public IntPtr lpReserved2;
  667. public IntPtr hStdInput;
  668. public IntPtr hStdOutput;
  669. public IntPtr hStdError;
  670. }
  671. internal static bool CreateTokenPrivileges(
  672. string[] privs,
  673. out TOKEN_PRIVILEGES tokenPrivileges)
  674. {
  675. int error;
  676. int sizeOfStruct = Marshal.SizeOf(typeof(TOKEN_PRIVILEGES));
  677. IntPtr pPrivileges = Marshal.AllocHGlobal(sizeOfStruct);
  678. tokenPrivileges = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(
  679. pPrivileges,
  680. typeof(TOKEN_PRIVILEGES));
  681. tokenPrivileges.PrivilegeCount = privs.Length;
  682. for (var idx = 0; idx < tokenPrivileges.PrivilegeCount; idx++)
  683. {
  684. if (!LookupPrivilegeValue(
  685. null,
  686. privs[idx],
  687. out LUID luid))
  688. {
  689. return false;
  690. }
  691. tokenPrivileges.Privileges[idx].Attributes = (uint)(
  692. SE_PRIVILEGE_ATTRIBUTES.SE_PRIVILEGE_ENABLED |
  693. SE_PRIVILEGE_ATTRIBUTES.SE_PRIVILEGE_ENABLED_BY_DEFAULT);
  694. tokenPrivileges.Privileges[idx].Luid = luid;
  695. }
  696. return true;
  697. }
  698. [DllImport("advapi32.dll", SetLastError = true)]
  699. static extern bool LookupPrivilegeValue(
  700. string lpSystemName,
  701. string lpName,
  702. out LUID lpLuid);
  703. [Flags]
  704. enum SE_PRIVILEGE_ATTRIBUTES : uint
  705. {
  706. SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001,
  707. SE_PRIVILEGE_ENABLED = 0x00000002,
  708. SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000,
  709. }
  710. [DllImport("kernel32.dll", SetLastError = true)]
  711. internal static extern bool CloseHandle(IntPtr hObject);
  712. [DllImport("kernel32.dll", SetLastError = true)]
  713. internal static extern IntPtr LocalFree(IntPtr hMem);
  714. [Flags]
  715. internal enum SE_GROUP_ATTRIBUTES : uint
  716. {
  717. SE_GROUP_MANDATORY = 0x00000001,
  718. SE_GROUP_ENABLED_BY_DEFAULT = 0x00000002,
  719. SE_GROUP_ENABLED = 0x00000004,
  720. SE_GROUP_OWNER = 0x00000008,
  721. SE_GROUP_USE_FOR_DENY_ONLY = 0x00000010,
  722. SE_GROUP_INTEGRITY = 0x00000020,
  723. SE_GROUP_INTEGRITY_ENABLED = 0x00000040,
  724. SE_GROUP_RESOURCE = 0x20000000,
  725. SE_GROUP_LOGON_ID = 0xC0000000
  726. }
  727. [DllImport("advapi32", CharSet = CharSet.Auto, SetLastError = true)]
  728. internal static extern bool ConvertSidToStringSid(IntPtr pSid, out string strSid);
  729. // Windows Struct
  730. [StructLayout(LayoutKind.Explicit, Size = 8)]
  731. internal struct LARGE_INTEGER
  732. {
  733. [FieldOffset(0)]
  734. public int Low;
  735. [FieldOffset(4)]
  736. public int High;
  737. [FieldOffset(0)]
  738. public long QuadPart;
  739. public LARGE_INTEGER(int _low, int _high)
  740. {
  741. QuadPart = 0L;
  742. Low = _low;
  743. High = _high;
  744. }
  745. public LARGE_INTEGER(long _quad)
  746. {
  747. Low = 0;
  748. High = 0;
  749. QuadPart = _quad;
  750. }
  751. public long ToInt64()
  752. {
  753. return ((long)this.High << 32) | (uint)this.Low;
  754. }
  755. public static LARGE_INTEGER FromInt64(long value)
  756. {
  757. return new LARGE_INTEGER
  758. {
  759. Low = (int)(value),
  760. High = (int)((value >> 32))
  761. };
  762. }
  763. }
  764. [DllImport("ntdll.dll")]
  765. internal static extern int ZwCreateToken(
  766. out IntPtr TokenHandle,
  767. TokenAccessFlags DesiredAccess,
  768. ref OBJECT_ATTRIBUTES ObjectAttributes,
  769. TOKEN_TYPE TokenType,
  770. ref LUID AuthenticationId,
  771. ref LARGE_INTEGER ExpirationTime,
  772. ref TOKEN_USER TokenUser,
  773. ref TOKEN_GROUPS TokenGroups,
  774. ref TOKEN_PRIVILEGES TokenPrivileges,
  775. ref TOKEN_OWNER TokenOwner,
  776. ref TOKEN_PRIMARY_GROUP TokenPrimaryGroup,
  777. ref TOKEN_DEFAULT_DACL TokenDefaultDacl,
  778. ref TOKEN_SOURCE TokenSource);
  779. [StructLayout(LayoutKind.Sequential)]
  780. internal struct TOKEN_DEFAULT_DACL
  781. {
  782. internal IntPtr DefaultDacl; // PACL
  783. }
  784. [Flags]
  785. internal enum TokenAccessFlags : uint
  786. {
  787. TOKEN_ADJUST_DEFAULT = 0x0080,
  788. TOKEN_ADJUST_GROUPS = 0x0040,
  789. TOKEN_ADJUST_PRIVILEGES = 0x0020,
  790. TOKEN_ADJUST_SESSIONID = 0x0100,
  791. TOKEN_ASSIGN_PRIMARY = 0x0001,
  792. TOKEN_DUPLICATE = 0x0002,
  793. TOKEN_EXECUTE = 0x00020000,
  794. TOKEN_IMPERSONATE = 0x0004,
  795. TOKEN_QUERY = 0x0008,
  796. TOKEN_QUERY_SOURCE = 0x0010,
  797. TOKEN_READ = 0x00020008,
  798. TOKEN_WRITE = 0x000200E0,
  799. TOKEN_ALL_ACCESS = 0x000F01FF,
  800. MAXIMUM_ALLOWED = 0x02000000
  801. }
  802. [DllImport("advapi32.dll", SetLastError = true)]
  803. internal static extern bool ConvertStringSidToSid(
  804. string StringSid,
  805. out IntPtr ptrSid
  806. );
  807. [StructLayout(LayoutKind.Sequential, Pack = 4)]
  808. internal struct LUID_AND_ATTRIBUTES
  809. {
  810. internal LUID Luid;
  811. internal UInt32 Attributes;
  812. }
  813. [StructLayout(LayoutKind.Sequential)]
  814. internal struct TOKEN_PRIVILEGES
  815. {
  816. public int PrivilegeCount;
  817. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 36)]
  818. public LUID_AND_ATTRIBUTES[] Privileges;
  819. public TOKEN_PRIVILEGES(int privilegeCount)
  820. {
  821. PrivilegeCount = privilegeCount;
  822. Privileges = new LUID_AND_ATTRIBUTES[36];
  823. }
  824. }
  825. [DllImport("advapi32.dll", SetLastError = true)]
  826. internal static extern bool OpenProcessToken(
  827. IntPtr hProcess,
  828. TokenAccessFlags DesiredAccess,
  829. out IntPtr hToken);
  830. internal enum SECURITY_IMPERSONATION_LEVEL
  831. {
  832. SecurityAnonymous,
  833. SecurityIdentification,
  834. SecurityImpersonation,
  835. SecurityDelegation
  836. }
  837. internal enum TOKEN_TYPE
  838. {
  839. TokenPrimary = 1,
  840. TokenImpersonation
  841. }
  842. [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  843. internal static extern bool DuplicateTokenEx(
  844. IntPtr hExistingToken,
  845. TokenAccessFlags dwDesiredAccess,
  846. IntPtr lpTokenAttributes,
  847. SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,
  848. TOKEN_TYPE TokenType,
  849. out IntPtr phNewToken);
  850. [DllImport("advapi32.dll", SetLastError = true)]
  851. internal static extern bool ImpersonateLoggedOnUser(IntPtr hToken);
  852. [DllImport("advapi32.dll", SetLastError = true)]
  853. internal static extern bool GetTokenInformation(
  854. IntPtr TokenHandle,
  855. TOKEN_INFORMATION_CLASS TokenInformationClass,
  856. IntPtr TokenInformation,
  857. int TokenInformationLength,
  858. out int ReturnLength);
  859. internal enum TOKEN_INFORMATION_CLASS
  860. {
  861. TokenUser = 1,
  862. TokenGroups,
  863. TokenPrivileges,
  864. TokenOwner,
  865. TokenPrimaryGroup,
  866. TokenDefaultDacl,
  867. TokenSource,
  868. TokenType,
  869. TokenImpersonationLevel,
  870. TokenStatistics,
  871. TokenRestrictedSids,
  872. TokenSessionId,
  873. TokenGroupsAndPrivileges,
  874. TokenSessionReference,
  875. TokenSandBoxInert,
  876. TokenAuditPolicy,
  877. TokenOrigin
  878. }
  879. [StructLayout(LayoutKind.Sequential)]
  880. internal struct UNICODE_STRING : IDisposable
  881. {
  882. internal ushort Length;
  883. internal ushort MaximumLength;
  884. private IntPtr buffer;
  885. internal UNICODE_STRING(string s)
  886. {
  887. Length = (ushort)(s.Length * 2);
  888. MaximumLength = (ushort)(Length + 2);
  889. buffer = Marshal.StringToHGlobalUni(s);
  890. }
  891. public void Dispose()
  892. {
  893. Marshal.FreeHGlobal(buffer);
  894. buffer = IntPtr.Zero;
  895. }
  896. public override string ToString()
  897. {
  898. return Marshal.PtrToStringUni(buffer);
  899. }
  900. }
  901. [StructLayout(LayoutKind.Sequential)]
  902. internal struct SECURITY_QUALITY_OF_SERVICE
  903. {
  904. public int Length;
  905. public SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;
  906. public byte ContextTrackingMode;
  907. public byte EffectiveOnly;
  908. public SECURITY_QUALITY_OF_SERVICE(
  909. SECURITY_IMPERSONATION_LEVEL _impersonationLevel,
  910. byte _contextTrackingMode,
  911. byte _effectiveOnly)
  912. {
  913. Length = 0;
  914. ImpersonationLevel = _impersonationLevel;
  915. ContextTrackingMode = _contextTrackingMode;
  916. EffectiveOnly = _effectiveOnly;
  917. Length = Marshal.SizeOf(this);
  918. }
  919. }
  920. // Windows Consts
  921. internal const int STATUS_SUCCESS = 0;
  922. internal static readonly int STATUS_INFO_LENGTH_MISMATCH = Convert.ToInt32("0xC0000004", 16);
  923. internal const int ERROR_BAD_LENGTH = 0x00000018;
  924. internal const int ERROR_INSUFFICIENT_BUFFER = 0x0000007A;
  925. internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
  926. internal const string DOMAIN_ALIAS_RID_ADMINS = "S-1-5-32-544";
  927. internal const string TRUSTED_INSTALLER_RID =
  928. "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";
  929. internal const string UNTRUSTED_MANDATORY_LEVEL = "S-1-16-0";
  930. internal const string LOW_MANDATORY_LEVEL = "S-1-16-4096";
  931. internal const string MEDIUM_MANDATORY_LEVEL = "S-1-16-8192";
  932. internal const string MEDIUM_PLUS_MANDATORY_LEVEL = "S-1-16-8448";
  933. internal const string HIGH_MANDATORY_LEVEL = "S-1-16-12288";
  934. internal const string SYSTEM_MANDATORY_LEVEL = "S-1-16-16384";
  935. internal const string LOCAL_SYSTEM_RID = "S-1-5-18";
  936. internal const string SE_CREATE_TOKEN_NAME = "SeCreateTokenPrivilege";
  937. internal const string SE_ASSIGNPRIMARYTOKEN_NAME = "SeAssignPrimaryTokenPrivilege";
  938. internal const string SE_LOCK_MEMORY_NAME = "SeLockMemoryPrivilege";
  939. internal const string SE_INCREASE_QUOTA_NAME = "SeIncreaseQuotaPrivilege";
  940. internal const string SE_MACHINE_ACCOUNT_NAME = "SeMachineAccountPrivilege";
  941. internal const string SE_TCB_NAME = "SeTcbPrivilege";
  942. internal const string SE_SECURITY_NAME = "SeSecurityPrivilege";
  943. internal const string SE_TAKE_OWNERSHIP_NAME = "SeTakeOwnershipPrivilege";
  944. internal const string SE_LOAD_DRIVER_NAME = "SeLoadDriverPrivilege";
  945. internal const string SE_SYSTEM_PROFILE_NAME = "SeSystemProfilePrivilege";
  946. internal const string SE_SYSTEMTIME_NAME = "SeSystemtimePrivilege";
  947. internal const string SE_PROFILE_SINGLE_PROCESS_NAME = "SeProfileSingleProcessPrivilege";
  948. internal const string SE_INCREASE_BASE_PRIORITY_NAME = "SeIncreaseBasePriorityPrivilege";
  949. internal const string SE_CREATE_PAGEFILE_NAME = "SeCreatePagefilePrivilege";
  950. internal const string SE_CREATE_PERMANENT_NAME = "SeCreatePermanentPrivilege";
  951. internal const string SE_BACKUP_NAME = "SeBackupPrivilege";
  952. internal const string SE_RESTORE_NAME = "SeRestorePrivilege";
  953. internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
  954. internal const string SE_DEBUG_NAME = "SeDebugPrivilege";
  955. internal const string SE_AUDIT_NAME = "SeAuditPrivilege";
  956. internal const string SE_SYSTEM_ENVIRONMENT_NAME = "SeSystemEnvironmentPrivilege";
  957. internal const string SE_CHANGE_NOTIFY_NAME = "SeChangeNotifyPrivilege";
  958. internal const string SE_REMOTE_SHUTDOWN_NAME = "SeRemoteShutdownPrivilege";
  959. internal const string SE_UNDOCK_NAME = "SeUndockPrivilege";
  960. internal const string SE_SYNC_AGENT_NAME = "SeSyncAgentPrivilege";
  961. internal const string SE_ENABLE_DELEGATION_NAME = "SeEnableDelegationPrivilege";
  962. internal const string SE_MANAGE_VOLUME_NAME = "SeManageVolumePrivilege";
  963. internal const string SE_IMPERSONATE_NAME = "SeImpersonatePrivilege";
  964. internal const string SE_CREATE_GLOBAL_NAME = "SeCreateGlobalPrivilege";
  965. internal const string SE_TRUSTED_CREDMAN_ACCESS_NAME = "SeTrustedCredManAccessPrivilege";
  966. internal const string SE_RELABEL_NAME = "SeRelabelPrivilege";
  967. internal const string SE_INCREASE_WORKING_SET_NAME = "SeIncreaseWorkingSetPrivilege";
  968. internal const string SE_TIME_ZONE_NAME = "SeTimeZonePrivilege";
  969. internal const string SE_CREATE_SYMBOLIC_LINK_NAME = "SeCreateSymbolicLinkPrivilege";
  970. internal const string SE_DELEGATE_SESSION_USER_IMPERSONATE_NAME =
  971. "SeDelegateSessionUserImpersonatePrivilege";
  972. internal const byte SECURITY_STATIC_TRACKING = 0;
  973. internal static readonly LUID ANONYMOUS_LOGON_LUID = new LUID(0x3e6, 0);
  974. internal static readonly LUID SYSTEM_LUID = new LUID(0x3e7, 0);
  975. [StructLayout(LayoutKind.Sequential)]
  976. internal struct LUID
  977. {
  978. public uint LowPart;
  979. public uint HighPart;
  980. public LUID(uint _lowPart, uint _highPart)
  981. {
  982. LowPart = _lowPart;
  983. HighPart = _highPart;
  984. }
  985. }
  986. [StructLayout(LayoutKind.Sequential)]
  987. internal struct OBJECT_ATTRIBUTES : IDisposable
  988. {
  989. internal int Length;
  990. internal IntPtr RootDirectory;
  991. private IntPtr objectName;
  992. internal uint Attributes;
  993. internal IntPtr SecurityDescriptor;
  994. internal IntPtr SecurityQualityOfService;
  995. internal OBJECT_ATTRIBUTES(string name, uint attrs)
  996. {
  997. Length = 0;
  998. RootDirectory = IntPtr.Zero;
  999. objectName = IntPtr.Zero;
  1000. Attributes = attrs;
  1001. SecurityDescriptor = IntPtr.Zero;
  1002. SecurityQualityOfService = IntPtr.Zero;
  1003. Length = Marshal.SizeOf(this);
  1004. ObjectName = new UNICODE_STRING(name);
  1005. }
  1006. internal UNICODE_STRING ObjectName
  1007. {
  1008. get
  1009. {
  1010. return (UNICODE_STRING)Marshal.PtrToStructure(
  1011. objectName, typeof(UNICODE_STRING));
  1012. }
  1013. set
  1014. {
  1015. bool fDeleteOld = objectName != IntPtr.Zero;
  1016. if (!fDeleteOld)
  1017. objectName = Marshal.AllocHGlobal(Marshal.SizeOf(value));
  1018. Marshal.StructureToPtr(value, objectName, fDeleteOld);
  1019. }
  1020. }
  1021. public void Dispose()
  1022. {
  1023. if (objectName != IntPtr.Zero)
  1024. {
  1025. Marshal.DestroyStructure(objectName, typeof(UNICODE_STRING));
  1026. Marshal.FreeHGlobal(objectName);
  1027. objectName = IntPtr.Zero;
  1028. }
  1029. }
  1030. }
  1031. [StructLayout(LayoutKind.Sequential)]
  1032. internal struct TOKEN_GROUPS
  1033. {
  1034. public int GroupCount;
  1035. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
  1036. public SID_AND_ATTRIBUTES[] Groups;
  1037. public TOKEN_GROUPS(int privilegeCount)
  1038. {
  1039. GroupCount = privilegeCount;
  1040. Groups = new SID_AND_ATTRIBUTES[32];
  1041. }
  1042. };
  1043. [StructLayout(LayoutKind.Sequential)]
  1044. internal struct SID_AND_ATTRIBUTES
  1045. {
  1046. internal IntPtr Sid;
  1047. internal uint Attributes;
  1048. }
  1049. internal struct TOKEN_PRIMARY_GROUP
  1050. {
  1051. public IntPtr PrimaryGroup; // PSID
  1052. public TOKEN_PRIMARY_GROUP(IntPtr _sid)
  1053. {
  1054. PrimaryGroup = _sid;
  1055. }
  1056. }
  1057. [StructLayout(LayoutKind.Sequential)]
  1058. internal struct TOKEN_SOURCE
  1059. {
  1060. public TOKEN_SOURCE(string name)
  1061. {
  1062. SourceName = new byte[8];
  1063. Encoding.GetEncoding(1252).GetBytes(name, 0, name.Length, SourceName, 0);
  1064. if (!AllocateLocallyUniqueId(out SourceIdentifier))
  1065. throw new System.ComponentModel.Win32Exception();
  1066. }
  1067. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
  1068. public byte[] SourceName;
  1069. public LUID SourceIdentifier;
  1070. }
  1071. [StructLayout(LayoutKind.Sequential)]
  1072. internal struct TOKEN_USER
  1073. {
  1074. public SID_AND_ATTRIBUTES User;
  1075. public TOKEN_USER(IntPtr _sid)
  1076. {
  1077. User = new SID_AND_ATTRIBUTES
  1078. {
  1079. Sid = _sid,
  1080. Attributes = 0
  1081. };
  1082. }
  1083. }
  1084. [StructLayout(LayoutKind.Sequential)]
  1085. internal struct TOKEN_OWNER
  1086. {
  1087. public IntPtr Owner; // PSID
  1088. public TOKEN_OWNER(IntPtr _owner)
  1089. {
  1090. Owner = _owner;
  1091. }
  1092. }
  1093. [DllImport("advapi32.dll", SetLastError = true)]
  1094. internal static extern bool AllocateAndInitializeSid(
  1095. ref SidIdentifierAuthority pIdentifierAuthority,
  1096. byte nSubAuthorityCount,
  1097. int dwSubAuthority0, int dwSubAuthority1,
  1098. int dwSubAuthority2, int dwSubAuthority3,
  1099. int dwSubAuthority4, int dwSubAuthority5,
  1100. int dwSubAuthority6, int dwSubAuthority7,
  1101. out IntPtr pSid);
  1102. [StructLayout(LayoutKind.Sequential)]
  1103. internal struct SidIdentifierAuthority
  1104. {
  1105. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.I1)]
  1106. internal byte[] Value;
  1107. }
  1108. internal const int NtSecurityAuthority = 5;
  1109. internal const int AuthenticatedUser = 11;
  1110. [DllImport("advapi32.dll")]
  1111. internal static extern bool AllocateLocallyUniqueId(out LUID allocated);
  1112. [DllImport("advapi32.dll")]
  1113. internal static extern IntPtr FreeSid(IntPtr pSid);
  1114. internal enum NtStatus : uint
  1115. {
  1116. // Success
  1117. Success = 0x00000000,
  1118. Wait0 = 0x00000000,
  1119. Wait1 = 0x00000001,
  1120. Wait2 = 0x00000002,
  1121. Wait3 = 0x00000003,
  1122. Wait63 = 0x0000003f,
  1123. Abandoned = 0x00000080,
  1124. AbandonedWait0 = 0x00000080,
  1125. AbandonedWait1 = 0x00000081,
  1126. AbandonedWait2 = 0x00000082,
  1127. AbandonedWait3 = 0x00000083,
  1128. AbandonedWait63 = 0x000000bf,
  1129. UserApc = 0x000000c0,
  1130. KernelApc = 0x00000100,
  1131. Alerted = 0x00000101,
  1132. Timeout = 0x00000102,
  1133. Pending = 0x00000103,
  1134. Reparse = 0x00000104,
  1135. MoreEntries = 0x00000105,
  1136. NotAllAssigned = 0x00000106,
  1137. SomeNotMapped = 0x00000107,
  1138. OpLockBreakInProgress = 0x00000108,
  1139. VolumeMounted = 0x00000109,
  1140. RxActCommitted = 0x0000010a,
  1141. NotifyCleanup = 0x0000010b,
  1142. NotifyEnumDir = 0x0000010c,
  1143. NoQuotasForAccount = 0x0000010d,
  1144. PrimaryTransportConnectFailed = 0x0000010e,
  1145. PageFaultTransition = 0x00000110,
  1146. PageFaultDemandZero = 0x00000111,
  1147. PageFaultCopyOnWrite = 0x00000112,
  1148. PageFaultGuardPage = 0x00000113,
  1149. PageFaultPagingFile = 0x00000114,
  1150. CrashDump = 0x00000116,
  1151. ReparseObject = 0x00000118,
  1152. NothingToTerminate = 0x00000122,
  1153. ProcessNotInJob = 0x00000123,
  1154. ProcessInJob = 0x00000124,
  1155. ProcessCloned = 0x00000129,
  1156. FileLockedWithOnlyReaders = 0x0000012a,
  1157. FileLockedWithWriters = 0x0000012b,
  1158. // Informational
  1159. Informational = 0x40000000,
  1160. ObjectNameExists = 0x40000000,
  1161. ThreadWasSuspended = 0x40000001,
  1162. WorkingSetLimitRange = 0x40000002,
  1163. ImageNotAtBase = 0x40000003,
  1164. RegistryRecovered = 0x40000009,
  1165. // Warning
  1166. Warning = 0x80000000,
  1167. GuardPageViolation = 0x80000001,
  1168. DatatypeMisalignment = 0x80000002,
  1169. Breakpoint = 0x80000003,
  1170. SingleStep = 0x80000004,
  1171. BufferOverflow = 0x80000005,
  1172. NoMoreFiles = 0x80000006,
  1173. HandlesClosed = 0x8000000a,
  1174. PartialCopy = 0x8000000d,
  1175. DeviceBusy = 0x80000011,
  1176. InvalidEaName = 0x80000013,
  1177. EaListInconsistent = 0x80000014,
  1178. NoMoreEntries = 0x8000001a,
  1179. LongJump = 0x80000026,
  1180. DllMightBeInsecure = 0x8000002b,
  1181. // Error
  1182. Error = 0xc0000000,
  1183. Unsuccessful = 0xc0000001,
  1184. NotImplemented = 0xc0000002,
  1185. InvalidInfoClass = 0xc0000003,
  1186. InfoLengthMismatch = 0xc0000004,
  1187. AccessViolation = 0xc0000005,
  1188. InPageError = 0xc0000006,
  1189. PagefileQuota = 0xc0000007,
  1190. InvalidHandle = 0xc0000008,
  1191. BadInitialStack = 0xc0000009,
  1192. BadInitialPc = 0xc000000a,
  1193. InvalidCid = 0xc000000b,
  1194. TimerNotCanceled = 0xc000000c,
  1195. InvalidParameter = 0xc000000d,
  1196. NoSuchDevice = 0xc000000e,
  1197. NoSuchFile = 0xc000000f,
  1198. InvalidDeviceRequest = 0xc0000010,
  1199. EndOfFile = 0xc0000011,
  1200. WrongVolume = 0xc0000012,
  1201. NoMediaInDevice = 0xc0000013,
  1202. NoMemory = 0xc0000017,
  1203. NotMappedView = 0xc0000019,
  1204. UnableToFreeVm = 0xc000001a,
  1205. UnableToDeleteSection = 0xc000001b,
  1206. IllegalInstruction = 0xc000001d,
  1207. AlreadyCommitted = 0xc0000021,
  1208. AccessDenied = 0xc0000022,
  1209. BufferTooSmall = 0xc0000023,
  1210. ObjectTypeMismatch = 0xc0000024,
  1211. NonContinuableException = 0xc0000025,
  1212. BadStack = 0xc0000028,
  1213. NotLocked = 0xc000002a,
  1214. NotCommitted = 0xc000002d,
  1215. InvalidParameterMix = 0xc0000030,
  1216. ObjectNameInvalid = 0xc0000033,
  1217. ObjectNameNotFound = 0xc0000034,
  1218. ObjectNameCollision = 0xc0000035,
  1219. ObjectPathInvalid = 0xc0000039,
  1220. ObjectPathNotFound = 0xc000003a,
  1221. ObjectPathSyntaxBad = 0xc000003b,
  1222. DataOverrun = 0xc000003c,
  1223. DataLate = 0xc000003d,
  1224. DataError = 0xc000003e,
  1225. CrcError = 0xc000003f,
  1226. SectionTooBig = 0xc0000040,
  1227. PortConnectionRefused = 0xc0000041,
  1228. InvalidPortHandle = 0xc0000042,
  1229. SharingViolation = 0xc0000043,
  1230. QuotaExceeded = 0xc0000044,
  1231. InvalidPageProtection = 0xc0000045,
  1232. MutantNotOwned = 0xc0000046,
  1233. SemaphoreLimitExceeded = 0xc0000047,
  1234. PortAlreadySet = 0xc0000048,
  1235. SectionNotImage = 0xc0000049,
  1236. SuspendCountExceeded = 0xc000004a,
  1237. ThreadIsTerminating = 0xc000004b,
  1238. BadWorkingSetLimit = 0xc000004c,
  1239. IncompatibleFileMap = 0xc000004d,
  1240. SectionProtection = 0xc000004e,
  1241. EasNotSupported = 0xc000004f,
  1242. EaTooLarge = 0xc0000050,
  1243. NonExistentEaEntry = 0xc0000051,
  1244. NoEasOnFile = 0xc0000052,
  1245. EaCorruptError = 0xc0000053,
  1246. FileLockConflict = 0xc0000054,
  1247. LockNotGranted = 0xc0000055,
  1248. DeletePending = 0xc0000056,
  1249. CtlFileNotSupported = 0xc0000057,
  1250. UnknownRevision = 0xc0000058,
  1251. RevisionMismatch = 0xc0000059,
  1252. InvalidOwner = 0xc000005a,
  1253. InvalidPrimaryGroup = 0xc000005b,
  1254. NoImpersonationToken = 0xc000005c,
  1255. CantDisableMandatory = 0xc000005d,
  1256. NoLogonServers = 0xc000005e,
  1257. NoSuchLogonSession = 0xc000005f,
  1258. NoSuchPrivilege = 0xc0000060,
  1259. PrivilegeNotHeld = 0xc0000061,
  1260. InvalidAccountName = 0xc0000062,
  1261. UserExists = 0xc0000063,
  1262. NoSuchUser = 0xc0000064,
  1263. GroupExists = 0xc0000065,
  1264. NoSuchGroup = 0xc0000066,
  1265. MemberInGroup = 0xc0000067,
  1266. MemberNotInGroup = 0xc0000068,
  1267. LastAdmin = 0xc0000069,
  1268. WrongPassword = 0xc000006a,
  1269. IllFormedPassword = 0xc000006b,
  1270. PasswordRestriction = 0xc000006c,
  1271. LogonFailure = 0xc000006d,
  1272. AccountRestriction = 0xc000006e,
  1273. InvalidLogonHours = 0xc000006f,
  1274. InvalidWorkstation = 0xc0000070,
  1275. PasswordExpired = 0xc0000071,
  1276. AccountDisabled = 0xc0000072,
  1277. NoneMapped = 0xc0000073,
  1278. TooManyLuidsRequested = 0xc0000074,
  1279. LuidsExhausted = 0xc0000075,
  1280. InvalidSubAuthority = 0xc0000076,
  1281. InvalidAcl = 0xc0000077,
  1282. InvalidSid = 0xc0000078,
  1283. InvalidSecurityDescr = 0xc0000079,
  1284. ProcedureNotFound = 0xc000007a,
  1285. InvalidImageFormat = 0xc000007b,
  1286. NoToken = 0xc000007c,
  1287. BadInheritanceAcl = 0xc000007d,
  1288. RangeNotLocked = 0xc000007e,
  1289. DiskFull = 0xc000007f,
  1290. ServerDisabled = 0xc0000080,
  1291. ServerNotDisabled = 0xc0000081,
  1292. TooManyGuidsRequested = 0xc0000082,
  1293. GuidsExhausted = 0xc0000083,
  1294. InvalidIdAuthority = 0xc0000084,
  1295. AgentsExhausted = 0xc0000085,
  1296. InvalidVolumeLabel = 0xc0000086,
  1297. SectionNotExtended = 0xc0000087,
  1298. NotMappedData = 0xc0000088,
  1299. ResourceDataNotFound = 0xc0000089,
  1300. ResourceTypeNotFound = 0xc000008a,
  1301. ResourceNameNotFound = 0xc000008b,
  1302. ArrayBoundsExceeded = 0xc000008c,
  1303. FloatDenormalOperand = 0xc000008d,
  1304. FloatDivideByZero = 0xc000008e,
  1305. FloatInexactResult = 0xc000008f,
  1306. FloatInvalidOperation = 0xc0000090,
  1307. FloatOverflow = 0xc0000091,
  1308. FloatStackCheck = 0xc0000092,
  1309. FloatUnderflow = 0xc0000093,
  1310. IntegerDivideByZero = 0xc0000094,
  1311. IntegerOverflow = 0xc0000095,
  1312. PrivilegedInstruction = 0xc0000096,
  1313. TooManyPagingFiles = 0xc0000097,
  1314. FileInvalid = 0xc0000098,
  1315. InstanceNotAvailable = 0xc00000ab,
  1316. PipeNotAvailable = 0xc00000ac,
  1317. InvalidPipeState = 0xc00000ad,
  1318. PipeBusy = 0xc00000ae,
  1319. IllegalFunction = 0xc00000af,
  1320. PipeDisconnected = 0xc00000b0,
  1321. PipeClosing = 0xc00000b1,
  1322. PipeConnected = 0xc00000b2,
  1323. PipeListening = 0xc00000b3,
  1324. InvalidReadMode = 0xc00000b4,
  1325. IoTimeout = 0xc00000b5,
  1326. FileForcedClosed = 0xc00000b6,
  1327. ProfilingNotStarted = 0xc00000b7,
  1328. ProfilingNotStopped = 0xc00000b8,
  1329. NotSameDevice = 0xc00000d4,
  1330. FileRenamed = 0xc00000d5,
  1331. CantWait = 0xc00000d8,
  1332. PipeEmpty = 0xc00000d9,
  1333. CantTerminateSelf = 0xc00000db,
  1334. InternalError = 0xc00000e5,
  1335. InvalidParameter1 = 0xc00000ef,
  1336. InvalidParameter2 = 0xc00000f0,
  1337. InvalidParameter3 = 0xc00000f1,
  1338. InvalidParameter4 = 0xc00000f2,
  1339. InvalidParameter5 = 0xc00000f3,
  1340. InvalidParameter6 = 0xc00000f4,
  1341. InvalidParameter7 = 0xc00000f5,
  1342. InvalidParameter8 = 0xc00000f6,
  1343. InvalidParameter9 = 0xc00000f7,
  1344. InvalidParameter10 = 0xc00000f8,
  1345. InvalidParameter11 = 0xc00000f9,
  1346. InvalidParameter12 = 0xc00000fa,
  1347. MappedFileSizeZero = 0xc000011e,
  1348. TooManyOpenedFiles = 0xc000011f,
  1349. Cancelled = 0xc0000120,
  1350. CannotDelete = 0xc0000121,
  1351. InvalidComputerName = 0xc0000122,
  1352. FileDeleted = 0xc0000123,
  1353. SpecialAccount = 0xc0000124,
  1354. SpecialGroup = 0xc0000125,
  1355. SpecialUser = 0xc0000126,
  1356. MembersPrimaryGroup = 0xc0000127,
  1357. FileClosed = 0xc0000128,
  1358. TooManyThreads = 0xc0000129,
  1359. ThreadNotInProcess = 0xc000012a,
  1360. TokenAlreadyInUse = 0xc000012b,
  1361. PagefileQuotaExceeded = 0xc000012c,
  1362. CommitmentLimit = 0xc000012d,
  1363. InvalidImageLeFormat = 0xc000012e,
  1364. InvalidImageNotMz = 0xc000012f,
  1365. InvalidImageProtect = 0xc0000130,
  1366. InvalidImageWin16 = 0xc0000131,
  1367. LogonServer = 0xc0000132,
  1368. DifferenceAtDc = 0xc0000133,
  1369. SynchronizationRequired = 0xc0000134,
  1370. DllNotFound = 0xc0000135,
  1371. IoPrivilegeFailed = 0xc0000137,
  1372. OrdinalNotFound = 0xc0000138,
  1373. EntryPointNotFound = 0xc0000139,
  1374. ControlCExit = 0xc000013a,
  1375. PortNotSet = 0xc0000353,
  1376. DebuggerInactive = 0xc0000354,
  1377. CallbackBypass = 0xc0000503,
  1378. PortClosed = 0xc0000700,
  1379. MessageLost = 0xc0000701,
  1380. InvalidMessage = 0xc0000702,
  1381. RequestCanceled = 0xc0000703,
  1382. RecursiveDispatch = 0xc0000704,
  1383. LpcReceiveBufferExpected = 0xc0000705,
  1384. LpcInvalidConnectionUsage = 0xc0000706,
  1385. LpcRequestsNotAllowed = 0xc0000707,
  1386. ResourceInUse = 0xc0000708,
  1387. ProcessIsProtected = 0xc0000712,
  1388. VolumeDirty = 0xc0000806,
  1389. FileCheckedOut = 0xc0000901,
  1390. CheckOutRequired = 0xc0000902,
  1391. BadFileType = 0xc0000903,
  1392. FileTooLarge = 0xc0000904,
  1393. FormsAuthRequired = 0xc0000905,
  1394. VirusInfected = 0xc0000906,
  1395. VirusDeleted = 0xc0000907,
  1396. TransactionalConflict = 0xc0190001,
  1397. InvalidTransaction = 0xc0190002,
  1398. TransactionNotActive = 0xc0190003,
  1399. TmInitializationFailed = 0xc0190004,
  1400. RmNotActive = 0xc0190005,
  1401. RmMetadataCorrupt = 0xc0190006,
  1402. TransactionNotJoined = 0xc0190007,
  1403. DirectoryNotRm = 0xc0190008,
  1404. CouldNotResizeLog = 0xc0190009,
  1405. TransactionsUnsupportedRemote = 0xc019000a,
  1406. LogResizeInvalidSize = 0xc019000b,
  1407. RemoteFileVersionMismatch = 0xc019000c,
  1408. CrmProtocolAlreadyExists = 0xc019000f,
  1409. TransactionPropagationFailed = 0xc0190010,
  1410. CrmProtocolNotFound = 0xc0190011,
  1411. TransactionSuperiorExists = 0xc0190012,
  1412. TransactionRequestNotValid = 0xc0190013,
  1413. TransactionNotRequested = 0xc0190014,
  1414. TransactionAlreadyAborted = 0xc0190015,
  1415. TransactionAlreadyCommitted = 0xc0190016,
  1416. TransactionInvalidMarshallBuffer = 0xc0190017,
  1417. CurrentTransactionNotValid = 0xc0190018,
  1418. LogGrowthFailed = 0xc0190019,
  1419. ObjectNoLongerExists = 0xc0190021,
  1420. StreamMiniversionNotFound = 0xc0190022,
  1421. StreamMiniversionNotValid = 0xc0190023,
  1422. MiniversionInaccessibleFromSpecifiedTransaction = 0xc0190024,
  1423. CantOpenMiniversionWithModifyIntent = 0xc0190025,
  1424. CantCreateMoreStreamMiniversions = 0xc0190026,
  1425. HandleNoLongerValid = 0xc0190028,
  1426. NoTxfMetadata = 0xc0190029,
  1427. LogCorruptionDetected = 0xc0190030,
  1428. CantRecoverWithHandleOpen = 0xc0190031,
  1429. RmDisconnected = 0xc0190032,
  1430. EnlistmentNotSuperior = 0xc0190033,
  1431. RecoveryNotNeeded = 0xc0190034,
  1432. RmAlreadyStarted = 0xc0190035,
  1433. FileIdentityNotPersistent = 0xc0190036,
  1434. CantBreakTransactionalDependency = 0xc0190037,
  1435. CantCrossRmBoundary = 0xc0190038,
  1436. TxfDirNotEmpty = 0xc0190039,
  1437. IndoubtTransactionsExist = 0xc019003a,
  1438. TmVolatile = 0xc019003b,
  1439. RollbackTimerExpired = 0xc019003c,
  1440. TxfAttributeCorrupt = 0xc019003d,
  1441. EfsNotAllowedInTransaction = 0xc019003e,
  1442. TransactionalOpenNotAllowed = 0xc019003f,
  1443. TransactedMappingUnsupportedRemote = 0xc0190040,
  1444. TxfMetadataAlreadyPresent = 0xc0190041,
  1445. TransactionScopeCallbacksNotSet = 0xc0190042,
  1446. TransactionRequiredPromotion = 0xc0190043,
  1447. CannotExecuteFileInTransaction = 0xc0190044,
  1448. TransactionsNotFrozen = 0xc0190045,
  1449. MaximumNtStatus = 0xffffffff
  1450. }
  1451. }
  1452. }
  1453. }