security: saved rules and tweak restores no longer trust their user-writable files

Rules load from %AppData%, which any program of the user can edit, but only the
priority path checked for protected processes; CPU Sets, memory and I/O priority
and EcoQoS went straight through. The rules engine now checks the live process
(critical-process list and PPL) before applying anything, and the list gains a
few more system processes. Driver tweak restores accept only the values the
tweak itself writes, and their backup file is written atomically.
This commit is contained in:
PrimeBuild-pc
2026-10-20 23:39:39 +02:00
committed by Prime Build
parent 3a2af1c0e9
commit e8ef489c9f
4 changed files with 74 additions and 4 deletions
+37 -1
View File
@@ -26,6 +26,7 @@ namespace ThreadPilot.Services
private const string PriorityNotObservedErrorCode = "PriorityNotObserved";
private const string PriorityVerificationUnavailableErrorCode = "PriorityVerificationUnavailable";
private const string RealtimePriorityBlockedErrorCode = "RealtimePriorityBlocked";
private const string ProtectedProcessErrorCode = "PersistentRuleProtectedProcess";
private readonly IPersistentProcessRuleStore ruleStore;
private readonly IPersistentProcessRuleMatcher matcher;
@@ -34,6 +35,7 @@ namespace ThreadPilot.Services
private readonly IProcessMemoryPriorityService memoryPriorityService;
private readonly ProcessPowerRequestService? powerRequestService;
private readonly ProcessPolicyApplyGate? applyGate;
private readonly ISecurityService? securityService;
private readonly ILogger<PersistentRulesEngine> logger;
public PersistentRulesEngine(
@@ -44,7 +46,8 @@ namespace ThreadPilot.Services
IProcessMemoryPriorityService memoryPriorityService,
ILogger<PersistentRulesEngine> logger,
ProcessPowerRequestService? powerRequestService = null,
ProcessPolicyApplyGate? applyGate = null)
ProcessPolicyApplyGate? applyGate = null,
ISecurityService? securityService = null)
{
this.ruleStore = ruleStore ?? throw new ArgumentNullException(nameof(ruleStore));
this.matcher = matcher ?? throw new ArgumentNullException(nameof(matcher));
@@ -54,6 +57,7 @@ namespace ThreadPilot.Services
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
this.powerRequestService = powerRequestService;
this.applyGate = applyGate;
this.securityService = securityService;
}
public async Task<IReadOnlyList<PersistentRuleApplyResult>> ApplyMatchingRulesAsync(
@@ -99,6 +103,18 @@ namespace ThreadPilot.Services
"This saved rule has no actions to apply.");
}
if (this.IsProtectedProcess(process))
{
const string message = "Saved rules never change protected system processes.";
return result with
{
Success = false,
ErrorCode = ProtectedProcessErrorCode,
UserMessage = message,
TechnicalMessage = $"Persistent rule '{rule.Name}' ({rule.Id}) skipped for protected process {process.Name} ({process.ProcessId}).",
};
}
if (rule.ApplyAffinityOnStart)
{
if (rule.CpuSelection == null && !rule.LegacyAffinityMask.HasValue)
@@ -391,6 +407,26 @@ namespace ThreadPilot.Services
return Task.FromResult(AffinityApplyResult.Succeeded(0, process.ProcessorAffinity));
}
// Rules come from a file any program of the user can edit, so the elevated engine checks the live
// process (critical-process list + PPL) itself instead of relying on each setter to do it.
private bool IsProtectedProcess(ProcessModel process)
{
if (this.securityService == null)
{
return false;
}
try
{
using var liveProcess = Process.GetProcessById(process.ProcessId);
return this.securityService.IsProtected(liveProcess);
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
{
return false; // Exited: the apply calls below report it.
}
}
private static PersistentRuleApplyResult MarkRuleConfigurationFailure(
PersistentRuleApplyResult result,
PersistentProcessRule rule,
+6
View File
@@ -47,6 +47,12 @@ namespace ThreadPilot.Services
"MsMpEng",
"SecurityHealthService",
"audiodg",
"Registry",
"MemCompression",
"Secure System",
"LsaIso",
"fontdrvhost",
"sihost",
};
private const uint ProcessQueryLimitedInformation = 0x1000;
+6 -3
View File
@@ -830,15 +830,18 @@ namespace ThreadPilot.Services
if (changedBackups)
{
this.SaveRegistryBackups(backups);
await SaveRegistryBackupsAsync(backups);
}
foreach (var target in targets)
{
var backupKey = target.BackupKey;
// The backup file is user-writable: only restore a value this tweak itself could have written.
var desiredValue = enabled
? enabledValue
: restoreOriginalWhenDisabled && backups.TryGetValue(backupKey, out var backup)
&& (backup.Value == enabledValue || backup.Value == disabledValue)
? backup.Value
: disabledValue;
using var key = Registry.LocalMachine.OpenSubKey(target.Path, writable: true);
@@ -917,10 +920,10 @@ namespace ThreadPilot.Services
}
}
private void SaveRegistryBackups(Dictionary<string, RegistryValueBackup> backups)
private static async Task SaveRegistryBackupsAsync(Dictionary<string, RegistryValueBackup> backups)
{
StoragePaths.EnsureAppDataDirectories();
File.WriteAllText(
await AtomicFileWriter.WriteAllTextAsync(
StoragePaths.DeviceTweakBackupsFilePath,
JsonSerializer.Serialize(backups, new JsonSerializerOptions { WriteIndented = true }));
}
@@ -521,6 +521,31 @@ namespace ThreadPilot.Core.Tests
affinity.Verify(s => s.ApplyAsync(process, 3), Times.Once);
}
[Fact]
public async Task ApplyMatchingRulesAsync_ProtectedProcess_ChangesNothing()
{
var rule = CreateRule(legacyAffinityMask: 3, applyAffinity: true);
var affinity = new Mock<IAffinityApplyService>(MockBehavior.Strict);
var security = new Mock<ISecurityService>(MockBehavior.Strict);
security.Setup(s => s.IsProtected(It.IsAny<System.Diagnostics.Process>())).Returns(true);
var engine = new PersistentRulesEngine(
new FakePersistentProcessRuleStore([rule]),
new PersistentProcessRuleMatcher(),
affinity.Object,
new Mock<IProcessService>(MockBehavior.Strict).Object,
new Mock<IProcessMemoryPriorityService>(MockBehavior.Strict).Object,
Microsoft.Extensions.Logging.Abstractions.NullLogger<PersistentRulesEngine>.Instance,
securityService: security.Object);
var process = CreateProcess();
process.ProcessId = Environment.ProcessId;
var result = Assert.Single(await engine.ApplyMatchingRulesAsync(process));
Assert.False(result.Success);
Assert.Equal("PersistentRuleProtectedProcess", result.ErrorCode);
security.Verify(s => s.IsProtected(It.IsAny<System.Diagnostics.Process>()), Times.Once);
}
private static PersistentRulesEngine CreateEngine(
IReadOnlyList<PersistentProcessRule> rules,
IAffinityApplyService affinityApplyService,