Skip to content

Portable Tool for an Ideal Windows Setup

add FileDirectoryHelper for centralized file and directory management fix dmwappushservice registry types, diagsvc privileges and hosts restore logic fix TrustedInstaller handle leaks and service wait loops fix SIDs, privilege revocation and API checks in TakingOwnership

Greedeksee98f13b7f81
diff --git a/.Source/GTweak/Core/ViewModel/AddonsViewModel.cs b/.Source/GTweak/Core/ViewModel/AddonsViewModel.cs
index 152a1b28..9ff3b800 100644
--- a/.Source/GTweak/Core/ViewModel/AddonsViewModel.cs
+++ b/.Source/GTweak/Core/ViewModel/AddonsViewModel.cs
@@ -94,7 +94,7 @@ namespace GTweak.Core.ViewModel
break;
}
- Task.Run(() => { CommandExecutor.RunCommandShow(fileName, CommandExecutor.CleanCommand(arguments), addon.RequiresElevation); });
+ Task.Run(() => { CommandExecutor.RunProcessVisible(fileName, CommandExecutor.CleanCommand(arguments), addon.RequiresElevation); });
}
catch (Exception ex) { ErrorLogger.LogDebug(ex); }
}
diff --git a/.Source/GTweak/GTweak.csproj b/.Source/GTweak/GTweak.csproj
index c1d5e936..60876249 100644
--- a/.Source/GTweak/GTweak.csproj
+++ b/.Source/GTweak/GTweak.csproj
@@ -225,6 +225,7 @@
<Compile Include="Modules\Configuration\StorageTypeIdentifier.cs" />
<Compile Include="Modules\Configuration\HardwareData.cs" />
<Compile Include="Modules\Extensions\PostActionExtensions.cs" />
+ <Compile Include="Modules\Helpers\FileDirectoryHelper.cs" />
<Compile Include="Modules\Helpers\UnlockHandleHelper.cs" />
<Compile Include="Modules\Extensions\WindowExtensions.cs" />
<Compile Include="Modules\Maintenance\MemoryCleaner.cs" />
diff --git a/.Source/GTweak/Modules/Helpers/CommandExecutor.cs b/.Source/GTweak/Modules/Helpers/CommandExecutor.cs
index 3041cd10..652cd648 100644
--- a/.Source/GTweak/Modules/Helpers/CommandExecutor.cs
+++ b/.Source/GTweak/Modules/Helpers/CommandExecutor.cs
@@ -11,7 +11,7 @@ namespace GTweak.Modules.Helpers
{
internal static class CommandExecutor
{
- internal static int PID = 0;
+ internal static volatile int PID = 0;
internal static async Task<string> GetCommandOutput(string command, bool isPowerShell = true)
{
@@ -51,51 +51,44 @@ namespace GTweak.Modules.Helpers
? $"\"{PathTargets.Executable.PowerShell}\" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy Bypass -Command \"{command.Replace("\"", "`\"")}\""
: $"\"{PathTargets.Executable.CommandShell}\" {command}");
- internal static async void RunCommand(string command, bool isPowerShell = false)
+ internal static void RunCommand(string command, bool isPowerShell = false)
{
- await Task.Run(() =>
+ ProcessStartInfo startInfo = new ProcessStartInfo()
{
- ProcessStartInfo startInfo = new ProcessStartInfo()
- {
- FileName = isPowerShell ? PathTargets.Executable.PowerShell : PathTargets.Executable.CommandShell,
- Arguments = isPowerShell ? $"-NoLogo -NonInteractive -NoProfile -ExecutionPolicy Bypass -Command \"{command}\"" : command,
- WindowStyle = ProcessWindowStyle.Hidden,
- UseShellExecute = true,
- Verb = "runas",
- CreateNoWindow = true
- };
-
- using Process process = new Process { StartInfo = startInfo };
- try { process.Start(); }
- catch (Exception ex) { ErrorLogger.LogDebug(ex); }
- }).ConfigureAwait(false);
+ FileName = isPowerShell ? PathTargets.Executable.PowerShell : PathTargets.Executable.CommandShell,
+ Arguments = isPowerShell ? $"-NoLogo -NonInteractive -NoProfile -ExecutionPolicy Bypass -Command \"{command}\"" : command,
+ WindowStyle = ProcessWindowStyle.Hidden,
+ UseShellExecute = true,
+ Verb = "runas",
+ CreateNoWindow = true
+ };
+
+ using Process process = new Process { StartInfo = startInfo };
+ try { process.Start(); }
+ catch (Exception ex) { ErrorLogger.LogDebug(ex); }
}
- internal static async void RunCommandShow(string fileName, string arguments = "", bool isElevationRequired = false)
+ internal static async void RunProcessVisible(string fileName, string arguments = "", bool isElevationRequired = false)
{
- await Task.Run(() =>
+ if (isElevationRequired)
{
- if (isElevationRequired)
- {
- TrustedInstaller.CreateProcessAsTrustedInstaller(PID, $"{fileName} {arguments}", true);
- }
- else
- {
- ProcessStartInfo startInfo = new ProcessStartInfo()
- {
- FileName = fileName,
- Arguments = arguments,
- WindowStyle = ProcessWindowStyle.Normal,
- UseShellExecute = true,
- Verb = "runas",
- CreateNoWindow = false
- };
-
- using Process process = new Process() { StartInfo = startInfo };
- try { process.Start(); }
- catch (Exception ex) { ErrorLogger.LogDebug(ex); }
- }
- }).ConfigureAwait(false);
+ TrustedInstaller.CreateProcessAsTrustedInstaller(PID, $"{fileName} {arguments}", true);
+ return;
+ }
+
+ ProcessStartInfo startInfo = new ProcessStartInfo()
+ {
+ FileName = fileName,
+ Arguments = arguments,
+ WindowStyle = ProcessWindowStyle.Normal,
+ UseShellExecute = true,
+ Verb = "runas",
+ CreateNoWindow = false
+ };
+
+ using Process process = new Process { StartInfo = startInfo };
+ try { process.Start(); }
+ catch (Exception ex) { ErrorLogger.LogDebug(ex); }
}
internal static async Task InvokeRunCommand(string command, bool isPowerShell = false)
@@ -120,6 +113,23 @@ namespace GTweak.Modules.Helpers
catch (Exception ex) { ErrorLogger.LogDebug(ex); }
}
+ internal static void RunEncodedPowerShell(string command)
+ {
+ try
+ {
+ Process comandoAEjecutar = new Process();
+ comandoAEjecutar.StartInfo.FileName = PathTargets.Executable.PowerShell;
+ comandoAEjecutar.StartInfo.Arguments = $"-NoLogo -NonInteractive -NoProfile -ExecutionPolicy Bypass -EncodedCommand \"{Convert.ToBase64String(Encoding.Unicode.GetBytes(command))}\"";
+ comandoAEjecutar.StartInfo.UseShellExecute = false;
+ comandoAEjecutar.StartInfo.RedirectStandardOutput = true;
+ comandoAEjecutar.StartInfo.RedirectStandardError = true;
+ comandoAEjecutar.StartInfo.CreateNoWindow = true;
+ comandoAEjecutar.Start();
+ comandoAEjecutar.StandardOutput.ReadToEnd();
+ }
+ catch (Exception ex) { ErrorLogger.LogDebug(ex); }
+ }
+
internal static Task WaitForExitAsync(this Process process)
{
if (!process.HasExited)
diff --git a/.Source/GTweak/Modules/Helpers/FileDirectoryHelper.cs b/.Source/GTweak/Modules/Helpers/FileDirectoryHelper.cs
new file mode 100644
index 00000000..c975d400
--- /dev/null
+++ b/.Source/GTweak/Modules/Helpers/FileDirectoryHelper.cs
@@ -0,0 +1,150 @@
+using System;
+using System.IO;
+using System.Threading;
+using GTweak.Modules.Common;
+
+namespace GTweak.Modules.Helpers
+{
+ internal static class FileDirectoryHelper
+ {
+ internal static void CreateDirectory(params string[] paths)
+ {
+ if (paths != null && paths.Length != 0)
+ {
+ foreach (string path in paths)
+ {
+ if (string.IsNullOrWhiteSpace(path) || Directory.Exists(path))
+ {
+ continue;
+ }
+
+ try { Directory.CreateDirectory(path); }
+ catch (Exception ex) { ErrorLogger.LogDebug(ex); }
+ }
+ }
+ }
+
+ internal static void DeleteDirectory(params string[] paths)
+ {
+ if (paths != null && paths.Length != 0)
+ {
+ foreach (string path in paths)
+ {
+ if (string.IsNullOrWhiteSpace(path) || !Directory.Exists(path))
+ {
+ continue;
+ }
+
+ try { Directory.Delete(path, true); }
+ catch (Exception ex) { ErrorLogger.LogDebug(ex); }
+ }
+ }
+ }
+
+ internal static void ForceDeleteDirectory(params string[] paths)
+ {
+ if (paths != null && paths.Length != 0)
+ {
+ foreach (string path in paths)
+ {
+ if (string.IsNullOrWhiteSpace(path) || !Directory.Exists(path))
+ {
+ continue;
+ }
+
+ UnlockHandleHelper.UnlockDirectory(path);
+
+ CommandExecutor.RunCommandAsTrustedInstaller($@"/c takeown /f ""{path}"" /r /d y && icacls ""{path}"" /inheritance:r && icacls ""{path}"" /remove *S-1-5-32-544 *S-1-5-11 *S-1-5-32-545 *S-1-5-18 && icacls ""{path}"" /grant ""{Environment.UserName}"":F /t && rd /s /q ""{path}""");
+
+ for (int i = 0; Directory.Exists(path) && i < 5; i++)
+ {
+ try
+ {
+ Directory.Delete(path, true);
+ }
+ catch (Exception ex) { ErrorLogger.LogDebug(ex); }
+
+ if (Directory.Exists(path))
+ {
+ CommandExecutor.RunCommand($"Remove-Item -LiteralPath '{path}' -Recurse -Force", true);
+ Thread.Sleep(300);
+ }
+ }
+ }
+ }
+ }
+
+ internal static void ForceDeleteDirectoryContents(params string[] directories)
+ {
+ if (directories != null && directories.Length != 0)
+ {
+ foreach (string directory in directories)
+ {
+ if (string.IsNullOrWhiteSpace(directory) || !Directory.Exists(directory))
+ {
+ continue;
+ }
+
+ try
+ {
+ UnlockHandleHelper.UnlockDirectory(directory);
+
+ foreach (string file in Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories))
+ {
+ ForceDeleteFile(file);
+ }
+ }
+ catch (Exception ex) { ErrorLogger.LogDebug(ex); }
+ }
+ }
+ }
+
+ internal static void DeleteFile(params string[] paths)
+ {
+ if (paths != null && paths.Length != 0)
+ {
+ foreach (string path in paths)
+ {
+ if (!File.Exists(path))
+ {
+ continue;
+ }
+
+ try { File.Delete(path); }
+ catch (Exception ex) { ErrorLogger.LogDebug(ex); }
+ }
+ }
+ }
+
+ internal static void ForceDeleteFile(params string[] paths)
+ {
+ if (paths != null && paths.Length != 0)
+ {
+ foreach (string path in paths)
+ {
+ if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
+ {
+ continue;
+ }
+
+ CommandExecutor.RunCommandAsTrustedInstaller($@"/c takeown /f ""{path}"" /a & icacls ""{path}"" /inheritance:r /remove *S-1-5-32-544 *S-1-5-11 *S-1-5-32-545 *S-1-5-18 & icacls ""{path}"" /grant ""{Environment.UserName}"":F & del /f /q ""{path}""");
+
+ for (int i = 0; File.Exists(path) && i < 5; i++)
+ {
+ try
+ {
+ File.Delete(path);
+ }
+ catch (Exception ex) { ErrorLogger.LogDebug(ex); }
+
+ if (File.Exists(path))
+ {
+ CommandExecutor.RunCommand($"Remove-Item -LiteralPath '{path}' -Force", true);
+ Thread.Sleep(300);
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/.Source/GTweak/Modules/Helpers/TakingOwnership.cs b/.Source/GTweak/Modules/Helpers/TakingOwnership.cs
index 59208660..d3898b11 100644
--- a/.Source/GTweak/Modules/Helpers/TakingOwnership.cs
+++ b/.Source/GTweak/Modules/Helpers/TakingOwnership.cs
@@ -114,8 +114,7 @@ namespace GTweak.Modules.Helpers
private const int SECURITY_BUILTIN_DOMAIN_RID = 0x00000020;
private const int DOMAIN_ALIAS_RID_ADMINS = 0x00000220;
private const int DOMAIN_ALIAS_RID_USERS = 0x00000221;
- private const int DOMAIN_ALIAS_RID_TRUSTED_INSTALLER = 0x00000222;
- private const int DOMAIN_ALIAS_RID_WD = 0x00000223;
+
private const int TOKEN_QUERY = 8;
private const int SE_PRIVILEGE_ENABLED = 2;
@@ -190,14 +189,12 @@ namespace GTweak.Modules.Helpers
IntPtr sidAdmin = IntPtr.Zero;
IntPtr sidUsers = IntPtr.Zero;
IntPtr sidTrustedInstaller = IntPtr.Zero;
- IntPtr sidWD = IntPtr.Zero;
AllocateAndInitializeSid(ref sidNTAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, ref sidAdmin);
AllocateAndInitializeSid(ref sidNTAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, ref sidUsers);
- AllocateAndInitializeSid(ref sidNTAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_TRUSTED_INSTALLER, 0, 0, 0, 0, 0, 0, ref sidTrustedInstaller);
- AllocateAndInitializeSid(ref sidNTAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_WD, 0, 0, 0, 0, 0, 0, ref sidWD);
+ AllocateAndInitializeSid(ref sidNTAuthority, 6, 80, 956008885, 3418522649, 1831038044, 1853292631, 2271478464, 0, 0, ref sidTrustedInstaller);
- EXPLICIT_ACCESS[] explicitAccesss = new EXPLICIT_ACCESS[4];
+ EXPLICIT_ACCESS[] explicitAccesss = new EXPLICIT_ACCESS[3];
explicitAccesss[0].grfAccessPermissions = ACCESS_MASK.GENERIC_ALL;
explicitAccesss[0].grfAccessMode = ACCESS_MODE.SET_ACCESS;
@@ -220,29 +217,19 @@ namespace GTweak.Modules.Helpers
explicitAccesss[2].Trustee.TrusteeType = TRUSTEE_TYPE.TRUSTEE_IS_GROUP;
explicitAccesss[2].Trustee.ptstrName = sidTrustedInstaller;
- explicitAccesss[3].grfAccessPermissions = ACCESS_MASK.GENERIC_ALL;
- explicitAccesss[3].grfAccessMode = ACCESS_MODE.DENY_ACCESS;
- explicitAccesss[3].grfInheritance = NO_INHERITANCE;
- explicitAccesss[3].Trustee.TrusteeForm = TRUSTEE_FORM.TRUSTEE_IS_SID;
- explicitAccesss[3].Trustee.TrusteeType = TRUSTEE_TYPE.TRUSTEE_IS_GROUP;
- explicitAccesss[3].Trustee.ptstrName = sidWD;
-
IntPtr acl = IntPtr.Zero;
- SetEntriesInAcl(4, ref explicitAccesss[0], (IntPtr)0, ref acl);
+ SetEntriesInAcl(3, ref explicitAccesss[0], (IntPtr)0, ref acl);
static void setPrivilege(string privilege, bool allow)
{
TOKEN_PRIVILEGES tokenPrivileges = new TOKEN_PRIVILEGES();
OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out IntPtr token);
- if (allow)
- {
- LookupPrivilegeValueA(null, privilege, out LUID luid);
- tokenPrivileges.PrivilegeCount = 1;
- tokenPrivileges.Privileges = new LUID_AND_ATTRIBUTES[1];
- tokenPrivileges.Privileges[0].Luid = luid;
- tokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
- }
+ LookupPrivilegeValueA(null, privilege, out LUID luid);
+ tokenPrivileges.PrivilegeCount = 1;
+ tokenPrivileges.Privileges = new LUID_AND_ATTRIBUTES[1];
+ tokenPrivileges.Privileges[0].Luid = luid;
+ tokenPrivileges.Privileges[0].Attributes = (uint)(allow ? SE_PRIVILEGE_ENABLED : 0);
AdjustTokenPrivileges(token, false, ref tokenPrivileges, 0, IntPtr.Zero, IntPtr.Zero);
CloseHandle(token);
@@ -269,7 +256,6 @@ namespace GTweak.Modules.Helpers
FreeSid(sidAdmin);
FreeSid(sidUsers);
FreeSid(sidTrustedInstaller);
- FreeSid(sidWD);
LocalFree(acl);
}
}
diff --git a/.Source/GTweak/Modules/Helpers/TrustedInstaller.cs b/.Source/GTweak/Modules/Helpers/TrustedInstaller.cs
index 0d4905d5..6f4b9a7e 100644
--- a/.Source/GTweak/Modules/Helpers/TrustedInstaller.cs
+++ b/.Source/GTweak/Modules/Helpers/TrustedInstaller.cs
@@ -248,16 +248,27 @@ namespace GTweak.Modules.Helpers
try
{
int currentSession = Process.GetCurrentProcess().SessionId;
- Process[] winlogons = Process.GetProcessesByName("winlogon");
-
- Process targetWinlogon = winlogons.FirstOrDefault(p => p.SessionId == currentSession) ?? winlogons.FirstOrDefault();
+ int targetWinlogonPid;
- if (targetWinlogon == null)
+ Process[] winlogons = Process.GetProcessesByName("winlogon");
+ try
{
- return false;
+ Process targetWinlogon = winlogons.FirstOrDefault(p => p.SessionId == currentSession) ?? winlogons.FirstOrDefault();
+ if (targetWinlogon == null)
+ {
+ return false;
+ }
+ targetWinlogonPid = targetWinlogon.Id;
+ }
+ finally
+ {
+ foreach (Process p in winlogons)
+ {
+ p.Dispose();
+ }
}
- winlogonHandle = OpenProcess(ProcessAccessFlags.QueryLimitedInformation, false, targetWinlogon.Id);
+ winlogonHandle = OpenProcess(ProcessAccessFlags.QueryLimitedInformation, false, targetWinlogonPid);
if (winlogonHandle == IntPtr.Zero)
{
return false;
@@ -313,8 +324,16 @@ namespace GTweak.Modules.Helpers
}
SERVICE_STATUS_PROCESS statusBuffer = new SERVICE_STATUS_PROCESS();
+ Stopwatch timeout = Stopwatch.StartNew();
+ const int maxWaitMs = 30000;
+
while (QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO, ref statusBuffer, (uint)Marshal.SizeOf(statusBuffer), out _))
{
+ if (timeout.ElapsedMilliseconds > maxWaitMs)
+ {
+ break;
+ }
+
if (statusBuffer.dwCurrentState == (uint)ServiceControllerStatus.Stopped)
{
if (!StartService(hService, 0, IntPtr.Zero))
@@ -326,7 +345,8 @@ namespace GTweak.Modules.Helpers
}
if (statusBuffer.dwCurrentState == (uint)ServiceControllerStatus.StartPending || statusBuffer.dwCurrentState == (uint)ServiceControllerStatus.StopPending)
{
- System.Threading.Thread.Sleep((int)statusBuffer.dwWaitHint);
+ int waitTime = Math.Max(250, Math.Min((int)statusBuffer.dwWaitHint, 10000));
+ System.Threading.Thread.Sleep(waitTime);
continue;
}
if (statusBuffer.dwCurrentState == (uint)ServiceControllerStatus.Running)
@@ -348,11 +368,13 @@ namespace GTweak.Modules.Helpers
CommandExecutor.PID = pid;
return;
}
+
+ System.Threading.Thread.Sleep(250);
}
CloseServiceHandle(hService);
CloseServiceHandle(hSCManager);
- throw new Win32Exception("QueryServiceStatusEx failed: " + Marshal.GetLastWin32Error());
+ throw new Win32Exception("TrustedInstaller service failed to start within timeout");
}
internal static void CreateProcessAsTrustedInstaller(int parentProcessId, string binaryPath, bool showWindow = false)
diff --git a/.Source/GTweak/Modules/Helpers/UnlockHandleHelper.cs b/.Source/GTweak/Modules/Helpers/UnlockHandleHelper.cs
index 0ca86aec..e36c66d4 100644
--- a/.Source/GTweak/Modules/Helpers/UnlockHandleHelper.cs
+++ b/.Source/GTweak/Modules/Helpers/UnlockHandleHelper.cs
@@ -75,23 +75,25 @@ namespace GTweak.Modules.Helpers
{
try
{
- Process process = Process.GetProcessById(pid);
- if (process.HasExited)
+ using (Process process = Process.GetProcessById(pid))
{
- continue;
- }
-
- try
- {
- process.CloseMainWindow();
- process.WaitForExit(1000);
- }
- catch (Exception ex) { ErrorLogger.LogDebug(ex); }
-
- if (!process.HasExited)
- {
- process.Kill();
- process.WaitForExit(2000);
+ if (process.HasExited)
+ {
+ continue;
+ }
+
+ try
+ {
+ process.CloseMainWindow();
+ process.WaitForExit(1000);
+ }
+ catch (Exception ex) { ErrorLogger.LogDebug(ex); }
+
+ if (!process.HasExited)
+ {
+ process.Kill();
+ process.WaitForExit(2000);
+ }
}
}
catch (Exception ex) { ErrorLogger.LogDebug(ex); }
@@ -112,7 +114,7 @@ namespace GTweak.Modules.Helpers
{
try
{
- files = string.IsNullOrEmpty(directoryPath) ? new string[0] : Directory.GetFiles(directoryPath, "*", SearchOption.AllDirectories);
+ files = Directory.GetFiles(directoryPath, "*", SearchOption.AllDirectories);
if (files == null || files.Length == 0)
{
@@ -155,9 +157,9 @@ namespace GTweak.Modules.Helpers
return result;
}
- foreach (var info in infos)
+ for (int i = 0; i < count; i++)
{
- result.Add(info.Process.dwProcessId);
+ result.Add(infos[i].Process.dwProcessId);
}
}
catch (Exception ex) { ErrorLogger.LogDebug(ex); }
diff --git a/.Source/GTweak/Modules/Maintenance/MemoryCleaner.cs b/.Source/GTweak/Modules/Maintenance/MemoryCleaner.cs
index 2d8c022c..b84d3f58 100644
--- a/.Source/GTweak/Modules/Maintenance/MemoryCleaner.cs
+++ b/.Source/GTweak/Modules/Maintenance/MemoryCleaner.cs
@@ -5,7 +5,6 @@ using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Principal;
-using System.Threading;
using System.Threading.Tasks;
using GTweak.Modules.Common;
using GTweak.Modules.Helpers;
@@ -190,17 +189,7 @@ namespace GTweak.Modules.Maintenance
if (removeWindowsOld)
{
- UnlockHandleHelper.UnlockDirectory(PathTargets.Folders.WindowsOld);
-
- CommandExecutor.RunCommandAsTrustedInstaller($@"/c takeown /f ""{PathTargets.Folders.WindowsOld}"" /r /d y && icacls ""{PathTargets.Folders.WindowsOld}"" /inheritance:r && icacls ""{PathTargets.Folders.WindowsOld}"" /remove *S-1-5-32-544 *S-1-5-11 *S-1-5-32-545 *S-1-5-18 && icacls ""{PathTargets.Folders.WindowsOld}"" /grant {Environment.UserName}:F /t && rd /s /q ""{PathTargets.Folders.WindowsOld}""");
-
- for (int i = 0; IsWinOldExists && i < 10; i++)
- {
- try { Directory.Delete(PathTargets.Folders.WindowsOld, true); Thread.Sleep(300); }
- catch (Exception ex) { ErrorLogger.LogDebug(ex); }
-
- CommandExecutor.RunCommand($"Remove-Item -LiteralPath '{PathTargets.Folders.WindowsOld}' -Recurse -Force", true);
- }
+ FileDirectoryHelper.ForceDeleteDirectory(PathTargets.Folders.WindowsOld);
}
CommandExecutor.RunCommandAsTrustedInstaller(@$"/c rd /s /q {PathTargets.Folders.SystemDrive}Windows\Temp & " +
diff --git a/.Source/GTweak/Modules/Maintenance/RegistryExporter.cs b/.Source/GTweak/Modules/Maintenance/RegistryExporter.cs
index d5da570e..dce3d268 100644
--- a/.Source/GTweak/Modules/Maintenance/RegistryExporter.cs
+++ b/.Source/GTweak/Modules/Maintenance/RegistryExporter.cs
@@ -3,6 +3,7 @@ using System.Diagnostics;
using System.IO;
using System.Text;
using GTweak.Modules.Common;
+using GTweak.Modules.Helpers;
using GTweak.Modules.Managers;
using Microsoft.Win32;
@@ -67,7 +68,8 @@ namespace GTweak.Modules.Maintenance
internal void Export(string fileName)
{
string tempDir = PathTargets.Folders.Workspace;
- Directory.CreateDirectory(tempDir);
+
+ FileDirectoryHelper.CreateDirectory(tempDir);
List<string> tempFiles = new List<string>();
try
@@ -99,18 +101,8 @@ namespace GTweak.Modules.Maintenance
catch { NotificationManager.Warn("error_reg_exporter_noty").Perform(); }
finally
{
- foreach (string file in tempFiles)
- {
- if (File.Exists(file))
- {
- File.Delete(file);
- }
- }
-
- if (Directory.Exists(tempDir))
- {
- Directory.Delete(tempDir);
- }
+ FileDirectoryHelper.DeleteFile(tempFiles.ToArray());
+ FileDirectoryHelper.DeleteDirectory(tempDir);
NotificationManager.Info("success_reg_exporter_noty").WithDelay(500).Perform();
}
diff --git a/.Source/GTweak/Modules/Managers/ArchiveManager.cs b/.Source/GTweak/Modules/Managers/ArchiveManager.cs
index e633413f..06d4e533 100644
--- a/.Source/GTweak/Modules/Managers/ArchiveManager.cs
+++ b/.Source/GTweak/Modules/Managers/ArchiveManager.cs
@@ -1,5 +1,6 @@
using System.IO;
using System.IO.Compression;
+using GTweak.Modules.Helpers;
namespace GTweak.Modules.Managers
{
@@ -7,12 +8,7 @@ namespace GTweak.Modules.Managers
{
internal static void Unarchive(string path, byte[] resource)
{
- string folderDir = Path.GetDirectoryName(path);
-
- if (!Directory.Exists(folderDir))
- {
- Directory.CreateDirectory(folderDir);
- }
+ FileDirectoryHelper.CreateDirectory(Path.GetDirectoryName(path));
using MemoryStream fileOut = new MemoryStream(resource);
using GZipStream gzipStream = new GZipStream(fileOut, CompressionMode.Decompress);
diff --git a/.Source/GTweak/Modules/Tweaks/AppxPackageHandler.cs b/.Source/GTweak/Modules/Tweaks/AppxPackageHandler.cs
index b375bf11..df3e8e83 100644
--- a/.Source/GTweak/Modules/Tweaks/AppxPackageHandler.cs
+++ b/.Source/GTweak/Modules/Tweaks/AppxPackageHandler.cs
@@ -4,7 +4,6 @@ using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
-using System.Threading;
using System.Threading.Tasks;
using GTweak.Modules.Common;
using GTweak.Modules.Helpers;
@@ -143,7 +142,7 @@ namespace GTweak.Modules.Tweaks
await CommandExecutor.InvokeRunCommand(psCommands, true).ConfigureAwait(false);
- CommandExecutor.RunCommandAsTrustedInstaller($@"/c for /d %i in ({string.Join(" ", packageNamesToRemove.Select(n => $@"""{Path.Combine(PathTargets.Folders.SystemDrive, "Program Files", "WindowsApps")}\*{n}*"""))}) do takeown /f ""%i"" /r /d y && icacls ""%i"" /inheritance:r /remove S-1-5-32-544 S-1-5-11 S-1-5-32-545 S-1-5-18 && icacls ""%i"" /grant {Environment.UserName}:F && rd /s /q ""%i""");
+ CommandExecutor.RunCommandAsTrustedInstaller($@"/c for /d %i in ({string.Join(" ", packageNamesToRemove.Select(n => $@"""{Path.Combine(PathTargets.Folders.SystemDrive, "Program Files", "WindowsApps")}\*{n}*"""))}) do takeown /f ""%i"" /r /d y && icacls ""%i"" /inheritance:r /remove S-1-5-32-544 S-1-5-11 S-1-5-32-545 S-1-5-18 && icacls ""%i"" /grant ""{Environment.UserName}"":F && rd /s /q ""%i""");
string[] allUserStorePaths =
{
@@ -264,12 +263,8 @@ namespace GTweak.Modules.Tweaks
string setup = PathTargets.Executable.EdgeSetup;
string stub = PathTargets.Executable.EdgeTempStub;
- try
- {
- Directory.CreateDirectory(Path.GetDirectoryName(stub));
- File.WriteAllBytes(stub, Array.Empty<byte>());
- }
- catch (Exception ex) { ErrorLogger.LogDebug(ex); }
+ FileDirectoryHelper.CreateDirectory(Path.GetDirectoryName(stub));
+ File.WriteAllBytes(stub, Array.Empty<byte>());
if (!string.IsNullOrEmpty(setup))
{
@@ -292,14 +287,7 @@ namespace GTweak.Modules.Tweaks
catch (Exception ex) { ErrorLogger.LogDebug(ex); }
}
- try
- {
- if (Directory.Exists(Path.GetDirectoryName(stub)))
- {
- Directory.Delete(Path.GetDirectoryName(stub), true);
- }
- }
- catch (Exception ex) { ErrorLogger.LogDebug(ex); }
+ FileDirectoryHelper.DeleteDirectory(Path.GetDirectoryName(stub));
if (removeWebView)
{
@@ -321,14 +309,7 @@ namespace GTweak.Modules.Tweaks
RegistryHelper.DeleteFolderTree(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Browser Helper Objects", true);
RegistryHelper.DeleteFolderTree(Registry.LocalMachine, @"SOFTWARE\Microsoft\WindowsUpdate\Orchestrator\UScheduler_Oobe\EdgeUpdate", true);
- foreach (string dir in PathTargets.Folders.EdgeComponents)
- {
- if (Directory.Exists(dir))
- {
- UnlockHandleHelper.UnlockDirectory(dir);
- RemoveDirectory(dir);
- }
- }
+ FileDirectoryHelper.ForceDeleteDirectory(PathTargets.Folders.EdgeComponents);
}
try
@@ -338,7 +319,7 @@ namespace GTweak.Modules.Tweaks
{
using RegistryKey subKeyEntry = key.OpenSubKey(subKey);
string path = subKeyEntry?.GetValue("Path") as string;
- if (!string.IsNullOrEmpty(path) && path.Equals("Edge"))
+ if (!string.IsNullOrEmpty(path) && path.Contains("Edge"))
{
if (!removeWebView && path.Contains("WebView"))
{
@@ -350,7 +331,7 @@ namespace GTweak.Modules.Tweaks
path = path.Replace(@"\AppxManifest.xml", "").Trim();
}
- RemoveDirectory(path);
+ FileDirectoryHelper.ForceDeleteDirectory(path);
key.DeleteSubKey(subKey);
@@ -360,18 +341,5 @@ namespace GTweak.Modules.Tweaks
}
catch (Exception ex) { ErrorLogger.LogDebug(ex); }
}
-
- private static void RemoveDirectory(string path)
- {
- CommandExecutor.RunCommandAsTrustedInstaller($@"/c takeown /f ""{path}"" /r /d y && icacls ""{path}"" /inheritance:r && icacls ""{path}"" /remove *S-1-5-32-544 *S-1-5-11 *S-1-5-32-545 *S-1-5-18 && icacls ""{path}"" /grant {Environment.UserName}:F /t && rd /s /q ""{path}""");
-
- for (int i = 0; Directory.Exists(path) && i < 10; i++)
- {
- try { Directory.Delete(path, true); Thread.Sleep(300); }
- catch (Exception ex) { ErrorLogger.LogDebug(ex); }
-
- CommandExecutor.RunCommand($"Remove-Item -LiteralPath '{path}' -Recurse -Force", true);
- }
- }
}
}
diff --git a/.Source/GTweak/Modules/Tweaks/ConfidentialityTweaks.cs b/.Source/GTweak/Modules/Tweaks/ConfidentialityTweaks.cs
index e37b1511..73c12a51 100644
--- a/.Source/GTweak/Modules/Tweaks/ConfidentialityTweaks.cs
+++ b/.Source/GTweak/Modules/Tweaks/ConfidentialityTweaks.cs
@@ -247,10 +247,9 @@ namespace GTweak.Modules.Tweaks
{
if (state)
{
- File.Copy(PathTargets.Files.Hosts.Backup, PathTargets.Files.Hosts.Original, true);
-
if (File.Exists(PathTargets.Files.Hosts.Backup))
{
+ File.Copy(PathTargets.Files.Hosts.Backup, PathTargets.Files.Hosts.Original, true);
File.Delete(PathTargets.Files.Hosts.Backup);
}
else
@@ -424,8 +423,8 @@ namespace GTweak.Modules.Tweaks
RegistryHelper.Write(Registry.LocalMachine, dmwappushservice, "DelayedAutoStart", 1, RegistryValueKind.DWord);
RegistryHelper.Write(Registry.LocalMachine, dmwappushservice, "DependOnService", new[] { "rpcss" }, RegistryValueKind.MultiString);
- RegistryHelper.Write(Registry.LocalMachine, dmwappushservice, "Description", @"@%SystemRoot%\system32\dmwappushsvc.dll,-201", RegistryValueKind.DWord);
- RegistryHelper.Write(Registry.LocalMachine, dmwappushservice, "DisplayName", @"@%SystemRoot%\system32\dmwappushsvc.dll,-200", RegistryValueKind.DWord);
+ RegistryHelper.Write(Registry.LocalMachine, dmwappushservice, "Description", @"@%SystemRoot%\system32\dmwappushsvc.dll,-201", RegistryValueKind.String);
+ RegistryHelper.Write(Registry.LocalMachine, dmwappushservice, "DisplayName", @"@%SystemRoot%\system32\dmwappushsvc.dll,-200", RegistryValueKind.String);
RegistryHelper.Write(Registry.LocalMachine, dmwappushservice, "ErrorControl", 1, RegistryValueKind.DWord);
RegistryHelper.Write(Registry.LocalMachine, dmwappushservice, "FailureActions", Array.ConvertAll("80,51,01,00,00,00,00,00,00,00,00,00,04,00,00,00,14,00,00,00,01,00,00,00,10,27,00,00,01,00,00,00,10,27,00,00,01,00,00,00,10,27,00,00,00,00,00,00,10,27,00,00".Split(','), s => Convert.ToByte(s, 16)), RegistryValueKind.Binary);
RegistryHelper.Write(Registry.LocalMachine, dmwappushservice, "ImagePath", @"%SystemRoot%\system32\svchost.exe -k netsvcs -p", RegistryValueKind.ExpandString);
@@ -457,7 +456,7 @@ namespace GTweak.Modules.Tweaks
RegistryHelper.Write(Registry.LocalMachine, diagsvc, "FailureActions", Array.ConvertAll("80,51,01,00,00,00,00,00,00,00,00,00,03,00,00,00,14,00,00,00,01,00,00,00,30,75,00,00,01,00,00,00,30,75,00,00,00,00,00,00,00,00,00,00".Split(','), s => Convert.ToByte(s, 16)), RegistryValueKind.Binary);
RegistryHelper.Write(Registry.LocalMachine, diagsvc, "ImagePath", @"%SystemRoot%\System32\svchost.exe -k diagnostics", RegistryValueKind.ExpandString);
RegistryHelper.Write(Registry.LocalMachine, diagsvc, "ObjectName", "LocalSystem", RegistryValueKind.String);
- RegistryHelper.Write(Registry.LocalMachine, diagsvc, "RequiredPrivileges", new[] { "SeTcbPrivilege", "nSeTakeOwnershipPrivilege", "nSeDebugPrivilege", "nSeBackupPrivilege", "nSeImpersonatePrivilege", "nSeLoadDriverPrivilege", "nSeRestorePrivilege", "nSeManageVolumePrivilege" }, RegistryValueKind.MultiString);
+ RegistryHelper.Write(Registry.LocalMachine, diagsvc, "RequiredPrivileges", new[] { "SeTcbPrivilege", "SeTakeOwnershipPrivilege", "SeDebugPrivilege", "SeBackupPrivilege", "SeImpersonatePrivilege", "SeLoadDriverPrivilege", "SeRestorePrivilege", "SeManageVolumePrivilege" }, RegistryValueKind.MultiString);
RegistryHelper.Write(Registry.LocalMachine, diagsvc, "ServiceSidType", 1, RegistryValueKind.DWord);
RegistryHelper.Write(Registry.LocalMachine, diagsvc, "Start", 3, RegistryValueKind.DWord);
RegistryHelper.Write(Registry.LocalMachine, diagsvc, "Type", 32, RegistryValueKind.DWord);
diff --git a/.Source/GTweak/Modules/Tweaks/Defender/AclPermissionsBackup.cs b/.Source/GTweak/Modules/Tweaks/Defender/AclPermissionsBackup.cs
index ac0699d6..eb91f3e6 100644
--- a/.Source/GTweak/Modules/Tweaks/Defender/AclPermissionsBackup.cs
+++ b/.Source/GTweak/Modules/Tweaks/Defender/AclPermissionsBackup.cs
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.IO;
using System.Security.AccessControl;
using GTweak.Modules.Common;
+using GTweak.Modules.Helpers;
using GTweak.Modules.Managers;
using Microsoft.Win32;
using Newtonsoft.Json;
@@ -97,7 +98,7 @@ namespace GTweak.Modules.Tweaks.Defender
{
try
{
- Directory.CreateDirectory(PathTargets.Folders.DefenderBackup);
+ FileDirectoryHelper.CreateDirectory(PathTargets.Folders.DefenderBackup);
Dictionary<string, Dictionary<string, RegistryValueBackup>> allValues = new Dictionary<string, Dictionary<string, RegistryValueBackup>>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, string> aclDataDict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
diff --git a/.Source/GTweak/Modules/Tweaks/Defender/DefenderTweaks.cs b/.Source/GTweak/Modules/Tweaks/Defender/DefenderTweaks.cs
index b90ec985..9b90aa5d 100644
--- a/.Source/GTweak/Modules/Tweaks/Defender/DefenderTweaks.cs
+++ b/.Source/GTweak/Modules/Tweaks/Defender/DefenderTweaks.cs
@@ -3,8 +3,6 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
-using System.Text;
-using System.Threading;
using GTweak.Modules.Common;
using GTweak.Modules.Helpers;
using Microsoft.Win32;
@@ -15,24 +13,24 @@ namespace GTweak.Modules.Tweaks.Defender
{
const string ServiceName = "GTweakWDManager";
- private static readonly Dictionary<string, string> services = new Dictionary<string, string>
+ private static readonly Dictionary<string, int> services = new Dictionary<string, int>
{
- { "WinDefend", "2" },
- { "SecurityHealthService", "2"},
- { "Sense", "3" },
- { "SgrmAgent", "3" },
- { "SgrmBroker", "3" },
- { "MDCoreSvc", "3" },
- { "MsSecCore", "3" },
- { "MsSecFlt", "3" },
- { "MsSecWfp", "3" },
- { "WdFilter", "0" },
- { "WdBoot", "0" },
- { "WdNisDrv", "3" },
- { "WdNisSvc", "3"},
- { "webthreatdefsvc", "3" },
- { "webthreatdefusersvc", "2" },
- { "wscsvc", "2" }
+ { "WinDefend", 2 },
+ { "SecurityHealthService", 2},
+ { "Sense", 3 },
+ { "SgrmAgent", 3 },
+ { "SgrmBroker", 3 },
+ { "MDCoreSvc", 3 },
+ { "MsSecCore", 3 },
+ { "MsSecFlt", 3 },
+ { "MsSecWfp", 3 },
+ { "WdFilter", 3 },
+ { "WdBoot", 0 },
+ { "WdNisDrv", 3 },
+ { "WdNisSvc", 3},
+ { "webthreatdefsvc", 3 },
+ { "webthreatdefusersvc", 2 },
+ { "wscsvc", 2 }
};
internal static void SetProtectionState(bool state) => (state ? (Action)Activate : Deactivate)();
@@ -41,7 +39,7 @@ namespace GTweak.Modules.Tweaks.Defender
{
TerminateProcess();
- InvokePowerShell(@"Set-MpPreference -DisableIOAVProtection $false
+ CommandExecutor.RunEncodedPowerShell(@"Set-MpPreference -DisableIOAVProtection $false
Set-MpPreference -DisableRealtimeMonitoring $false
Set-MpPreference -DisableBehaviorMonitoring $false
Set-MpPreference -DisableBlockAtFirstSeen $false
@@ -71,14 +69,14 @@ namespace GTweak.Modules.Tweaks.Defender
@"reg delete ""HKLM\SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection"" /v DisableRawWriteNotification /f & " +
@"reg delete ""HKLM\SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection"" /v DisableIntrusionPreventionSystem /f & " +
@"reg delete ""HKLM\SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection"" /v DisableInformationProtectionControl /f & " +
- @"reg delete ""HKLM\SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection"" /v RealtimeScanDirection /t REG_DWORD /f & " +
+ @"reg delete ""HKLM\SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection"" /v RealtimeScanDirection /f & " +
@"reg delete ""HKLM\SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection"" /v DisableArchiveScanning /f & " +
@"reg delete ""HKLM\SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection"" /v SignatureDisableUpdateOnStartupWithoutEngine /f & " +
@"reg delete ""HKLM\SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection"" /v DisablePrivacyMode /f & " +
@"reg delete ""HKLM\SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection"" /v DisableBlockAtFirstSeen /f");
CommandExecutor.RunCommandAsTrustedInstaller($@"""{PathTargets.Executable.NSudo}"" -U:T -P:E -CreatePath:S -ShowWindowMode:Hide -Wait cmd /c " +
- @"reg delete ""HKCU\Software\Microsoft\Windows\CurrentVersion\AppHost"" /v EnableWebContentEvaluation /t REG_DWORD /d 0 /f & " +
+ @"reg delete ""HKCU\Software\Microsoft\Windows\CurrentVersion\AppHost"" /v EnableWebContentEvaluation /f & " +
@"reg delete ""HKLM\SOFTWARE\Policies\Microsoft\MicrosoftEdge\PhishingFilter"" /v EnabledV9 /f & " +
@"reg add ""HKLM\SOFTWARE\Microsoft\Windows Defender"" /v PUAProtection /t REG_DWORD /d 2 /f & " +
@"reg add ""HKLM\SOFTWARE\Microsoft\Windows Defender\Features"" /v TamperProtection /t REG_DWORD /d 1 /f & " +
@@ -118,16 +116,16 @@ namespace GTweak.Modules.Tweaks.Defender
RegistryHelper.Write(Registry.LocalMachine, @"SOFTWARE\WOW6432Node\Policies\Microsoft\Windows Defender", "DisableRoutinelyTakingAction", 0, RegistryValueKind.DWord);
RegistryHelper.DeleteFolderTree(Registry.LocalMachine, @"SOFTWARE\Policies\Microsoft\MicrosoftEdge\PhishingFilter");
+ RegistryHelper.DeleteFolderTree(Registry.LocalMachine, @"SOFTWARE\Policies\Microsoft\Windows\WTDS");
+ RegistryHelper.DeleteFolderTree(Registry.LocalMachine, @"SOFTWARE\Policies\Microsoft\Windows Defender Security Center\App and Browser protection");
RegistryHelper.Write(Registry.LocalMachine, @"SYSTEM\CurrentControlSet\Control\CI\Policy", "VerifiedAndReputablePolicyState", 1, RegistryValueKind.DWord);
RegistryHelper.Write(Registry.LocalMachine, @"SYSTEM\CurrentControlSet\Control\CI\Config", "VulnerableDriverBlocklistEnable", 1, RegistryValueKind.DWord);
RegistryHelper.Write(Registry.LocalMachine, @"SYSTEM\CurrentControlSet\Control\CI\Config", "EnabledV9", 1, RegistryValueKind.DWord);
RegistryHelper.Write(Registry.LocalMachine, @"System\CurrentControlSet\Control\CI\State", "HVCIEnabled", 1, RegistryValueKind.DWord);
- RegistryHelper.DeleteFolderTree(Registry.LocalMachine, @"SOFTWARE\Policies\Microsoft\Windows\WTDS");
RegistryHelper.DeleteValue(Registry.LocalMachine, @"SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity", "Enabled");
RegistryHelper.DeleteValue(Registry.LocalMachine, @"SYSTEM\CurrentControlSet\Control\DeviceGuard", "EnableVirtualizationBasedSecurity");
-
RegistryHelper.DeleteValue(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\AppHost", "EnableWebContentEvaluation");
RegistryHelper.DeleteValue(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\AppHost", "PreventOverride");
RegistryHelper.CreateFolder(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
@@ -139,7 +137,7 @@ namespace GTweak.Modules.Tweaks.Defender
RegistryHelper.Write(Registry.ClassesRoot, @"*\shellex\ContextMenuHandlers\EPP", "", "{09A47860-11B0-4DA5-AFA5-26D86198A780}", RegistryValueKind.String);
RegistryHelper.Write(Registry.ClassesRoot, @"Directory\shellex\ContextMenuHandlers\EPP", "", "{09A47860-11B0-4DA5-AFA5-26D86198A780}", RegistryValueKind.String);
RegistryHelper.Write(Registry.ClassesRoot, @"Drive\shellex\ContextMenuHandlers\EPP", "", "{09A47860-11B0-4DA5-AFA5-26D86198A780}", RegistryValueKind.String);
- RegistryHelper.Write(Registry.ClassesRoot, @"CLSID\{09A47860-11B0-4DA5-AFA5-26D86198A780}\InprocServer32", "", PathTargets.Folders.SystemDrive + @"Program Files\Windows Defender\shellext.dll", RegistryValueKind.String);
+ RegistryHelper.Write(Registry.ClassesRoot, @"CLSID\{09A47860-11B0-4DA5-AFA5-26D86198A780}\InprocServer32", "", Path.Combine(PathTargets.Folders.SystemDrive, @"Program Files\Windows Defender\shellext.dll"), RegistryValueKind.String);
RegistryHelper.Write(Registry.ClassesRoot, @"CLSID\{09A47860-11B0-4DA5-AFA5-26D86198A780}\InprocServer32", "ThreadingModel", "Apartment", RegistryValueKind.String);
RegistryHelper.DeleteValue(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows defender\Windows defender Exploit Guard\ASR", "EnableASRConsumers");
@@ -170,25 +168,33 @@ namespace GTweak.Modules.Tweaks.Defender
foreach ((string Normal, string Block) in PathTargets.Targets.Defender.Mappings)
{
- CommandExecutor.RunCommandAsTrustedInstaller($@"""{PathTargets.Executable.NSudo}"" -U:T -P:E -CreatePath:S -ShowWindowMode:Hide -Wait cmd /c ""{CommandExecutor.CleanCommand(string.Join(" && ", new[] {
- $@"(if exist ""{Normal}"" (takeown /f ""{Normal}"" /a && del /f /q /a ""{Normal}"") else (cd .))",
- $@"takeown /f ""{Block}"" /a",
- $@"rename ""{Block}"" ""{Path.GetFileName(Normal)}""",
- $@"icacls ""{Normal}"" /setowner *S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464",
- $@"icacls ""{Normal}"" /inheritance:r",
- $@"icacls ""{Normal}"" /grant *S-1-5-32-544:F",
- $@"icacls ""{Normal}"" /grant *S-1-5-32-545:R",
- $@"icacls ""{Normal}"" /grant *S-1-5-18:F",
- $@"icacls ""{Normal}"" /grant *S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464:F",
- $@"icacls ""{Normal}"" /grant *S-1-15-2-1:R",
- $@"icacls ""{Normal}"" /grant *S-1-15-2-2:R",
- $@"icacls ""{Normal}"" /remove ""{Environment.UserName}"""}))}""");
+ if (File.Exists(Normal))
+ {
+ CommandExecutor.RunCommandAsTrustedInstaller($@"""{PathTargets.Executable.NSudo}"" -U:T -P:E -CreatePath:S -ShowWindowMode:Hide -Wait cmd /c takeown /f ""{Block}"" /a && del /f /q /a ""{Block}""");
+ }
+ else if (File.Exists(Block))
+ {
+ CommandExecutor.RunCommandAsTrustedInstaller($@"""{PathTargets.Executable.NSudo}"" -U:T -P:E -CreatePath:S -ShowWindowMode:Hide -Wait cmd /c {CommandExecutor.CleanCommand(string.Join(" && ", new[]
+ {
+ $@"takeown /f ""{Block}"" /a",
+ $@"rename ""{Block}"" ""{Path.GetFileName(Normal)}""",
+ $@"icacls ""{Normal}"" /setowner *S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464",
+ $@"icacls ""{Normal}"" /inheritance:r",
+ $@"icacls ""{Normal}"" /grant *S-1-5-32-544:F",
+ $@"icacls ""{Normal}"" /grant *S-1-5-32-545:R",
+ $@"icacls ""{Normal}"" /grant *S-1-5-18:F",
+ $@"icacls ""{Normal}"" /grant *S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464:F",
+ $@"icacls ""{Normal}"" /grant *S-1-15-2-1:R",
+ $@"icacls ""{Normal}"" /grant *S-1-15-2-2:R",
+ $@"icacls ""{Normal}"" /remove ""{Environment.UserName}"""
+ }))}""");
+ }
}
ImportRights();
- InvokePowerShell("Get-AppxPackage Microsoft.SecHealthUI -AllUsers | Reset-AppxPackage");
- InvokePowerShell(@"Get-AppXpackage Microsoft.WindowsDefender | Foreach {Add-AppxPackage -DisableDevelopmentMode -Register ""$($_.InstallLocation)\AppXManifest.xml""}");
+ CommandExecutor.RunEncodedPowerShell("Get-AppxPackage Microsoft.SecHealthUI -AllUsers | Reset-AppxPackage");
+ CommandExecutor.RunEncodedPowerShell(@"Get-AppXpackage Microsoft.WindowsDefender | Foreach {Add-AppxPackage -DisableDevelopmentMode -Register ""$($_.InstallLocation)\AppXManifest.xml""}");
CommandExecutor.RunCommand($"/c timeout /t 10 && del /f \"{PathTargets.Executable.NSudo}\"");
}
@@ -234,7 +240,7 @@ namespace GTweak.Modules.Tweaks.Defender
RegistryHelper.Write(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows defender\Windows defender Exploit Guard\Controlled Folder Access", "EnableControlledFolderAccess", 0, RegistryValueKind.DWord, true);
RegistryHelper.Write(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows defender\Windows defender Exploit Guard\Network Protection", "EnableNetworkProtection", 0, RegistryValueKind.DWord, true);
- InvokePowerShell(@"Set-MpPreference -DisableIOAVProtection $true
+ CommandExecutor.RunEncodedPowerShell(@"Set-MpPreference -DisableIOAVProtection $true
Set-MpPreference -DisableRealtimeMonitoring $true
Set-MpPreference -DisableBehaviorMonitoring $true
Set-MpPreference -DisableBlockAtFirstSeen $true
@@ -368,8 +374,8 @@ namespace GTweak.Modules.Tweaks.Defender
RegistryHelper.Write(Registry.LocalMachine, @"System\CurrentControlSet\Control\CI\State", "HVCIEnabled", 0, RegistryValueKind.DWord);
RegistryHelper.Write(Registry.LocalMachine, @"SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity", "Enabled", 0, RegistryValueKind.DWord);
RegistryHelper.Write(Registry.LocalMachine, @"SYSTEM\CurrentControlSet\Control\DeviceGuard", "EnableVirtualizationBasedSecurity", 0, RegistryValueKind.DWord);
- RegistryHelper.Write(Registry.LocalMachine, @"SOFTWARE\Policies\Microsoft\Windows\WTDS\Components", "ServiceEnabled", "0", RegistryValueKind.DWord);
- RegistryHelper.Write(Registry.LocalMachine, @"SOFTWARE\Policies\Microsoft\MicrosoftEdge\PhishingFilter", "EnabledV9", "0", RegistryValueKind.DWord);
+ RegistryHelper.Write(Registry.LocalMachine, @"SOFTWARE\Policies\Microsoft\Windows\WTDS\Components", "ServiceEnabled", 0, RegistryValueKind.DWord);
+ RegistryHelper.Write(Registry.LocalMachine, @"SOFTWARE\Policies\Microsoft\MicrosoftEdge\PhishingFilter", "EnabledV9", 0, RegistryValueKind.DWord);
RegistryHelper.Write(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\AppHost", "EnableWebContentEvaluation", 0, RegistryValueKind.DWord);
RegistryHelper.Write(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\AppHost", "PreventOverride", 0, RegistryValueKind.DWord);
RegistryHelper.Write(Registry.CurrentUser, @"SOFTWARE\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppContainer\Storage\microsoft.microsoftedge_8wekyb3d8bbwe\MicrosoftEdge", "EnabledV9", 0, RegistryValueKind.DWord);
@@ -396,36 +402,6 @@ namespace GTweak.Modules.Tweaks.Defender
RegistryHelper.DeleteFolderTree(Registry.ClassesRoot, @"Drive\shellex\ContextMenuHandlers\EPP");
RegistryHelper.DeleteFolderTree(Registry.ClassesRoot, @"CLSID\{09A47860-11B0-4DA5-AFA5-26D86198A780}\InprocServer32");
- ManageExclusions(true);
-
- foreach (string directory in PathTargets.Targets.Defender.CleanupFolders)
- {
- try
- {
- if (!Directory.Exists(directory))
- {
- continue;
- }
-
- foreach (string file in Directory.EnumerateFiles(directory, "*", SearchOption.TopDirectoryOnly))
- {
- CommandExecutor.RunCommandAsTrustedInstaller($@"""{PathTargets.Executable.NSudo}"" -U:T -P:E -CreatePath:S -ShowWindowMode:Hide -Wait cmd /c ""{$@"takeown /f ""{file}"" /a & icacls ""{file}"" /inheritance:r /remove *S-1-5-32-544 *S-1-5-11 *S-1-5-32-545 *S-1-5-18 & icacls ""{file}"" /grant ""{Environment.UserName}"":F & del /f /q ""{file}"""}""");
-
- for (int i = 0; File.Exists(file) && i < 10; i++)
- {
- try { File.Delete(file); }
- catch (Exception ex) { ErrorLogger.LogDebug(ex); }
-
- CommandExecutor.RunCommandAsTrustedInstaller($@"""{PathTargets.Executable.NSudo}"" -U:T -P:E -CreatePath:S -ShowWindowMode:Hide -Wait cmd /c ""del /f /q ""{file}""""");
- TakingOwnership.GrantAdministratorsAccess(file, TakingOwnership.SE_OBJECT_TYPE.SE_FILE_OBJECT);
-
- Thread.Sleep(500);
- }
- }
- }
- catch (Exception ex) { ErrorLogger.LogDebug(ex); }
- }
-
RegistryHelper.Write(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "ConsentPromptBehaviorAdmin", 0, RegistryValueKind.DWord);
RegistryHelper.Write(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "EnableInstallerDetection", 0, RegistryValueKind.DWord);
RegistryHelper.Write(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "EnableLUA", 0, RegistryValueKind.DWord);
@@ -434,6 +410,10 @@ namespace GTweak.Modules.Tweaks.Defender
RegistryHelper.Write(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "FilterAdministratorToken", 0, RegistryValueKind.DWord);
RegistryHelper.Write(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "PromptOnSecureDesktop", 0, RegistryValueKind.DWord);
+ ManageExclusions(true);
+
+ FileDirectoryHelper.ForceDeleteDirectoryContents(PathTargets.Targets.Defender.CleanupFolders);
+
CommandExecutor.RunCommand($"/c sc create {ServiceName} binPath= \"{PathTargets.Executable.DisablingWD} /unlock\" type= own start= auto obj= LocalSystem");
RegistryHelper.Write(Registry.LocalMachine, $@"SYSTEM\CurrentControlSet\Control\SafeBoot\Minimal\{ServiceName}", "", "Service", RegistryValueKind.String);
@@ -463,31 +443,10 @@ namespace GTweak.Modules.Tweaks.Defender
private static void TerminateProcess()
{
string[] processes = { "smartscreen", "mpdefendercoreservice", "msmpeng", "securityhealthservice", "securityhealthsystray", "securityhealthui", "wuauserv", "searchui", "sechealthui", "configsecuritypolicy", "runtimebroker", "msedge", "ssoncom", "usocoreworker", "defenderbootstrapper", "sensedlpprocessor", "sensetracer",
- "dlpuseragent", "mpam-d", "mpam-fe", "mpam-fe_bd", "mpas-d", "mpas-fe", "mpas-fe_bd", "mpav-d", "mpav-fe", "mpav-fe_bd", "mpcmdrun", "mpcopyaccelerator", "mpdlpcmd", "mpdlpservice", "mpextms", "mpsigstub", "mrt", "msmpengcp", "mssense", "nissrv", "offlinescannershell", "securekernel", "usocoreworker", "securityhealthhost",
+ "dlpuseragent", "mpam-d", "mpam-fe", "mpam-fe_bd", "mpas-d", "mpas-fe", "mpas-fe_bd", "mpav-d", "mpav-fe", "mpav-fe_bd", "mpcmdrun", "mpcopyaccelerator", "mpdlpcmd", "mpdlpservice", "mpextms", "mpsigstub", "mrt", "msmpengcp", "mssense", "nissrv", "offlinescannershell", "securekernel", "securityhealthhost",
"senseap", "senseaptoast", "sensecm", "sensegpparser", "senseidentity", "senseimdscollector", "senseir", "sensendr", "sensesampleuploader", "sensetvm", "sgrmbroker", "healthattestationclientagent", "wdnissvc", "wdboot", "msseccore", "mssecflt", "mssecwfp", "mdcoresvc", "sensece", "senseui", "sensepp", "wdshield", "mipdlp" };
CommandExecutor.RunCommandAsTrustedInstaller($@"""{PathTargets.Executable.NSudo}"" -U:T -P:E -CreatePath:S -ShowWindowMode:Hide -Wait cmd /c taskkill /f " + string.Join(" ", processes.Select(p => $"/im {p}.exe")));
}
-
- private static void InvokePowerShell(string command)
- {
- try
- {
- Process comandoAEjecutar = new Process();
- comandoAEjecutar.StartInfo.FileName = PathTargets.Executable.PowerShell;
- comandoAEjecutar.StartInfo.Arguments =
- "-NoLogo -NonInteractive -NoProfile -ExecutionPolicy Bypass -EncodedCommand \"" +
- Convert.ToBase64String(Encoding.Unicode.GetBytes(command)) + "\"";
- comandoAEjecutar.StartInfo.UseShellExecute = false;
- comandoAEjecutar.StartInfo.RedirectStandardOutput = true;
- comandoAEjecutar.StartInfo.RedirectStandardError = true;
- comandoAEjecutar.StartInfo.CreateNoWindow = true;
- comandoAEjecutar.Start();
- comandoAEjecutar.StandardOutput.ReadToEnd();
- return;
- }
- catch (Exception ex) { ErrorLogger.LogDebug(ex); }
-
- }
}
}
diff --git a/.Source/GTweak/Modules/Tweaks/InterfaceTweaks.cs b/.Source/GTweak/Modules/Tweaks/InterfaceTweaks.cs
index 8ca4a7f2..9f6de385 100644
--- a/.Source/GTweak/Modules/Tweaks/InterfaceTweaks.cs
+++ b/.Source/GTweak/Modules/Tweaks/InterfaceTweaks.cs
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
-using System.IO;
using System.Text;
using System.Threading.Tasks;
using GTweak.Modules.Common;
@@ -492,10 +491,7 @@ namespace GTweak.Modules.Tweaks
{
if (state)
{
- if (File.Exists(PathTargets.Files.BlankIcon))
- {
- File.Delete(PathTargets.Files.BlankIcon);
- }
+ FileDirectoryHelper.DeleteFile(PathTargets.Files.BlankIcon);
RegistryHelper.DeleteFolderTree(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Icons");
}
diff --git a/.Source/GTweak/Modules/Tweaks/ServicesTweaks.cs b/.Source/GTweak/Modules/Tweaks/ServicesTweaks.cs
index 5fc983dd..c40b4b2c 100644
--- a/.Source/GTweak/Modules/Tweaks/ServicesTweaks.cs
+++ b/.Source/GTweak/Modules/Tweaks/ServicesTweaks.cs
@@ -622,7 +622,7 @@ namespace GTweak.Modules.Tweaks
internal void Apply(string tweakName, bool state)
{
- INIManager.TempWrite(INIManager.TempTweaksConf, tweakName, state);
+ INIManager.TempWrite(INIManager.TempTweaksSvc, tweakName, state);
if (tweakName.StartsWith("TglButton") && int.TryParse(tweakName.Substring(9), out int index))
{
@@ -649,22 +649,10 @@ namespace GTweak.Modules.Tweaks
{
CommandExecutor.RunCommandAsTrustedInstaller($"/c net stop wuauserv & net stop bits & net stop cryptSvc & net stop RuntimeBroker & taskkill /f " + string.Join(" ", (new string[] { "usocoreworker", "msedge", "pwahelper", "edgeupdate", "edgeupdatem", "microsoftedgeupdate", "msedgewebviewhost", "msedgeuserbroker", "runtimebroker", "widgets" }).Select(p => $"/im {p}.exe")));
- foreach (string path in PathTargets.Targets.WindowsUpdate.CleanupFolders)
- {
- UnlockHandleHelper.UnlockDirectory(path);
-
- CommandExecutor.RunCommandAsTrustedInstaller($@"/c takeown /f ""{path}"" /r /d y && icacls ""{path}"" /inheritance:r && icacls ""{path}"" /remove *S-1-5-32-544 *S-1-5-11 *S-1-5-32-545 *S-1-5-18 && icacls ""{path}"" /grant {Environment.UserName}:F /t && rd /s /q ""{path}""");
-
- for (int i = 0; Directory.Exists(path) && i < 5; i++)
- {
- try { Directory.Delete(path, true); }
- catch (Exception ex) { ErrorLogger.LogDebug(ex); }
-
- CommandExecutor.RunCommand($"Remove-Item -LiteralPath '{path}' -Recurse -Force", true);
- }
- }
+ FileDirectoryHelper.ForceDeleteDirectory(PathTargets.Targets.WindowsUpdate.CleanupFolders);
SetTaskStateOwner(false, winUpdatesTasks);
+
CommandExecutor.RunCommandAsTrustedInstaller("/c net start bits & net start cryptSvc");
}
}