diff --git a/Services/PersistentRulesEngine.cs b/Services/PersistentRulesEngine.cs index f275ea3..228936e 100644 --- a/Services/PersistentRulesEngine.cs +++ b/Services/PersistentRulesEngine.cs @@ -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 logger; public PersistentRulesEngine( @@ -44,7 +46,8 @@ namespace ThreadPilot.Services IProcessMemoryPriorityService memoryPriorityService, ILogger 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> 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, diff --git a/Services/SecurityService.cs b/Services/SecurityService.cs index cd4f777..9985d99 100644 --- a/Services/SecurityService.cs +++ b/Services/SecurityService.cs @@ -47,6 +47,12 @@ namespace ThreadPilot.Services "MsMpEng", "SecurityHealthService", "audiodg", + "Registry", + "MemCompression", + "Secure System", + "LsaIso", + "fontdrvhost", + "sihost", }; private const uint ProcessQueryLimitedInformation = 0x1000; diff --git a/Services/SystemTweaksService.cs b/Services/SystemTweaksService.cs index a616d21..6119170 100644 --- a/Services/SystemTweaksService.cs +++ b/Services/SystemTweaksService.cs @@ -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 backups) + private static async Task SaveRegistryBackupsAsync(Dictionary backups) { StoragePaths.EnsureAppDataDirectories(); - File.WriteAllText( + await AtomicFileWriter.WriteAllTextAsync( StoragePaths.DeviceTweakBackupsFilePath, JsonSerializer.Serialize(backups, new JsonSerializerOptions { WriteIndented = true })); } diff --git a/Tests/ThreadPilot.Core.Tests/PersistentRulesEngineTests.cs b/Tests/ThreadPilot.Core.Tests/PersistentRulesEngineTests.cs index 774d9bd..88ee4d8 100644 --- a/Tests/ThreadPilot.Core.Tests/PersistentRulesEngineTests.cs +++ b/Tests/ThreadPilot.Core.Tests/PersistentRulesEngineTests.cs @@ -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(MockBehavior.Strict); + var security = new Mock(MockBehavior.Strict); + security.Setup(s => s.IsProtected(It.IsAny())).Returns(true); + var engine = new PersistentRulesEngine( + new FakePersistentProcessRuleStore([rule]), + new PersistentProcessRuleMatcher(), + affinity.Object, + new Mock(MockBehavior.Strict).Object, + new Mock(MockBehavior.Strict).Object, + Microsoft.Extensions.Logging.Abstractions.NullLogger.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()), Times.Once); + } + private static PersistentRulesEngine CreateEngine( IReadOnlyList rules, IAffinityApplyService affinityApplyService,