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.

317 lines
15 KiB

1 year ago
  1. #nullable enable
  2. using System;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Management;
  7. using System.ServiceProcess;
  8. using System.Text.RegularExpressions;
  9. using System.Threading.Tasks;
  10. using Microsoft.Win32;
  11. using TrustedUninstaller.Shared.Exceptions;
  12. using TrustedUninstaller.Shared.Tasks;
  13. using YamlDotNet.Serialization;
  14. namespace TrustedUninstaller.Shared.Actions
  15. {
  16. internal enum ServiceOperation
  17. {
  18. Stop,
  19. Continue,
  20. Start,
  21. Pause,
  22. Delete,
  23. Change
  24. }
  25. internal class ServiceAction : ITaskAction
  26. {
  27. [YamlMember(typeof(ServiceOperation), Alias = "operation")]
  28. public ServiceOperation Operation { get; set; } = ServiceOperation.Delete;
  29. [YamlMember(typeof(string), Alias = "name")]
  30. public string ServiceName { get; set; } = null!;
  31. [YamlMember(typeof(int), Alias = "startup")]
  32. public int? Startup { get; set; }
  33. [YamlMember(typeof(bool), Alias = "deleteStop")]
  34. public bool DeleteStop { get; set; } = true;
  35. [YamlMember(typeof(bool), Alias = "deleteUsingRegistry")]
  36. public bool RegistryDelete { get; set; } = false;
  37. [YamlMember(typeof(string), Alias = "device")]
  38. public bool Device { get; set; } = false;
  39. [YamlMember(typeof(string), Alias = "weight")]
  40. public int ProgressWeight { get; set; } = 4;
  41. public int GetProgressWeight() => ProgressWeight;
  42. private bool InProgress { get; set; }
  43. public void ResetProgress() => InProgress = false;
  44. public string ErrorString() => $"ServiceAction failed to {Operation.ToString().ToLower()} service {ServiceName}.";
  45. private ServiceController? GetService()
  46. {
  47. if (ServiceName.EndsWith("*") && ServiceName.StartsWith("*")) return ServiceController.GetServices()
  48. .FirstOrDefault(service => service.ServiceName.IndexOf(ServiceName.Trim('*'), StringComparison.CurrentCultureIgnoreCase) >= 0);
  49. if (ServiceName.EndsWith("*")) return ServiceController.GetServices()
  50. .FirstOrDefault(service => service.ServiceName.StartsWith(ServiceName.TrimEnd('*'), StringComparison.CurrentCultureIgnoreCase));
  51. if (ServiceName.StartsWith("*")) return ServiceController.GetServices()
  52. .FirstOrDefault(service => service.ServiceName.EndsWith(ServiceName.TrimStart('*'), StringComparison.CurrentCultureIgnoreCase));
  53. return ServiceController.GetServices()
  54. .FirstOrDefault(service => service.ServiceName.Equals(ServiceName, StringComparison.CurrentCultureIgnoreCase));
  55. }
  56. private ServiceController? GetDevice()
  57. {
  58. if (ServiceName.EndsWith("*") && ServiceName.StartsWith("*")) return ServiceController.GetDevices()
  59. .FirstOrDefault(service => service.ServiceName.IndexOf(ServiceName.Trim('*'), StringComparison.CurrentCultureIgnoreCase) >= 0);
  60. if (ServiceName.EndsWith("*")) return ServiceController.GetDevices()
  61. .FirstOrDefault(service => service.ServiceName.StartsWith(ServiceName.TrimEnd('*'), StringComparison.CurrentCultureIgnoreCase));
  62. if (ServiceName.StartsWith("*")) return ServiceController.GetDevices()
  63. .FirstOrDefault(service => service.ServiceName.EndsWith(ServiceName.TrimStart('*'), StringComparison.CurrentCultureIgnoreCase));
  64. return ServiceController.GetDevices()
  65. .FirstOrDefault(service => service.ServiceName.Equals(ServiceName, StringComparison.CurrentCultureIgnoreCase));
  66. }
  67. public UninstallTaskStatus GetStatus()
  68. {
  69. if (InProgress) return UninstallTaskStatus.InProgress;
  70. if (Operation == ServiceOperation.Change && Startup.HasValue)
  71. {
  72. // TODO: Implement dev log. Example:
  73. // if (Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\{ServiceName}") == null) WriteToDevLog($"Warning: Service name '{ServiceName}' not found in registry.");
  74. var root = Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\{ServiceName}");
  75. if (root == null) return UninstallTaskStatus.Completed;
  76. var value = root.GetValue("Start");
  77. return (int)value == Startup.Value ? UninstallTaskStatus.Completed : UninstallTaskStatus.ToDo;
  78. }
  79. ServiceController serviceController;
  80. if (Device) serviceController = GetDevice();
  81. else serviceController = GetService();
  82. if (Operation == ServiceOperation.Delete && RegistryDelete)
  83. {
  84. // TODO: Implement dev log. Example:
  85. // if (Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\{ServiceName}") == null) WriteToDevLog($"Warning: Service name '{ServiceName}' not found in registry.");
  86. var root = Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\{ServiceName}");
  87. return root == null ? UninstallTaskStatus.Completed : UninstallTaskStatus.ToDo;
  88. }
  89. return Operation switch
  90. {
  91. ServiceOperation.Stop =>
  92. serviceController?.Status == ServiceControllerStatus.Stopped
  93. || serviceController?.Status == ServiceControllerStatus.StopPending ?
  94. UninstallTaskStatus.Completed : UninstallTaskStatus.ToDo,
  95. ServiceOperation.Continue =>
  96. serviceController?.Status == ServiceControllerStatus.Running
  97. || serviceController?.Status == ServiceControllerStatus.ContinuePending ?
  98. UninstallTaskStatus.Completed : UninstallTaskStatus.ToDo,
  99. ServiceOperation.Start =>
  100. serviceController?.Status == ServiceControllerStatus.StartPending
  101. || serviceController?.Status == ServiceControllerStatus.Running ?
  102. UninstallTaskStatus.Completed : UninstallTaskStatus.ToDo,
  103. ServiceOperation.Pause =>
  104. serviceController?.Status == ServiceControllerStatus.Paused
  105. || serviceController?.Status == ServiceControllerStatus.PausePending ?
  106. UninstallTaskStatus.Completed : UninstallTaskStatus.ToDo,
  107. ServiceOperation.Delete =>
  108. serviceController == null ?
  109. UninstallTaskStatus.Completed : UninstallTaskStatus.ToDo,
  110. _ => throw new ArgumentOutOfRangeException("Argument out of Range", new ArgumentOutOfRangeException())
  111. };
  112. }
  113. private readonly string[] RegexNoKill = { "DcomLaunch" };
  114. public async Task<bool> RunTask()
  115. {
  116. if (InProgress) throw new TaskInProgressException("Another Service action was called while one was in progress.");
  117. if (Operation == ServiceOperation.Change && !Startup.HasValue) throw new ArgumentException("Startup property must be specified with the change operation.");
  118. if (Operation == ServiceOperation.Change && (Startup.Value > 4 || Startup.Value < 0)) throw new ArgumentException("Startup property must be between 1 and 4.");
  119. // This is a little cursed but it works and is concise lol
  120. Console.WriteLine($"{Operation.ToString().Replace("Stop", "Stopp").TrimEnd('e')}ing services matching '{ServiceName}'...");
  121. if (Operation == ServiceOperation.Change)
  122. {
  123. var action = new RegistryValueAction()
  124. {
  125. KeyName = $@"HKLM\SYSTEM\CurrentControlSet\Services\{ServiceName}",
  126. Value = "Start",
  127. Data = Startup.Value,
  128. Type = RegistryValueType.REG_DWORD,
  129. Operation = RegistryValueOperation.Set
  130. };
  131. await action.RunTask();
  132. InProgress = false;
  133. return true;
  134. }
  135. ServiceController? service;
  136. if (Device) service = GetDevice();
  137. else service = GetService();
  138. if (service == null)
  139. {
  140. Console.WriteLine($"No services found matching '{ServiceName}'.");
  141. //ErrorLogger.WriteToErrorLog($"The service matching '{ServiceName}' does not exist.", Environment.StackTrace, "ServiceAction Error");
  142. return false;
  143. }
  144. InProgress = true;
  145. var cmdAction = new CmdAction();
  146. if (Operation == ServiceOperation.Delete || Operation == ServiceOperation.Stop)
  147. {
  148. if (RegexNoKill.Any(regex => Regex.Match(ServiceName, regex, RegexOptions.IgnoreCase).Success))
  149. {
  150. Console.WriteLine($"Skipping {ServiceName}...");
  151. return false;
  152. }
  153. foreach (ServiceController dependentService in service.DependentServices)
  154. {
  155. Console.WriteLine($"Killing dependent service {dependentService.ServiceName}...");
  156. cmdAction.Command = Environment.Is64BitOperatingSystem ?
  157. $"ProcessHacker\\x64\\ProcessHacker.exe -s -elevate -c -ctype service -cobject {dependentService.ServiceName} -caction stop" :
  158. $"ProcessHacker\\x86\\ProcessHacker.exe -s -elevate -c -ctype service -cobject {dependentService.ServiceName} -caction stop";
  159. await cmdAction.RunTask();
  160. Console.WriteLine("Waiting for the service to stop...");
  161. int delay = 100;
  162. while (service.Status != ServiceControllerStatus.Stopped && delay <= 1000)
  163. {
  164. service.Refresh();
  165. //Wait for the service to stop
  166. Task.Delay(delay).Wait();
  167. delay += 100;
  168. }
  169. if (delay >= 1000)
  170. {
  171. Console.WriteLine("\r\nService stop timeout exceeded. Trying second method...");
  172. try
  173. {
  174. using var search = new ManagementObjectSearcher($"SELECT * FROM Win32_Service WHERE Name='{service.ServiceName}'");
  175. foreach (ManagementObject queryObj in search.Get())
  176. {
  177. var serviceId = (UInt32)queryObj["ProcessId"]; // Access service name
  178. var killServ = new TaskKillAction()
  179. {
  180. ProcessID = (int)serviceId
  181. };
  182. await killServ.RunTask();
  183. }
  184. }
  185. catch (Exception e)
  186. {
  187. ErrorLogger.WriteToErrorLog($"Could not kill dependent service {dependentService.ServiceName}.",
  188. e.StackTrace, "ServiceAction Error");
  189. }
  190. }
  191. }
  192. if (service.ServiceName == "SgrmAgent" && ((Operation == ServiceOperation.Delete && DeleteStop) || Operation == ServiceOperation.Stop))
  193. {
  194. await new TaskKillAction() { ProcessName = "SgrmBroker" }.RunTask();
  195. }
  196. }
  197. if (Operation == ServiceOperation.Delete)
  198. {
  199. if (DeleteStop && service.Status != ServiceControllerStatus.StopPending && service.Status != ServiceControllerStatus.Stopped)
  200. {
  201. cmdAction.Command = Environment.Is64BitOperatingSystem ?
  202. $"ProcessHacker\\x64\\ProcessHacker.exe -s -elevate -c -ctype service -cobject {service.ServiceName} -caction stop" :
  203. $"ProcessHacker\\x86\\ProcessHacker.exe -s -elevate -c -ctype service -cobject {service.ServiceName} -caction stop";
  204. await cmdAction.RunTask();
  205. }
  206. Console.WriteLine("Waiting for the service to stop...");
  207. int delay = 100;
  208. while (DeleteStop && service.Status != ServiceControllerStatus.Stopped && delay <= 1500)
  209. {
  210. service.Refresh();
  211. //Wait for the service to stop
  212. await Task.Delay(delay);
  213. delay += 100;
  214. }
  215. if (delay >= 1500)
  216. {
  217. Console.WriteLine("\r\nService stop timeout exceeded. Trying second method...");
  218. try
  219. {
  220. using var search = new ManagementObjectSearcher($"SELECT * FROM Win32_Service WHERE Name='{service.ServiceName}'");
  221. foreach (ManagementObject queryObj in search.Get())
  222. {
  223. var serviceId = (UInt32)queryObj["ProcessId"]; // Access service name
  224. var killServ = new TaskKillAction()
  225. {
  226. ProcessID = (int)serviceId
  227. };
  228. await killServ.RunTask();
  229. }
  230. }
  231. catch (Exception e)
  232. {
  233. ErrorLogger.WriteToErrorLog($"Could not kill service {service.ServiceName}.",
  234. e.StackTrace, "ServiceAction Error");
  235. }
  236. }
  237. if (RegistryDelete)
  238. {
  239. var action = new RegistryKeyAction()
  240. {
  241. KeyName = $@"HKLM\SYSTEM\CurrentControlSet\Services\{ServiceName}",
  242. Operation = RegistryKeyOperation.Delete
  243. };
  244. await action.RunTask();
  245. }
  246. else
  247. {
  248. cmdAction.Command = Environment.Is64BitOperatingSystem ?
  249. $"ProcessHacker\\x64\\ProcessHacker.exe -s -elevate -c -ctype service -cobject {service.ServiceName} -caction delete" :
  250. $"ProcessHacker\\x86\\ProcessHacker.exe -s -elevate -c -ctype service -cobject {service.ServiceName} -caction delete";
  251. await cmdAction.RunTask();
  252. }
  253. }
  254. else
  255. {
  256. cmdAction.Command = Environment.Is64BitOperatingSystem ?
  257. $"ProcessHacker\\x64\\ProcessHacker.exe -s -elevate -c -ctype service -cobject {ServiceName} -caction {Operation.ToString().ToLower()}" :
  258. $"ProcessHacker\\x86\\ProcessHacker.exe -s -elevate -c -ctype service -cobject {ServiceName} -caction {Operation.ToString().ToLower()}";
  259. await cmdAction.RunTask();
  260. }
  261. service?.Dispose();
  262. await Task.Delay(100);
  263. InProgress = false;
  264. return true;
  265. }
  266. }
  267. }