diff --git a/Services/AdminOnlyDirectory.cs b/Services/AdminOnlyDirectory.cs new file mode 100644 index 0000000..09ee8ac --- /dev/null +++ b/Services/AdminOnlyDirectory.cs @@ -0,0 +1,54 @@ +/* + * ThreadPilot - directories only administrators and SYSTEM can write, for files the elevated app later runs or hands to Windows. + */ +namespace ThreadPilot.Services +{ + using System; + using System.IO; + using System.Security.AccessControl; + using System.Security.Principal; + + public static class AdminOnlyDirectory + { + /// + /// Gets the default parent: in %SystemRoot%\Temp users may create folders but cannot rename or delete + /// another account's, unlike their own %TEMP%, where they could swap a file between check and use. + /// + public static string DefaultRoot { get; } = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Temp"); + + /// Creates (which must not exist) with an Administrators + SYSTEM only DACL. + public static string Create(string path) + { + var security = new DirectorySecurity(); + security.SetAccessRuleProtection(isProtected: true, preserveInheritance: false); + Allow(security, new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null)); + Allow(security, new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null)); + + // Not elevated (tests, dev runs): there is no privilege gap to protect, and without this the + // process could not write its own files. + using var identity = WindowsIdentity.GetCurrent(); + if (!new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator) && identity.User != null) + { + Allow(security, identity.User); + } + + if (Directory.Exists(path) || File.Exists(path)) + { + throw new IOException($"Refusing to reuse existing path '{path}'."); + } + + security.CreateDirectory(path); + return path; + } + + private static void Allow(DirectorySecurity security, IdentityReference identity) + { + security.AddAccessRule(new FileSystemAccessRule( + identity, + FileSystemRights.FullControl, + InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, + PropagationFlags.None, + AccessControlType.Allow)); + } + } +} diff --git a/Services/ElevatedTaskService.cs b/Services/ElevatedTaskService.cs index df982ef..31dc8fb 100644 --- a/Services/ElevatedTaskService.cs +++ b/Services/ElevatedTaskService.cs @@ -101,7 +101,9 @@ namespace ThreadPilot.Services return true; } - var taskXmlPath = Path.Combine(Path.GetTempPath(), $"threadpilot-launch-task-{Guid.NewGuid():N}.xml"); + // 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( @@ -128,7 +130,7 @@ namespace ThreadPilot.Services } finally { - TryDeleteFile(taskXmlPath, this.logger); + TryDeleteDirectory(taskXmlDirectory, this.logger); } } catch (Exception ex) @@ -421,13 +423,13 @@ namespace ThreadPilot.Services return this.processRunner.RunAsync(SchTasksExecutablePath, arguments, ScheduledTaskTimeout); } - private static void TryDeleteFile(string path, ILogger logger) + private static void TryDeleteDirectory(string path, ILogger logger) { try { - if (File.Exists(path)) + if (Directory.Exists(path)) { - File.Delete(path); + Directory.Delete(path, recursive: true); } } catch (Exception ex) diff --git a/Services/UpdateTempDirectoryProvider.cs b/Services/UpdateTempDirectoryProvider.cs index 4f9a8d0..b46047d 100644 --- a/Services/UpdateTempDirectoryProvider.cs +++ b/Services/UpdateTempDirectoryProvider.cs @@ -6,12 +6,18 @@ namespace ThreadPilot.Services using System; using System.IO; + /// + /// Each download gets its own admin-only folder directly under the root, with an unguessable name, so a + /// non-admin process cannot swap the verified installer (or plant DLLs beside it) before it runs elevated. + /// public sealed class UpdateTempDirectoryProvider : IUpdateTempDirectoryProvider { + private const string FolderPrefix = "ThreadPilot-update-"; + private readonly string rootDirectory; public UpdateTempDirectoryProvider() - : this(Path.Combine(Path.GetTempPath(), "ThreadPilot", "Updates")) + : this(AdminOnlyDirectory.DefaultRoot) { } @@ -22,9 +28,7 @@ namespace ThreadPilot.Services public string CreateUpdateTempDirectory(SemanticVersion version) { - var directory = Path.Combine(this.rootDirectory, version.ToString(), Guid.NewGuid().ToString("N")); - Directory.CreateDirectory(directory); - return directory; + return AdminOnlyDirectory.Create(Path.Combine(this.rootDirectory, $"{FolderPrefix}{version}-{Guid.NewGuid():N}")); } public bool IsSafeUpdateTempPath(string path) @@ -35,9 +39,8 @@ namespace ThreadPilot.Services } var fullPath = Path.GetFullPath(path); - var rootWithSeparator = this.rootDirectory.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) - + Path.DirectorySeparatorChar; - return fullPath.StartsWith(rootWithSeparator, StringComparison.OrdinalIgnoreCase); + var prefix = Path.TrimEndingDirectorySeparator(this.rootDirectory) + Path.DirectorySeparatorChar + FolderPrefix; + return fullPath.StartsWith(prefix, StringComparison.OrdinalIgnoreCase); } public void Cleanup(string path) @@ -48,21 +51,6 @@ namespace ThreadPilot.Services } Directory.Delete(path, recursive: true); - this.DeleteEmptyParentsUntilRoot(Path.GetDirectoryName(Path.GetFullPath(path))); - } - - private void DeleteEmptyParentsUntilRoot(string? directory) - { - while (!string.IsNullOrWhiteSpace(directory) && this.IsSafeUpdateTempPath(directory)) - { - if (Directory.GetFileSystemEntries(directory).Length > 0) - { - return; - } - - Directory.Delete(directory); - directory = Path.GetDirectoryName(directory); - } } } } diff --git a/Tests/ThreadPilot.Core.Tests/AdminOnlyDirectoryTests.cs b/Tests/ThreadPilot.Core.Tests/AdminOnlyDirectoryTests.cs new file mode 100644 index 0000000..d5c41a5 --- /dev/null +++ b/Tests/ThreadPilot.Core.Tests/AdminOnlyDirectoryTests.cs @@ -0,0 +1,81 @@ +namespace ThreadPilot.Core.Tests +{ + using System.Security.AccessControl; + using System.Security.Principal; + using ThreadPilot.Services; + + public sealed class AdminOnlyDirectoryTests + { + [Fact] + public void Create_GrantsOnlyAdministratorsAndSystem_WithoutInheritingTheParentAcl() + { + var path = Path.Combine(Path.GetTempPath(), $"threadpilot-acl-{Guid.NewGuid():N}"); + try + { + AdminOnlyDirectory.Create(path); + + var security = new DirectoryInfo(path).GetAccessControl(); + Assert.True(security.AreAccessRulesProtected); + + var allowed = security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier)) + .Cast() + .Select(rule => (SecurityIdentifier)rule.IdentityReference) + .ToHashSet(); + var expected = new HashSet + { + new(WellKnownSidType.LocalSystemSid, null), + new(WellKnownSidType.BuiltinAdministratorsSid, null), + }; + using var identity = WindowsIdentity.GetCurrent(); + if (!new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)) + { + expected.Add(identity.User!); + } + + Assert.Equal(expected, allowed); + } + finally + { + if (Directory.Exists(path)) + { + Directory.Delete(path, recursive: true); + } + } + } + + [Fact] + public void Create_RefusesAnExistingFolder() + { + var path = Directory.CreateTempSubdirectory("threadpilot-acl-").FullName; + try + { + Assert.Throws(() => AdminOnlyDirectory.Create(path)); + } + finally + { + Directory.Delete(path, recursive: true); + } + } + + [Fact] + public void UpdateFolders_AreCreatedDirectlyUnderTheRoot_AndOnlyThoseAreTrusted() + { + var root = Directory.CreateTempSubdirectory("threadpilot-updates-").FullName; + try + { + var provider = new UpdateTempDirectoryProvider(root); + + var created = provider.CreateUpdateTempDirectory(new SemanticVersion(1, 8, 0)); + + Assert.Equal(root, Path.GetDirectoryName(created)); + Assert.True(provider.IsSafeUpdateTempPath(Path.Combine(created, "ThreadPilot_v1.8.0_Setup.exe"))); + Assert.False(provider.IsSafeUpdateTempPath(Path.Combine(root, "other", "ThreadPilot_v1.8.0_Setup.exe"))); + Assert.False(provider.IsSafeUpdateTempPath(Path.Combine(created, "..", "..", "Setup.exe"))); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + } +}