-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
453 lines (423 loc) · 27 KB
/
Copy pathProgram.cs
File metadata and controls
453 lines (423 loc) · 27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
using System.IO.Compression;
using System.IO;
using Microsoft.Win32;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Xml;
using System.Xml.Linq;
namespace DarksFIDO2.Setup;
internal static class Program
{
private const string AppName = "Darks FIDO2";
private static readonly string InstallDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "DarksFIDO2");
private static readonly string LegacyInstallDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "DarksFIDO2");
private static readonly string StartMenuDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu), "Programs", "Darks FIDO2");
private static readonly string DesktopShortcut = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "Darks FIDO2.lnk");
[STAThread]
private static int Main(string[] args)
{
try
{
if (args.Contains("--uninstall-silent", StringComparer.OrdinalIgnoreCase)) return Uninstall(silent: true);
if (args.Contains("--uninstall", StringComparer.OrdinalIgnoreCase)) return Uninstall(silent: false);
return Install(args.Contains("--install-silent", StringComparer.OrdinalIgnoreCase));
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("Setup stopped safely:\n\n" + ex.Message, "Darks FIDO2 Setup", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
return 1;
}
}
private static int Install(bool silent)
{
if (!silent && System.Windows.MessageBox.Show("Install Darks FIDO2 and its Windows virtual passkey provider?\n\nSetup never adds certificates to a trusted store. Windows will install the provider only when its existing signature chain is already trusted.", "Darks FIDO2 Setup", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Question) != System.Windows.MessageBoxResult.Yes)
return 2;
using Stream payload = typeof(Program).Assembly.GetManifestResourceStream("DarksFIDO2.Payload.zip")
?? throw new InvalidOperationException("The portable application payload is missing from this setup file.");
string staging = Path.Combine(Path.GetTempPath(), "DarksFIDO2-Setup-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(staging);
string? rollbackDirectory = null;
bool previousInstallExisted = false;
try
{
string archive = Path.Combine(staging, "payload.zip");
using (var output = File.Create(archive)) payload.CopyTo(output);
string extracted = Path.Combine(staging, "app");
ValidateArchive(archive, extracted);
ZipFile.ExtractToDirectory(archive, extracted, overwriteFiles: true);
VerifyExtractedPayload(extracted);
StopInstalledProcesses();
previousInstallExisted = Directory.Exists(InstallDirectory);
if (previousInstallExisted)
{
rollbackDirectory = InstallDirectory + ".rollback-" + Guid.NewGuid().ToString("N");
Directory.Move(InstallDirectory, rollbackDirectory);
}
try
{
Directory.CreateDirectory(InstallDirectory);
foreach (string directory in Directory.GetDirectories(extracted, "*", SearchOption.AllDirectories))
Directory.CreateDirectory(Path.Combine(InstallDirectory, Path.GetRelativePath(extracted, directory)));
foreach (string file in Directory.GetFiles(extracted, "*", SearchOption.AllDirectories))
File.Copy(file, Path.Combine(InstallDirectory, Path.GetRelativePath(extracted, file)), overwrite: true);
string portableMarker = Path.Combine(InstallDirectory, "portable.mode");
if (File.Exists(portableMarker)) File.Delete(portableMarker);
string uninstallPath = Path.Combine(InstallDirectory, "Uninstall Darks FIDO2.exe");
File.Copy(Environment.ProcessPath!, uninstallPath, overwrite: true);
Directory.CreateDirectory(StartMenuDirectory);
CreateShortcut(Path.Combine(StartMenuDirectory, "Darks FIDO2.lnk"), Path.Combine(InstallDirectory, "DarksFIDO2.exe"), InstallDirectory);
CreateShortcut(DesktopShortcut, Path.Combine(InstallDirectory, "DarksFIDO2.exe"), InstallDirectory);
CreateShortcut(Path.Combine(StartMenuDirectory, "Uninstall Darks FIDO2.lnk"), uninstallPath, InstallDirectory, "--uninstall");
WriteUninstallEntry(uninstallPath);
string? rollbackProviderPackage = rollbackDirectory is null
? null
: Path.Combine(rollbackDirectory, "DarksFIDO2.Provider.msix");
InstallProviderPackage(staging, rollbackProviderPackage);
}
catch
{
try { DeleteTreeWithoutFollowingReparsePoints(InstallDirectory); } catch { }
if (rollbackDirectory is not null && Directory.Exists(rollbackDirectory))
{
Directory.Move(rollbackDirectory, InstallDirectory);
RestoreShellIntegration();
}
else
{
try { File.Delete(DesktopShortcut); } catch { }
try { Directory.Delete(StartMenuDirectory, recursive: true); } catch { }
try { Registry.CurrentUser.DeleteSubKeyTree(@"Software\Microsoft\Windows\CurrentVersion\Uninstall\DarksFIDO2", throwOnMissingSubKey: false); } catch { }
}
throw;
}
if (rollbackDirectory is not null)
{
try { DeleteTreeWithoutFollowingReparsePoints(rollbackDirectory); } catch { }
rollbackDirectory = null;
}
try { DeleteTreeWithoutFollowingReparsePoints(LegacyInstallDirectory); } catch { }
}
finally
{
try { Directory.Delete(staging, recursive: true); } catch { }
if (!previousInstallExisted && rollbackDirectory is not null)
{
try { DeleteTreeWithoutFollowingReparsePoints(rollbackDirectory); } catch { }
}
}
if (!silent)
{
System.Windows.MessageBox.Show("Darks FIDO2 is installed. To use it as a virtual passkey for Google and other sites, enable Darks FIDO2 once in Settings > Accounts > Passkeys > Advanced options.", "Darks FIDO2 Setup", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(Path.Combine(InstallDirectory, "DarksFIDO2.exe")) { UseShellExecute = true, WorkingDirectory = InstallDirectory });
}
return 0;
}
private static void StopInstalledProcesses()
{
if (!Directory.Exists(InstallDirectory)) return;
string installRoot = Path.GetFullPath(InstallDirectory).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
foreach (string processName in new[] { "DarksFIDO2", "darksfido-cli", "DarksFIDO2.Provider" })
{
foreach (System.Diagnostics.Process process in System.Diagnostics.Process.GetProcessesByName(processName))
{
using (process)
{
string? executable;
try { executable = process.MainModule?.FileName; }
catch { continue; }
if (string.IsNullOrWhiteSpace(executable) ||
!Path.GetFullPath(executable).StartsWith(installRoot, StringComparison.OrdinalIgnoreCase))
continue;
try
{
if (process.CloseMainWindow()) process.WaitForExit(5_000);
if (!process.HasExited)
{
process.Kill(entireProcessTree: true);
if (!process.WaitForExit(10_000))
throw new InvalidOperationException("The running Darks FIDO2 process did not stop.");
}
}
catch (InvalidOperationException) when (process.HasExited) { }
}
}
}
}
private static int Uninstall(bool silent)
{
if (!silent && System.Windows.MessageBox.Show("Uninstall Darks FIDO2?\n\nEncrypted profiles in LocalAppData\\DarksFIDO2 are preserved so they are not destroyed accidentally.", "Uninstall Darks FIDO2", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Warning) != System.Windows.MessageBoxResult.Yes)
return 2;
try
{
string provider = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft", "WindowsApps", "darksfido2-provider.exe");
if (File.Exists(provider))
{
using var removal = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(provider, "--unregister") { UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = InstallDirectory });
removal?.WaitForExit(30_000);
}
}
catch { }
try { RunPowerShell("Get-AppxPackage -Name 'DarksFIDO2.Provider' | Remove-AppxPackage", 60_000); } catch { }
try { File.Delete(DesktopShortcut); } catch { }
try { Directory.Delete(StartMenuDirectory, recursive: true); } catch { }
try { Registry.CurrentUser.DeleteSubKeyTree(@"Software\Microsoft\Windows\CurrentVersion\Uninstall\DarksFIDO2", throwOnMissingSubKey: false); } catch { }
string self = Environment.ProcessPath!;
DeleteTreeWithoutFollowingReparsePoints(InstallDirectory, self);
MoveFileEx(self, null, 4);
MoveFileEx(InstallDirectory, null, 4);
if (!silent) System.Windows.MessageBox.Show("Darks FIDO2 was uninstalled. Its encrypted profile data was preserved.", "Uninstall Darks FIDO2", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
return 0;
}
private static void WriteUninstallEntry(string uninstallPath)
{
string version = typeof(Program).Assembly.GetName().Version?.ToString(3) ?? "Unknown";
try
{
string? detected = System.Diagnostics.FileVersionInfo.GetVersionInfo(Path.Combine(InstallDirectory, "DarksFIDO2.exe")).ProductVersion;
if (Version.TryParse(detected?.Split('+')[0], out Version? parsed)) version = parsed.ToString(3);
}
catch { }
using RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall\DarksFIDO2", writable: true);
key.SetValue("DisplayName", AppName);
key.SetValue("DisplayVersion", version);
key.SetValue("Publisher", "Darks FIDO2 Project");
key.SetValue("InstallLocation", InstallDirectory);
key.SetValue("DisplayIcon", Path.Combine(InstallDirectory, "DarksFIDO2.exe"));
key.SetValue("UninstallString", '"' + uninstallPath + "\" --uninstall");
key.SetValue("NoModify", 1, RegistryValueKind.DWord);
key.SetValue("NoRepair", 1, RegistryValueKind.DWord);
}
private static void RestoreShellIntegration()
{
string executable = Path.Combine(InstallDirectory, "DarksFIDO2.exe");
string uninstallPath = Path.Combine(InstallDirectory, "Uninstall Darks FIDO2.exe");
if (!File.Exists(executable) || !File.Exists(uninstallPath)) return;
Directory.CreateDirectory(StartMenuDirectory);
CreateShortcut(Path.Combine(StartMenuDirectory, "Darks FIDO2.lnk"), executable, InstallDirectory);
CreateShortcut(DesktopShortcut, executable, InstallDirectory);
CreateShortcut(Path.Combine(StartMenuDirectory, "Uninstall Darks FIDO2.lnk"), uninstallPath, InstallDirectory, "--uninstall");
WriteUninstallEntry(uninstallPath);
}
private static void CreateShortcut(string shortcutPath, string targetPath, string workingDirectory, string arguments = "")
{
Type type = Type.GetTypeFromProgID("WScript.Shell") ?? throw new InvalidOperationException("Windows shortcut service is unavailable.");
dynamic shell = Activator.CreateInstance(type)!;
dynamic shortcut = shell.CreateShortcut(shortcutPath);
shortcut.TargetPath = targetPath;
shortcut.WorkingDirectory = workingDirectory;
shortcut.Arguments = arguments;
shortcut.Description = "Secure local FIDO2, TPM, and TOTP manager";
shortcut.Save();
}
private static void InstallProviderPackage(string staging, string? rollbackPackagePath)
{
string packagePath = Path.Combine(staging, "DarksFIDO2.Provider.msix");
using (Stream package = typeof(Program).Assembly.GetManifestResourceStream("DarksFIDO2.Provider.msix")
?? throw new InvalidOperationException("The virtual passkey provider package is missing."))
using (FileStream output = File.Create(packagePath)) package.CopyTo(output);
File.Copy(packagePath, Path.Combine(InstallDirectory, "DarksFIDO2.Provider.msix"), overwrite: true);
Version packageVersion = ReadProviderPackageVersion(packagePath);
ProviderPackageState? previous = ReadInstalledProviderState();
string escapedPackage = packagePath.Replace("'", "''");
bool packageChanged = previous is null || previous.ParsedVersion < packageVersion;
try
{
RunPowerShell($"$existing=Get-AppxPackage -Name 'DarksFIDO2.Provider'; if (!$existing -or [version]$existing.Version -lt [version]'{packageVersion}') {{ Add-AppxPackage -Path '{escapedPackage}' -ForceApplicationShutdown }}", 120_000);
string alias = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft", "WindowsApps", "darksfido2-provider.exe");
if (!File.Exists(alias)) throw new InvalidOperationException("Windows did not publish the passkey provider execution alias.");
using System.Diagnostics.Process registration = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(alias, "--register") { UseShellExecute = false, CreateNoWindow = true })
?? throw new InvalidOperationException("Unable to register the virtual passkey provider.");
if (!registration.WaitForExit(30_000)) { registration.Kill(true); throw new TimeoutException("Virtual passkey registration timed out."); }
if (registration.ExitCode != 0 && registration.ExitCode != unchecked((int)0x8009000F))
throw new InvalidOperationException($"Windows rejected virtual passkey registration (0x{registration.ExitCode:X8}).");
}
catch
{
if (packageChanged) RollBackProviderPackage(previous, rollbackPackagePath);
throw;
}
}
private static ProviderPackageState? ReadInstalledProviderState()
{
string json = RunPowerShellCapture(
"$p=Get-AppxPackage -Name 'DarksFIDO2.Provider' | Sort-Object Version -Descending | Select-Object -First 1;" +
"if($p){[pscustomobject]@{PackageFullName=$p.PackageFullName;Version=$p.Version.ToString()}|ConvertTo-Json -Compress}",
30_000);
if (string.IsNullOrWhiteSpace(json)) return null;
ProviderPackageState? state = JsonSerializer.Deserialize<ProviderPackageState>(json);
return state is not null && Version.TryParse(state.Version, out _) ? state : null;
}
private static void RollBackProviderPackage(ProviderPackageState? previous, string? rollbackPackagePath)
{
bool canRestorePrevious = previous is not null &&
!string.IsNullOrWhiteSpace(rollbackPackagePath) &&
File.Exists(rollbackPackagePath);
if (previous is not null && !canRestorePrevious) return;
try
{
RunPowerShell("Get-AppxPackage -Name 'DarksFIDO2.Provider' | Remove-AppxPackage", 60_000);
if (canRestorePrevious)
{
string escaped = rollbackPackagePath!.Replace("'", "''");
RunPowerShell($"Add-AppxPackage -Path '{escaped}' -ForceApplicationShutdown", 120_000);
string alias = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft", "WindowsApps", "darksfido2-provider.exe");
if (File.Exists(alias))
{
using System.Diagnostics.Process? registration = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(alias, "--register") { UseShellExecute = false, CreateNoWindow = true });
registration?.WaitForExit(30_000);
}
}
}
catch
{
// Preserve the installation error. The application-file transaction still
// restores the previous desktop installation.
}
}
private static Version ReadProviderPackageVersion(string packagePath)
{
using ZipArchive archive = ZipFile.OpenRead(packagePath);
ZipArchiveEntry manifest = archive.GetEntry("AppxManifest.xml")
?? throw new InvalidOperationException("The provider package manifest is missing.");
if (manifest.Length is < 1 or > 1024 * 1024)
throw new InvalidOperationException("The provider package manifest has an invalid size.");
using Stream stream = manifest.Open();
using XmlReader reader = XmlReader.Create(stream, new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Prohibit,
XmlResolver = null,
MaxCharactersInDocument = 1024 * 1024
});
XDocument document = XDocument.Load(reader, LoadOptions.None);
XNamespace ns = document.Root?.Name.Namespace
?? throw new InvalidOperationException("The provider package manifest is invalid.");
string? value = document.Root?.Element(ns + "Identity")?.Attribute("Version")?.Value;
if (!Version.TryParse(value, out Version? version) || version.Major < 0 || version.Minor < 0 ||
version.Build < 0 || version.Revision < 0)
throw new InvalidOperationException("The provider package version is invalid.");
return version;
}
private static void RunPowerShell(string command, int timeout)
{
string encoded = Convert.ToBase64String(Encoding.Unicode.GetBytes("$ErrorActionPreference='Stop';" + command));
using System.Diagnostics.Process process = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("powershell.exe", $"-NoProfile -ExecutionPolicy Bypass -EncodedCommand {encoded}") { UseShellExecute = false, CreateNoWindow = true })
?? throw new InvalidOperationException("Unable to start Windows package deployment.");
if (!process.WaitForExit(timeout)) { process.Kill(true); throw new TimeoutException("Windows package deployment timed out."); }
if (process.ExitCode != 0) throw new InvalidOperationException("Windows package deployment failed.");
}
private static string RunPowerShellCapture(string command, int timeout)
{
string encoded = Convert.ToBase64String(Encoding.Unicode.GetBytes("$ErrorActionPreference='Stop';" + command));
using System.Diagnostics.Process process = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("powershell.exe", $"-NoProfile -ExecutionPolicy Bypass -EncodedCommand {encoded}")
{
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true
}) ?? throw new InvalidOperationException("Unable to inspect Windows package deployment.");
string output = process.StandardOutput.ReadToEnd();
_ = process.StandardError.ReadToEnd();
if (!process.WaitForExit(timeout)) { process.Kill(true); throw new TimeoutException("Windows package inspection timed out."); }
if (process.ExitCode != 0) throw new InvalidOperationException("Windows package inspection failed.");
return output.Trim();
}
private static void VerifyExtractedPayload(string root)
{
string manifestPath = Path.Combine(root, "integrity.sha256.json");
if (!File.Exists(manifestPath) || new FileInfo(manifestPath).Length > 1024 * 1024)
throw new CryptographicException("The signed payload integrity manifest is missing or invalid.");
byte[] manifestBytes = File.ReadAllBytes(manifestPath);
ReadOnlySpan<byte> manifestJson = manifestBytes;
if (manifestJson.StartsWith(new byte[] { 0xEF, 0xBB, 0xBF })) manifestJson = manifestJson[3..];
Dictionary<string, string> manifest = JsonSerializer.Deserialize<Dictionary<string, string>>(manifestJson)
?? throw new CryptographicException("The signed payload integrity manifest is invalid.");
if (manifest.Count is < 3 or > 10_000) throw new CryptographicException("The payload manifest contains an invalid number of files.");
string canonicalRoot = Path.GetFullPath(root) + Path.DirectorySeparatorChar;
var expected = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach ((string relative, string expectedHash) in manifest)
{
if (string.IsNullOrWhiteSpace(relative) || relative.Length > 1_024 || expectedHash.Length != 64 ||
Path.IsPathRooted(relative) || relative.Split('/', '\\').Any(part => part is "" or "." or ".."))
throw new CryptographicException("The payload manifest contains an unsafe path.");
string fullPath = Path.GetFullPath(Path.Combine(root, relative.Replace('/', Path.DirectorySeparatorChar)));
if (!fullPath.StartsWith(canonicalRoot, StringComparison.OrdinalIgnoreCase) ||
!File.Exists(fullPath) || (File.GetAttributes(fullPath) & FileAttributes.ReparsePoint) != 0)
throw new CryptographicException("The payload is incomplete or contains an unsafe link.");
byte[] actualHash;
using (FileStream file = File.OpenRead(fullPath)) actualHash = SHA256.HashData(file);
byte[] wantedHash = Convert.FromHexString(expectedHash);
if (!CryptographicOperations.FixedTimeEquals(actualHash, wantedHash))
throw new CryptographicException("The signed application payload failed integrity verification.");
CryptographicOperations.ZeroMemory(actualHash);
CryptographicOperations.ZeroMemory(wantedHash);
expected.Add(Path.GetRelativePath(root, fullPath).Replace('\\', '/'));
}
foreach (string file in Directory.GetFiles(root, "*", SearchOption.AllDirectories))
{
string relative = Path.GetRelativePath(root, file).Replace('\\', '/');
if (!relative.Equals("integrity.sha256.json", StringComparison.OrdinalIgnoreCase) && !expected.Contains(relative))
throw new CryptographicException("The payload contains an unlisted file.");
}
}
private static void ValidateArchive(string archivePath, string extractionRoot)
{
using ZipArchive archive = ZipFile.OpenRead(archivePath);
if (archive.Entries.Count is < 3 or > 10_000) throw new InvalidDataException("The application payload has an invalid entry count.");
string canonicalRoot = Path.GetFullPath(extractionRoot) + Path.DirectorySeparatorChar;
long totalLength = 0;
var paths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (ZipArchiveEntry entry in archive.Entries)
{
if (entry.FullName.Length > 1_024 || entry.Length > 512L * 1024 * 1024 ||
entry.Length > 0 && entry.CompressedLength == 0 ||
entry.CompressedLength > 0 && entry.Length / Math.Max(1, entry.CompressedLength) > 1_000)
throw new InvalidDataException("The application payload contains an unsafe archive entry.");
totalLength = checked(totalLength + entry.Length);
if (totalLength > 1024L * 1024 * 1024) throw new InvalidDataException("The application payload exceeds the extraction safety limit.");
string fullPath = Path.GetFullPath(Path.Combine(extractionRoot, entry.FullName.Replace('/', Path.DirectorySeparatorChar)));
if (!fullPath.StartsWith(canonicalRoot, StringComparison.OrdinalIgnoreCase) || !paths.Add(fullPath))
throw new InvalidDataException("The application payload contains an unsafe or duplicate path.");
}
}
private static void DeleteTreeWithoutFollowingReparsePoints(string root, string? preserveFile = null)
{
string fullRoot = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar);
string expectedRoot = Path.GetFullPath(InstallDirectory).TrimEnd(Path.DirectorySeparatorChar);
string legacyRoot = Path.GetFullPath(LegacyInstallDirectory).TrimEnd(Path.DirectorySeparatorChar);
bool rollbackRoot = string.Equals(Path.GetDirectoryName(fullRoot), Path.GetDirectoryName(expectedRoot), StringComparison.OrdinalIgnoreCase) &&
Path.GetFileName(fullRoot).StartsWith(Path.GetFileName(expectedRoot) + ".rollback-", StringComparison.OrdinalIgnoreCase);
if ((!fullRoot.Equals(expectedRoot, StringComparison.OrdinalIgnoreCase) &&
!fullRoot.Equals(legacyRoot, StringComparison.OrdinalIgnoreCase) &&
!rollbackRoot) || !Directory.Exists(fullRoot)) return;
if ((File.GetAttributes(fullRoot) & FileAttributes.ReparsePoint) != 0)
{
Directory.Delete(fullRoot, recursive: false);
return;
}
DeleteContents(fullRoot, preserveFile is null ? null : Path.GetFullPath(preserveFile));
if (preserveFile is null) Directory.Delete(fullRoot, recursive: false);
}
private sealed class ProviderPackageState
{
public string PackageFullName { get; set; } = "";
public string Version { get; set; } = "";
[System.Text.Json.Serialization.JsonIgnore]
public Version ParsedVersion => System.Version.Parse(Version);
}
private static void DeleteContents(string directory, string? preserveFile)
{
foreach (string entry in Directory.GetFileSystemEntries(directory))
{
string full = Path.GetFullPath(entry);
if (preserveFile is not null && full.Equals(preserveFile, StringComparison.OrdinalIgnoreCase)) continue;
FileAttributes attributes = File.GetAttributes(full);
if ((attributes & FileAttributes.Directory) == 0) { try { File.Delete(full); } catch { } continue; }
if ((attributes & FileAttributes.ReparsePoint) != 0) { try { Directory.Delete(full, recursive: false); } catch { } continue; }
DeleteContents(full, preserveFile);
try { Directory.Delete(full, recursive: false); } catch { }
}
}
[System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
private static extern bool MoveFileEx(string existingFileName, string? newFileName, int flags);
}