Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
name: Build

on:
push:
pull_request:

jobs:
windows:
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-dotnet@v4
with:
dotnet-version: 9.0.x
- name: Test and build
run: dotnet test DiskSweeper.sln -c Release --nologo
13 changes: 13 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -485,3 +485,16 @@ $RECYCLE.BIN/

# The template's *.app rule (macOS app bundles) also matches the DiskSweeper.App project folder on Windows.
!src/DiskSweeper.App/

# Local secrets. This repo has none; keep new ones out of git.
.env.*
!.env.example
*.pem
*.key
id_rsa
id_rsa.pub

# Crash dumps and editor backups
*.dmp
*.orig
*.rej
9 changes: 9 additions & 0 deletions Directory.Build.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Project>
<PropertyGroup>
<Version>1.0.0</Version>
<Product>DiskSweeper</Product>
<Company>DiskSweeper</Company>
<Copyright>Copyright © 2026 DiskSweeper contributors</Copyright>
<NeutralLanguage>en-US</NeutralLanguage>
</PropertyGroup>
</Project>
4 changes: 3 additions & 1 deletion DiskSweeper.sln
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{7C3E9A21-4B58-4E1D-9F0A-6D2C8B4E1A77}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DiskSweeper.Core", "src\DiskSweeper.Core\DiskSweeper.Core.csproj", "{B90FE70F-AEE5-4F07-9A30-FBE1874D6843}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DiskSweeper.Cli", "src\DiskSweeper.Cli\DiskSweeper.Cli.csproj", "{2410D1B9-8A03-41EB-B18A-1814BF0F32C4}"
Expand Down Expand Up @@ -78,7 +80,7 @@ Global
GlobalSection(NestedProjects) = preSolution
{B90FE70F-AEE5-4F07-9A30-FBE1874D6843} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{2410D1B9-8A03-41EB-B18A-1814BF0F32C4} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{F0B8CF17-A527-441F-A08B-8C175DD94231} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{F0B8CF17-A527-441F-A08B-8C175DD94231} = {7C3E9A21-4B58-4E1D-9F0A-6D2C8B4E1A77}
{F264EE83-4F55-4F8F-BCBB-D4D42719AE61} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
EndGlobalSection
EndGlobal
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 DiskSweeper contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
241 changes: 146 additions & 95 deletions README.md

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions global.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"sdk": {
"version": "9.0.100",
"rollForward": "latestFeature",
"allowPrerelease": false
}
}
2 changes: 2 additions & 0 deletions src/DiskSweeper.App/DiskSweeper.App.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
<RootNamespace>DiskSweeper.App</RootNamespace>
<ApplicationManifest>app.manifest</ApplicationManifest>
<ApplicationIcon>Assets\DiskSweeper.ico</ApplicationIcon>
<!-- The app runs only on Windows. This lets the project compile on other systems too. -->
<EnableWindowsTargeting>true</EnableWindowsTargeting>
<!-- WPF's Fluent theme (light/dark following Windows) is marked experimental in .NET 9. -->
<NoWarn>$(NoWarn);WPF0001</NoWarn>
</PropertyGroup>
Expand Down
56 changes: 49 additions & 7 deletions src/DiskSweeper.App/Infrastructure/ElevatedRunner.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
using DiskSweeper.Core;
using DiskSweeper.Core.Deletion;

Expand All @@ -25,6 +27,7 @@ public static async Task<IReadOnlyList<DeleteResult>> RunAsync(AdminAction actio
foreach (var job in AdminJob.Split(action, paths, method))
{
string resultFile = Path.Join(Path.GetTempPath(), $"DiskSweeper-{Guid.NewGuid():N}.json");
CreateResultFile(resultFile);
var start = new ProcessStartInfo(Environment.ProcessPath!)
{
UseShellExecute = true,
Expand Down Expand Up @@ -68,6 +71,9 @@ public static async Task<IReadOnlyList<DeleteResult>> RunAsync(AdminAction actio
/// <summary>Entry point of the hidden elevated copy. Returns the process exit code.</summary>
public static int RunHelper(string encodedJob, string resultFile)
{
// Refuse before doing any work. A crafted command line must not delete files or write outside temp.
if (!AdminJob.IsAcceptableResultFile(resultFile)) return 1;

try
{
var job = AdminJob.Decode(encodedJob);
Expand All @@ -77,17 +83,53 @@ public static int RunHelper(string encodedJob, string resultFile)
}
catch (Exception ex)
{
try
{
File.WriteAllText(resultFile + ".error.txt", ex.ToString());
}
catch (IOException)
{
}
TryWriteError(resultFile, ex);
return 1;
}
}

/// <summary>Creates the result file first so its name is fixed before the permission prompt, and only this user can replace it.</summary>
private static void CreateResultFile(string path)
{
using (new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
}

try
{
var user = WindowsIdentity.GetCurrent().User;
if (user is null) return;

var security = new FileSecurity();
security.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
var rights = FileSystemRights.Read | FileSystemRights.Write | FileSystemRights.Delete;
security.AddAccessRule(new FileSystemAccessRule(user, rights, AccessControlType.Allow));
security.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), rights, AccessControlType.Allow));
security.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), rights, AccessControlType.Allow));
new FileInfo(path).SetAccessControl(security);
}
catch (Exception ex) when (ex is UnauthorizedAccessException or IdentityNotMappedException or PlatformNotSupportedException or InvalidOperationException or IOException)
{
// The path check still keeps the write inside this temp file.
}
}

private static void TryWriteError(string resultFile, Exception ex)
{
if (!AdminJob.IsAcceptableResultFile(resultFile)) return;

string full = Path.GetFullPath(resultFile);
string errorFile = Path.Join(Path.GetDirectoryName(full)!, Path.GetFileName(full) + ".error.txt");
try
{
if (File.Exists(errorFile) && (File.GetAttributes(errorFile) & FileAttributes.ReparsePoint) != 0) return;
File.WriteAllText(errorFile, ex.ToString());
}
catch (Exception writeError) when (writeError is IOException or UnauthorizedAccessException)
{
}
}

/// <summary>Starts a new DiskSweeper as administrator. Returns false if the permission prompt was declined.</summary>
public static bool RestartElevated(string path)
{
Expand Down
25 changes: 18 additions & 7 deletions src/DiskSweeper.App/Infrastructure/Shell.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.IO;
using System.Windows;
using DiskSweeper.Core;
using DiskSweeper.Core.SmartFinds;

namespace DiskSweeper.App.Infrastructure;

Expand Down Expand Up @@ -32,22 +33,32 @@ public static void CopyText(string text)
public static void OpenUrl(string url) => Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });

/// <summary>
/// Opens a command the user chose to run from a Cleanup advice (e.g. a Settings page or
/// System Properties). Commands that need a terminal open in an administrator PowerShell window.
/// Opens a command the user chose to run from a Cleanup advice (a Settings page or System Properties).
/// Commands that need a terminal open in an administrator PowerShell window. Returns false when the
/// command is not one of the shapes DiskSweeper ships (so a changed rules file can't launch an arbitrary program).
/// </summary>
public static void RunAdvice(string command)
public static bool RunAdvice(string command)
{
if (!AdviceCommands.IsAllowed(command)) return false;

if (command.StartsWith("start ", StringComparison.OrdinalIgnoreCase))
{
OpenUrl(command[6..].Trim());
return true;
}
else if (command.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))

if (command.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
{
Process.Start(new ProcessStartInfo(command) { UseShellExecute = true });
return true;
}
else

Process.Start(new ProcessStartInfo("powershell.exe")
{
Process.Start(new ProcessStartInfo("powershell.exe", $"-NoExit -Command \"{command}\"") { UseShellExecute = true, Verb = "runas" });
}
UseShellExecute = true,
Verb = "runas",
ArgumentList = { "-NoExit", "-NoProfile", "-Command", command },
});
return true;
}
}
6 changes: 4 additions & 2 deletions src/DiskSweeper.App/ViewModels/SmartFindsViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,9 @@ private void RaiseTotals()
private void RunAdvice(object? parameter)
{
if (parameter is not string command) return;
if (Dialogs.Confirm($"Run this?\n\n{command}\n\nCommands that change Windows settings open in an administrator PowerShell window so you can see what happens."))
Shell.RunAdvice(command);
if (!Dialogs.Confirm($"Run this?\n\n{command}\n\nCommands that change Windows settings open in an administrator PowerShell window so you can see what happens."))
return;
if (!Shell.RunAdvice(command))
Dialogs.Info("DiskSweeper didn't run that command. Copy it and run it yourself if you still want to.");
}
}
70 changes: 68 additions & 2 deletions src/DiskSweeper.Core/Deletion/AdminJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,74 @@ public IReadOnlyList<DeleteResult> Run(DeleteService service, CancellationToken
_ => service.Delete(path, Method, cancellationToken: cancellationToken),
}).ToList();

public static void WriteResults(string file, IReadOnlyList<DeleteResult> results) =>
File.WriteAllText(file, JsonSerializer.Serialize(results, Json));
/// <summary>
/// True when <paramref name="path"/> is a <c>DiskSweeper-{32 hex}.json</c> file directly in the temp folder.
/// The elevated helper will not write anywhere else, and it will not follow a link planted at that name.
/// </summary>
public static bool IsAcceptableResultFile(string? path)
{
if (string.IsNullOrWhiteSpace(path)) return false;

string full;
try
{
full = Path.GetFullPath(path);
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
{
return false;
}

// A second colon is an NTFS alternate data stream (C:\Temp\file.json:evil), not part of the file name.
int colon = full.IndexOf(':');
if (colon >= 0 && full.IndexOf(':', colon + 1) >= 0) return false;

const string prefix = "DiskSweeper-";
const string suffix = ".json";
string name = Path.GetFileName(full);
if (name.Length != prefix.Length + 32 + suffix.Length
|| !name.StartsWith(prefix, StringComparison.Ordinal)
|| !name.EndsWith(suffix, StringComparison.OrdinalIgnoreCase))
{
return false;
}

foreach (char c in name.AsSpan(prefix.Length, 32))
{
if (!Uri.IsHexDigit(c)) return false;
}

string? directory = Path.GetDirectoryName(full);
if (string.IsNullOrEmpty(directory)) return false;

string temp = Path.TrimEndingDirectorySeparator(Path.GetFullPath(Path.GetTempPath()));
var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
if (!string.Equals(Path.TrimEndingDirectorySeparator(directory), temp, comparison)) return false;

try
{
// GetAttributes does not follow the last component, so a dangling symlink is visible here
// even though File.Exists is false for it.
if ((File.GetAttributes(full) & FileAttributes.ReparsePoint) != 0) return false;
}
catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException)
{
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return false;
}

return true;
}

public static void WriteResults(string file, IReadOnlyList<DeleteResult> results)
{
if (!IsAcceptableResultFile(file))
throw new ArgumentException("Result file must be a DiskSweeper-*.json file directly in the temp folder.", nameof(file));

File.WriteAllText(Path.GetFullPath(file), JsonSerializer.Serialize(results, Json));
}

public static IReadOnlyList<DeleteResult> ReadResults(string file) =>
JsonSerializer.Deserialize<List<DeleteResult>>(File.ReadAllText(file), Json) ?? [];
Expand Down
11 changes: 9 additions & 2 deletions src/DiskSweeper.Core/Deletion/DeletionLog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@ public void Write(string action, string outcome, long bytes, string path, string
}
}

private static string Csv(string value) =>
value.IndexOfAny([',', '"', '\n', '\r']) < 0 ? value : "\"" + value.Replace("\"", "\"\"") + "\"";
private static string Csv(string value)
{
// A file name can start with =, +, - or @. Excel would treat that cell as a formula.
bool neutralize = value.Length > 0 && value[0] is '=' or '+' or '-' or '@' or '\t' or '\r';
if (neutralize) value = "'" + value;

if (!neutralize && value.IndexOfAny([',', '"', '\n', '\r']) < 0) return value;
return "\"" + value.Replace("\"", "\"\"") + "\"";
}
}
32 changes: 32 additions & 0 deletions src/DiskSweeper.Core/SmartFinds/AdviceCommands.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
namespace DiskSweeper.Core.SmartFinds;

/// <summary>
/// Which Cleanup advice commands DiskSweeper is willing to start. The rules file is compiled into the app,
/// and this keeps an edited or replaced command from opening an arbitrary program or a PowerShell payload.
/// Shell commands and executables are an exact list. Settings links and https links are allowed by shape.
/// </summary>
public static class AdviceCommands
{
private static readonly HashSet<string> KnownCommands = new(StringComparer.OrdinalIgnoreCase)
{
"powercfg /h off",
"DISM /Online /Cleanup-Image /StartComponentCleanup",
"SystemPropertiesPerformance.exe",
"SystemPropertiesProtection.exe",
};

public static bool IsAllowed(string? command)
{
if (string.IsNullOrWhiteSpace(command) || command.Length > 240 || command.Any(char.IsControl) || command.Contains('"') || command.Contains('\''))
return false;

if (KnownCommands.Contains(command)) return true;

if (!command.StartsWith("start ", StringComparison.OrdinalIgnoreCase)) return false;

string target = command[6..].Trim();
if (target.Length == 0 || target.Contains(' ')) return false;
return target.StartsWith("ms-settings:", StringComparison.OrdinalIgnoreCase)
|| target.StartsWith("https://", StringComparison.OrdinalIgnoreCase);
}
}
Loading
Loading