security: keep the task XML and update installer in admin-only folders

The elevated app wrote the scheduled-task definition and downloaded the update
installer into the user's %TEMP%, where a non-admin process can swap them (or
plant DLLs beside the installer) between the check and the elevated use. Both
now go into a fresh, unguessable folder under %SystemRoot%\Temp whose DACL
grants only Administrators and SYSTEM; users there cannot rename or delete
another account's folders.
This commit is contained in:
PrimeBuild-pc
2026-10-20 23:35:30 +02:00
committed by Prime Build
parent 8070d1c31d
commit e9e5c39772
4 changed files with 152 additions and 27 deletions
+54
View File
@@ -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
{
/// <summary>
/// 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.
/// </summary>
public static string DefaultRoot { get; } = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Temp");
/// <summary>Creates <paramref name="path"/> (which must not exist) with an Administrators + SYSTEM only DACL.</summary>
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));
}
}
}
+7 -5
View File
@@ -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)
+10 -22
View File
@@ -6,12 +6,18 @@ namespace ThreadPilot.Services
using System;
using System.IO;
/// <summary>
/// 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.
/// </summary>
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);
}
}
}
}
@@ -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<FileSystemAccessRule>()
.Select(rule => (SecurityIdentifier)rule.IdentityReference)
.ToHashSet();
var expected = new HashSet<SecurityIdentifier>
{
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<IOException>(() => 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);
}
}
}
}