LD-Uninstaller/src-csharp/LDUninstaller.Core/Startup/StartupManager.cs

437 lines
19 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.ServiceProcess;
using System.Xml.Linq;
using LDUninstaller.Core.Models;
using Microsoft.Win32;
namespace LDUninstaller.Core.Startup
{
public class StartupManager
{
private static readonly HashSet<string> CriticalSystemServices = new(StringComparer.OrdinalIgnoreCase)
{
"spooler", "searchindexer", "windefend", "securityhealthservice", "wuauserv",
"rpcss", "dcomlaunch", "eventlog", "plugplay", "dhcp", "dnscache", "cryptsvc",
"lanmanworkstation", "lanmanserver", "bfe", "mpssvc", "audioendpointbuilder", "audiosrv",
"samss", "lsass", "termservice", "w32time", "bits", "vss", "profsvc", "gpsvc"
};
public static List<StartupEntry> GetAllStartupEntries()
{
var list = new List<StartupEntry>();
// 1. Registry HKCU Run & RunOnce (F8)
ScanRegistryRun(Registry.CurrentUser, @"Software\Microsoft\Windows\CurrentVersion\Run", StartupType.RegistryRun, list, isHklm: false, isWow64: false);
ScanRegistryRun(Registry.CurrentUser, @"Software\Microsoft\Windows\CurrentVersion\RunOnce", StartupType.RegistryRunOnce, list, isHklm: false, isWow64: false);
// 2. Registry HKLM Run & RunOnce (F8)
ScanRegistryRun(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", StartupType.RegistryRun, list, isHklm: true, isWow64: false);
ScanRegistryRun(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce", StartupType.RegistryRunOnce, list, isHklm: true, isWow64: false);
// 3. Registry HKLM 32-bit (Wow6432Node)
if (Environment.Is64BitOperatingSystem)
{
try
{
using var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
using var key = baseKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
if (key != null)
{
foreach (var name in key.GetValueNames())
{
var val = key.GetValue(name)?.ToString() ?? string.Empty;
list.Add(new StartupEntry
{
Name = name,
Command = val,
Type = StartupType.RegistryRun,
Location = @"HKLM\Software\Wow6432Node\...\Run",
IsEnabled = CheckStartupApproved(name, isHklm: true, isWow64: true)
});
}
}
}
catch { }
}
// 4. Startup Folders
ScanFolder(Environment.GetFolderPath(Environment.SpecialFolder.Startup), "Kullanıcı Başlangıç Klasörü", list, isCommon: false);
ScanFolder(Environment.GetFolderPath(Environment.SpecialFolder.CommonStartup), "Tüm Kullanıcılar Başlangıç Klasörü", list, isCommon: true);
// 5. Task Scheduler Logon Tasks (F8)
ScanLogonScheduledTasks(list);
// 6. 3rd-Party Services (Automatic/Disabled) (B20: filters critical OS services)
ScanServices(list);
return list;
}
private static void ScanRegistryRun(RegistryKey root, string subKey, StartupType type, List<StartupEntry> list, bool isHklm, bool isWow64)
{
try
{
using var key = root.OpenSubKey(subKey);
if (key == null) return;
foreach (var name in key.GetValueNames())
{
string cmd = key.GetValue(name)?.ToString() ?? string.Empty;
list.Add(new StartupEntry
{
Name = name,
Command = cmd,
Type = type,
Location = $"{root.Name}\\{subKey}",
IsEnabled = CheckStartupApproved(name, isHklm, isWow64)
});
}
}
catch { }
}
private static void ScanFolder(string path, string locationDesc, List<StartupEntry> list, bool isCommon)
{
if (string.IsNullOrWhiteSpace(path) || !Directory.Exists(path)) return;
try
{
foreach (var file in Directory.GetFiles(path))
{
string ext = Path.GetExtension(file).ToLowerInvariant();
if (ext != ".lnk" && ext != ".url" && ext != ".disabled") continue;
string fileName = Path.GetFileName(file);
string cleanFileName = fileName.EndsWith(".disabled", StringComparison.OrdinalIgnoreCase)
? fileName.Substring(0, fileName.Length - ".disabled".Length)
: fileName;
string displayName = Path.GetFileNameWithoutExtension(cleanFileName);
bool isEnabled = !ext.Equals(".disabled", StringComparison.OrdinalIgnoreCase);
// Check StartupApproved using clean original filename (B10)
if (isEnabled)
{
isEnabled = CheckStartupFolderApproved(cleanFileName, isCommon);
}
list.Add(new StartupEntry
{
Name = displayName,
Command = file,
Type = StartupType.StartupFolder,
Location = locationDesc,
IsEnabled = isEnabled
});
}
}
catch { }
}
private static void ScanLogonScheduledTasks(List<StartupEntry> list)
{
try
{
string tasksDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "System32", "Tasks");
if (!Directory.Exists(tasksDir)) return;
foreach (var file in Directory.GetFiles(tasksDir, "*", SearchOption.AllDirectories))
{
// Exclude standard Microsoft Windows internal tasks
if (file.Contains(@"\Tasks\Microsoft\Windows", StringComparison.OrdinalIgnoreCase))
continue;
try
{
string xml = File.ReadAllText(file);
if (xml.Contains("<LogonTrigger", StringComparison.OrdinalIgnoreCase) || xml.Contains("<BootTrigger", StringComparison.OrdinalIgnoreCase))
{
string rel = file.Substring(tasksDir.Length).TrimStart('\\');
string taskName = Path.GetFileName(file);
// Extract command if possible
string execPath = "";
var doc = XDocument.Parse(xml);
var execNode = doc.Descendants().FirstOrDefault(d => d.Name.LocalName == "Command");
if (execNode != null)
{
execPath = execNode.Value;
}
bool isEnabled = !xml.Contains("<Enabled>false</Enabled>", StringComparison.OrdinalIgnoreCase);
list.Add(new StartupEntry
{
Name = taskName,
Command = !string.IsNullOrEmpty(execPath) ? execPath : rel,
Type = StartupType.TaskScheduler,
Location = $@"Görev: \{rel}",
IsEnabled = isEnabled
});
}
}
catch { }
}
}
catch { }
}
private static void ScanServices(List<StartupEntry> list)
{
try
{
var services = ServiceController.GetServices();
foreach (var sc in services)
{
try
{
// B20: Filter critical system services
if (CriticalSystemServices.Contains(sc.ServiceName))
continue;
using var key = Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\{sc.ServiceName}");
if (key != null)
{
int startType = (int)(key.GetValue("Start") ?? 3);
string imgPath = key.GetValue("ImagePath")?.ToString() ?? "";
string imgLower = imgPath.ToLowerInvariant();
// Exclude internal OS binaries
if (!imgLower.Contains(@"\windows\system32\svchost.exe") &&
!imgLower.Contains(@"\windows\system32\services.exe") &&
!imgLower.Contains(@"\windows\system32\lsass.exe"))
{
if (startType == 2 || startType == 4)
{
list.Add(new StartupEntry
{
Name = sc.DisplayName,
ServiceName = sc.ServiceName,
Command = imgPath,
Type = StartupType.Service,
Location = "Windows Servisi",
IsEnabled = (startType == 2)
});
}
}
}
}
catch { }
}
}
catch { }
}
public static bool CheckStartupApproved(string entryName, bool isHklm = false, bool isWow64 = false)
{
try
{
string approvedSub = isWow64 ? @"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run32"
: @"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run";
using (var key = Registry.CurrentUser.OpenSubKey(approvedSub))
{
if (key?.GetValue(entryName) is byte[] data && data.Length > 0)
{
return data[0] == 0x02;
}
}
if (isHklm)
{
using var hklmKey = Registry.LocalMachine.OpenSubKey(approvedSub);
if (hklmKey?.GetValue(entryName) is byte[] data && data.Length > 0)
{
return data[0] == 0x02;
}
}
}
catch { }
return true;
}
public static bool CheckStartupFolderApproved(string fileName, bool isCommon)
{
try
{
const string approvedSub = @"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\StartupFolder";
using (var key = Registry.CurrentUser.OpenSubKey(approvedSub))
{
if (key?.GetValue(fileName) is byte[] data && data.Length > 0)
{
return data[0] == 0x02;
}
}
if (isCommon)
{
using var hklmKey = Registry.LocalMachine.OpenSubKey(approvedSub);
if (hklmKey?.GetValue(fileName) is byte[] data && data.Length > 0)
{
return data[0] == 0x02;
}
}
}
catch { }
return true;
}
public static bool ToggleStartupEntry(StartupEntry entry, bool enable)
{
try
{
byte[] binaryData = enable
? new byte[] { 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
: new byte[] { 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
if (entry.Type == StartupType.RegistryRun || entry.Type == StartupType.RegistryRunOnce)
{
bool isWow64 = entry.Location.Contains("Wow6432Node", StringComparison.OrdinalIgnoreCase);
bool isHklm = entry.Location.Contains("HKEY_LOCAL_MACHINE", StringComparison.OrdinalIgnoreCase) || entry.Location.Contains("HKLM", StringComparison.OrdinalIgnoreCase);
string approvedSub = isWow64 ? @"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run32"
: @"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run";
using (var key = Registry.CurrentUser.CreateSubKey(approvedSub))
{
key?.SetValue(entry.Name, binaryData, RegistryValueKind.Binary);
}
if (isHklm)
{
try
{
using var key = Registry.LocalMachine.CreateSubKey(approvedSub);
key?.SetValue(entry.Name, binaryData, RegistryValueKind.Binary);
}
catch { }
}
entry.IsEnabled = enable;
return true;
}
else if (entry.Type == StartupType.StartupFolder)
{
// B10: Manage clean filename and preserve StartupApproved registration
string fileName = Path.GetFileName(entry.Command);
string cleanFileName = fileName.EndsWith(".disabled", StringComparison.OrdinalIgnoreCase)
? fileName.Substring(0, fileName.Length - ".disabled".Length)
: fileName;
bool isCommon = entry.Location.Contains("Tüm Kullanıcılar", StringComparison.OrdinalIgnoreCase) || entry.Location.Contains("All Users", StringComparison.OrdinalIgnoreCase);
const string approvedFolderSub = @"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\StartupFolder";
using (var key = Registry.CurrentUser.CreateSubKey(approvedFolderSub))
{
key?.SetValue(cleanFileName, binaryData, RegistryValueKind.Binary);
}
if (isCommon)
{
try
{
using var key = Registry.LocalMachine.CreateSubKey(approvedFolderSub);
key?.SetValue(cleanFileName, binaryData, RegistryValueKind.Binary);
}
catch { }
}
// Physical file rename
string dir = Path.GetDirectoryName(entry.Command) ?? "";
string normalPath = Path.Combine(dir, cleanFileName);
string disabledPath = normalPath + ".disabled";
if (!enable && File.Exists(normalPath))
{
File.Move(normalPath, disabledPath, true);
entry.Command = disabledPath;
}
else if (enable && File.Exists(disabledPath))
{
File.Move(disabledPath, normalPath, true);
entry.Command = normalPath;
}
entry.IsEnabled = enable;
return true;
}
else if (entry.Type == StartupType.TaskScheduler)
{
// Toggle scheduled task via schtasks /change
string taskName = entry.Location.Replace("Görev: ", "").Trim();
string state = enable ? "/ENABLE" : "/DISABLE";
var psi = new ProcessStartInfo("schtasks.exe", $"/Change /TN \"{taskName}\" {state}")
{
CreateNoWindow = true,
UseShellExecute = false
};
using var p = Process.Start(psi);
p?.WaitForExit(3000);
entry.IsEnabled = enable;
return true;
}
else if (entry.Type == StartupType.Service)
{
string svcName = !string.IsNullOrEmpty(entry.ServiceName) ? entry.ServiceName : entry.Name;
// B20: Never allow stopping critical Windows services
if (CriticalSystemServices.Contains(svcName))
{
return false;
}
int targetStartType = enable ? 2 : 4; // 2 = Auto, 4 = Disabled
try
{
using var key = Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\{svcName}", true);
if (key != null)
{
key.SetValue("Start", targetStartType, RegistryValueKind.DWord);
}
}
catch { }
try
{
string mode = enable ? "auto" : "disabled";
var psi = new ProcessStartInfo("sc.exe", $"config \"{svcName}\" start= {mode}")
{
CreateNoWindow = true,
UseShellExecute = false
};
using var p = Process.Start(psi);
p?.WaitForExit(3000);
}
catch { }
try
{
using var sc = new ServiceController(svcName);
if (!enable && sc.Status == ServiceControllerStatus.Running)
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(3));
}
else if (enable && sc.Status == ServiceControllerStatus.Stopped)
{
sc.Start();
}
}
catch { }
entry.IsEnabled = enable;
return true;
}
}
catch (Exception ex)
{
Debug.WriteLine($"ToggleStartupEntry error: {ex.Message}");
}
return false;
}
}
}