namespace ThreadPilot.Services { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Security; using System.Security.Principal; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using ThreadPilot.Services.Abstractions; public partial class ElevatedTaskService : IElevatedTaskService { private static readonly string SchTasksExecutablePath = Path.Combine(Environment.SystemDirectory, "schtasks.exe"); private static readonly TimeSpan ScheduledTaskTimeout = TimeSpan.FromSeconds(20); private readonly ILogger logger; private readonly IProcessRunner processRunner; private readonly Func? executablePathProvider; private readonly Func? currentUserProvider; private readonly Func isProtectedInstallPath; public ElevatedTaskService(ILogger logger, IProcessRunner processRunner) : this(logger, processRunner, null, null) { } public ElevatedTaskService( ILogger logger, IProcessRunner processRunner, Func? executablePathProvider, Func? currentUserProvider, Func? isProtectedInstallPath = null) { this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); this.processRunner = processRunner ?? throw new ArgumentNullException(nameof(processRunner)); this.executablePathProvider = executablePathProvider; this.currentUserProvider = currentUserProvider; this.isProtectedInstallPath = isProtectedInstallPath ?? IsProtectedInstallPath; } public string LaunchTaskName => "ThreadPilot_Launch"; public string AutostartTaskName => "ThreadPilot_Startup"; /// /// True when the path is inside Program Files. The tasks run with highest privileges and no UAC prompt, /// so they may only point at an exe that a non-admin user cannot replace. /// public static bool IsProtectedInstallPath(string? executablePath) { if (string.IsNullOrWhiteSpace(executablePath) || !Path.IsPathFullyQualified(executablePath)) { return false; } string fullPath; try { fullPath = Path.GetFullPath(executablePath); } catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) { return false; } return new[] { Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolder.ProgramFilesX86 } .Select(Environment.GetFolderPath) .Where(root => !string.IsNullOrWhiteSpace(root)) .Select(root => Path.TrimEndingDirectorySeparator(root) + Path.DirectorySeparatorChar) .Any(root => fullPath.StartsWith(root, StringComparison.OrdinalIgnoreCase)); } public async Task EnsureLaunchTaskAsync() { try { var executablePath = this.executablePathProvider?.Invoke() ?? this.GetExecutablePath(); await this.RemoveTasksOutsideProtectedLocationsAsync(); if (!IsValidExecutablePath(executablePath)) { LogSkipEnsureLaunchTaskInvalidPath(this.logger, executablePath ?? "(null)"); return false; } if (!this.isProtectedInstallPath(executablePath)) { LogLaunchTaskNotRegisteredUnprotectedPath(this.logger, executablePath!); return false; } // schtasks reads the definition from a file: keep it where only admins can change it before it does. var taskXmlDirectory = AdminOnlyDirectory.Create(Path.Combine(AdminOnlyDirectory.DefaultRoot, $"ThreadPilot-task-{Guid.NewGuid():N}")); var taskXmlPath = Path.Combine(taskXmlDirectory, "launch-task.xml"); try { WriteLaunchTaskDefinition( taskXmlPath, executablePath!, this.currentUserProvider?.Invoke() ?? GetCurrentUserName()); var result = await this.RunSchTasksAsync(new List { "/Create", "/TN", this.LaunchTaskName, "/XML", taskXmlPath, "/F", }); if (result.ExitCode == 0) { LogLaunchTaskEnsured(this.logger, this.LaunchTaskName, executablePath!); return true; } LogEnsureLaunchTaskFailed(this.logger, result.ExitCode, result.StandardError); return false; } finally { TryDeleteDirectory(taskXmlDirectory, this.logger); } } catch (Exception ex) { LogEnsureLaunchTaskException(this.logger, ex); return false; } } public async Task TryRunLaunchTaskAsync() { try { var result = await this.RunSchTasksAsync(new List { "/Run", "/TN", this.LaunchTaskName, }); if (result.ExitCode == 0) { LogLaunchTaskStarted(this.logger, this.LaunchTaskName); return true; } LogRunLaunchTaskFailed(this.logger, result.ExitCode, result.StandardError); return false; } catch (Exception ex) { LogRunLaunchTaskException(this.logger, ex); return false; } } public async Task EnsureAutostartTaskAsync(string executablePath, string arguments) { try { if (!IsValidExecutablePath(executablePath)) { LogSkipEnsureAutostartTaskInvalidPath(this.logger, executablePath); return false; } if (!this.isProtectedInstallPath(executablePath)) { LogAutostartTaskNotRegisteredUnprotectedPath(this.logger, executablePath); return false; } var taskRunCommand = BuildCommand(executablePath, arguments); var result = await this.RunSchTasksAsync(new List { "/Create", "/TN", this.AutostartTaskName, "/TR", taskRunCommand, "/SC", "ONLOGON", "/RL", "HIGHEST", "/F", "/RU", Environment.UserName, }); if (result.ExitCode == 0) { LogAutostartTaskEnsured(this.logger, this.AutostartTaskName); return true; } LogEnsureAutostartTaskFailed(this.logger, result.ExitCode, result.StandardError); return false; } catch (Exception ex) { LogEnsureAutostartTaskException(this.logger, ex); return false; } } public async Task RemoveAutostartTaskAsync() { try { var result = await this.RunSchTasksAsync(new List { "/Delete", "/TN", this.AutostartTaskName, "/F", }); if (result.ExitCode == 0) { LogAutostartTaskRemoved(this.logger, this.AutostartTaskName); return true; } // Exit code 1 is expected when task doesn't exist; treat as already removed. if (result.ExitCode == 1) { LogAutostartTaskAlreadyRemoved(this.logger, this.AutostartTaskName); return true; } LogRemoveAutostartTaskFailed(this.logger, result.ExitCode, result.StandardError); return false; } catch (Exception ex) { LogRemoveAutostartTaskException(this.logger, ex); return false; } } public async Task IsAutostartTaskRegisteredAsync() { try { var result = await this.RunSchTasksAsync(new List { "/Query", "/TN", this.AutostartTaskName, }); var exists = result.ExitCode == 0; LogAutostartTaskQueryResult(this.logger, this.AutostartTaskName, exists, result.ExitCode); return exists; } catch (Exception ex) { LogAutostartTaskQueryException(this.logger, ex); return false; } } // Deletes ThreadPilot tasks left pointing at a user-writable exe (portable or dev copies, older versions). private async Task RemoveTasksOutsideProtectedLocationsAsync() { foreach (var taskName in new[] { this.LaunchTaskName, this.AutostartTaskName }) { var command = await this.QueryTaskCommandAsync(taskName); if (command == null || this.isProtectedInstallPath(command)) { continue; } var result = await this.RunSchTasksAsync(new List { "/Delete", "/TN", taskName, "/F" }); LogUnprotectedTaskRemoved(this.logger, taskName, command, result.ExitCode); } } // schtasks prints the XML in the console code page despite its UTF-16 header, so read it as text. private async Task QueryTaskCommandAsync(string taskName) { var result = await this.RunSchTasksAsync(new List { "/Query", "/TN", taskName, "/XML" }); if (result.ExitCode != 0) { return null; } var match = Regex.Match(result.StandardOutput ?? string.Empty, "(.*?)", RegexOptions.Singleline); return match.Success ? WebUtility.HtmlDecode(match.Groups[1].Value).Trim().Trim('"') : null; } private string? GetExecutablePath() { try { var currentPath = Process.GetCurrentProcess().MainModule?.FileName; if (IsValidExecutablePath(currentPath)) { return currentPath; } var assemblyLocation = Assembly.GetExecutingAssembly().Location; if (!string.IsNullOrWhiteSpace(assemblyLocation) && assemblyLocation.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) { var candidatePath = Path.ChangeExtension(assemblyLocation, ".exe"); if (IsValidExecutablePath(candidatePath)) { return candidatePath; } } return IsValidExecutablePath(assemblyLocation) ? assemblyLocation : null; } catch (Exception ex) { LogGetExecutablePathFailed(this.logger, ex); return null; } } private static string BuildCommand(string executablePath, string arguments) { var trimmedArguments = arguments?.Trim(); return string.IsNullOrWhiteSpace(trimmedArguments) ? $"\"{executablePath}\"" : $"\"{executablePath}\" {trimmedArguments}"; } private static bool IsValidExecutablePath(string? executablePath) { if (string.IsNullOrWhiteSpace(executablePath) || !Path.IsPathFullyQualified(executablePath)) { return false; } return File.Exists(executablePath) && string.Equals(Path.GetExtension(executablePath), ".exe", StringComparison.OrdinalIgnoreCase); } private static string GetCurrentUserName() { var userName = WindowsIdentity.GetCurrent().Name; if (string.IsNullOrWhiteSpace(userName)) { throw new InvalidOperationException("Could not determine current user identity for launch task registration."); } return userName; } private static void WriteLaunchTaskDefinition(string taskXmlPath, string executablePath, string userName) { if (string.IsNullOrWhiteSpace(userName)) { throw new InvalidOperationException("Could not determine current user identity for launch task registration."); } var workingDirectory = Path.GetDirectoryName(executablePath); if (string.IsNullOrWhiteSpace(workingDirectory)) { throw new InvalidOperationException("Could not determine working directory for launch task registration."); } var escapedUserName = SecurityElement.Escape(userName); var escapedExecutablePath = SecurityElement.Escape(executablePath); var escapedArguments = SecurityElement.Escape("--launched-via-task"); var escapedWorkingDirectory = SecurityElement.Escape(workingDirectory); var taskXml = $@" ThreadPilot Launches ThreadPilot with highest available privileges on demand. {escapedUserName} InteractiveToken HighestAvailable IgnoreNew false false false false false false false true true false false false PT0S 7 {escapedExecutablePath} {escapedArguments} {escapedWorkingDirectory} "; File.WriteAllText(taskXmlPath, taskXml, Encoding.Unicode); } private Task RunSchTasksAsync(IReadOnlyList arguments) { return this.processRunner.RunAsync(SchTasksExecutablePath, arguments, ScheduledTaskTimeout); } private static void TryDeleteDirectory(string path, ILogger logger) { try { if (Directory.Exists(path)) { Directory.Delete(path, recursive: true); } } catch (Exception ex) { LogDeleteTemporaryFileFailed(logger, path, ex); } } [LoggerMessage(EventId = 4250, Level = LogLevel.Warning, Message = "Skipping launch task registration due to invalid executable path: {Path}")] private static partial void LogSkipEnsureLaunchTaskInvalidPath(ILogger logger, string path); [LoggerMessage(EventId = 4251, Level = LogLevel.Information, Message = "Ensured elevated launch task '{TaskName}' for executable '{ExecutablePath}'")] private static partial void LogLaunchTaskEnsured(ILogger logger, string taskName, string executablePath); [LoggerMessage(EventId = 4252, Level = LogLevel.Warning, Message = "Failed to ensure elevated launch task. Exit code: {ExitCode}, Error: {Error}")] private static partial void LogEnsureLaunchTaskFailed(ILogger logger, int exitCode, string error); [LoggerMessage(EventId = 4253, Level = LogLevel.Warning, Message = "Exception while ensuring elevated launch task")] private static partial void LogEnsureLaunchTaskException(ILogger logger, Exception ex); [LoggerMessage(EventId = 4254, Level = LogLevel.Information, Message = "Started elevated launch task '{TaskName}'")] private static partial void LogLaunchTaskStarted(ILogger logger, string taskName); [LoggerMessage(EventId = 4255, Level = LogLevel.Warning, Message = "Failed to run elevated launch task. Exit code: {ExitCode}, Error: {Error}")] private static partial void LogRunLaunchTaskFailed(ILogger logger, int exitCode, string error); [LoggerMessage(EventId = 4256, Level = LogLevel.Warning, Message = "Exception while running elevated launch task")] private static partial void LogRunLaunchTaskException(ILogger logger, Exception ex); [LoggerMessage(EventId = 4257, Level = LogLevel.Warning, Message = "Skipping autostart task registration due to invalid executable path: {Path}")] private static partial void LogSkipEnsureAutostartTaskInvalidPath(ILogger logger, string path); [LoggerMessage(EventId = 4258, Level = LogLevel.Information, Message = "Ensured elevated autostart task '{TaskName}'")] private static partial void LogAutostartTaskEnsured(ILogger logger, string taskName); [LoggerMessage(EventId = 4259, Level = LogLevel.Warning, Message = "Failed to ensure elevated autostart task. Exit code: {ExitCode}, Error: {Error}")] private static partial void LogEnsureAutostartTaskFailed(ILogger logger, int exitCode, string error); [LoggerMessage(EventId = 4260, Level = LogLevel.Warning, Message = "Exception while ensuring elevated autostart task")] private static partial void LogEnsureAutostartTaskException(ILogger logger, Exception ex); [LoggerMessage(EventId = 4261, Level = LogLevel.Information, Message = "Removed elevated autostart task '{TaskName}'")] private static partial void LogAutostartTaskRemoved(ILogger logger, string taskName); [LoggerMessage(EventId = 4262, Level = LogLevel.Debug, Message = "Elevated autostart task '{TaskName}' was already absent")] private static partial void LogAutostartTaskAlreadyRemoved(ILogger logger, string taskName); [LoggerMessage(EventId = 4263, Level = LogLevel.Warning, Message = "Failed to remove elevated autostart task. Exit code: {ExitCode}, Error: {Error}")] private static partial void LogRemoveAutostartTaskFailed(ILogger logger, int exitCode, string error); [LoggerMessage(EventId = 4264, Level = LogLevel.Warning, Message = "Exception while removing elevated autostart task")] private static partial void LogRemoveAutostartTaskException(ILogger logger, Exception ex); [LoggerMessage(EventId = 4265, Level = LogLevel.Debug, Message = "Autostart task query for '{TaskName}': Exists={Exists}, ExitCode={ExitCode}")] private static partial void LogAutostartTaskQueryResult(ILogger logger, string taskName, bool exists, int exitCode); [LoggerMessage(EventId = 4266, Level = LogLevel.Warning, Message = "Exception while querying elevated autostart task")] private static partial void LogAutostartTaskQueryException(ILogger logger, Exception ex); [LoggerMessage(EventId = 4267, Level = LogLevel.Warning, Message = "Failed to resolve executable path while ensuring elevated tasks")] private static partial void LogGetExecutablePathFailed(ILogger logger, Exception ex); [LoggerMessage(EventId = 4268, Level = LogLevel.Debug, Message = "Failed to delete temporary file '{Path}'")] private static partial void LogDeleteTemporaryFileFailed(ILogger logger, string path, Exception ex); [LoggerMessage(EventId = 4269, Level = LogLevel.Information, Message = "Elevated launch task not registered: '{ExecutablePath}' is outside Program Files, so a non-admin user could replace it")] private static partial void LogLaunchTaskNotRegisteredUnprotectedPath(ILogger logger, string executablePath); [LoggerMessage(EventId = 4270, Level = LogLevel.Warning, Message = "Autostart task not registered: '{ExecutablePath}' is outside Program Files, so a non-admin user could replace it")] private static partial void LogAutostartTaskNotRegisteredUnprotectedPath(ILogger logger, string executablePath); [LoggerMessage(EventId = 4271, Level = LogLevel.Warning, Message = "Removed task '{TaskName}' pointing at '{Command}' outside Program Files (schtasks exit code {ExitCode})")] private static partial void LogUnprotectedTaskRemoved(ILogger logger, string taskName, string command, int exitCode); } }