Skip to content
Draft
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: 13 additions & 3 deletions .github/workflows/windows-image-lock-experiment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,20 @@ jobs:
with:
dotnet-version: '10.0.x'
- name: Publish Native AOT experiment peer
run: dotnet publish tests/ReportWorker/ReportWorker.csproj -c Release -f net10.0 -r win-x64 -p:PublishAot=true -p:TargetFrameworks=net10.0 -o native-peer
- name: Test held image with native peer
run: dotnet publish tests/ReportWorker/ReportWorker.csproj -c Release -f net10.0 -r win-x64 -p:PublishAot=true -p:TargetFrameworks=net10.0 -p:DefineConstants=WINDOWS_SNAPSHOT_LAUNCH_EXPERIMENT -o native-peer
- name: Inspect static native dependencies
shell: pwsh
run: |
$vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
$vs = & $vswhere -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
if (-not $vs) { throw 'Visual C++ tools were not found' }
$tools = Get-ChildItem (Join-Path $vs 'VC\Tools\MSVC') -Directory | Sort-Object Name -Descending | Select-Object -First 1
$dumpbin = Join-Path $tools.FullName 'bin\Hostx64\x64\dumpbin.exe'
& $dumpbin /dependents (Join-Path $PWD 'native-peer\ReportWorker.exe')
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
- name: Test sharing and restricted inheritance with native peer
shell: pwsh
run: |
$env:GU_WINDOWS_NATIVE_LOCK_PEER = Join-Path $PWD 'native-peer\ReportWorker.exe'
dotnet test tests/CoreTest/CoreTest.csproj -c Release --filter "FullyQualifiedName~WindowsImageLockExperimentTests" --logger "console;verbosity=detailed"
dotnet test tests/CoreTest/CoreTest.csproj -c Release -p:DefineConstants=WINDOWS_SNAPSHOT_LAUNCH_EXPERIMENT --filter "FullyQualifiedName~WindowsImageLockExperimentTests|FullyQualifiedName~WindowsRestrictedInheritanceExperimentTests|FullyQualifiedName~WindowsDllSearchExperimentTests|FullyQualifiedName~WindowsJobLifetimeExperimentTests|FullyQualifiedName~WindowsAtomicSnapshotExperimentTests|FullyQualifiedName~WindowsImageSnapshotLeaseTests" --logger "console;verbosity=detailed"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
451 changes: 451 additions & 0 deletions src/GeneralUpdate.Core/Security/WindowsImageSnapshotLease.cs

Large diffs are not rendered by default.

354 changes: 354 additions & 0 deletions src/GeneralUpdate.Core/Security/WindowsNativeLaunchLease.cs

Large diffs are not rendered by default.

126 changes: 126 additions & 0 deletions tests/CoreTest/Ipc/WindowsAtomicSnapshotExperimentTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.AccessControl;
using System.Security.Principal;
using Microsoft.Win32.SafeHandles;

namespace CoreTest.Ipc;

/// <summary>Exercises atomic private-directory creation, not a protected updater launcher.</summary>
public sealed class WindowsAtomicSnapshotExperimentTests
{
[Fact]
public void AtomicCreateReturnsLockedPrivateObjectAndRejectsExistingName()
{
if (!OperatingSystem.IsWindows()) return;
RunExperiment();
}

[SupportedOSPlatform("windows")]
private static void RunExperiment()
{
var root = Path.Combine(Path.GetTempPath(), "gu-atomic-directory-" + Guid.NewGuid().ToString("N"));
var identity = WindowsIdentity.GetCurrent().User
?? throw new InvalidOperationException("The current user has no SID.");
var security = new DirectorySecurity();
security.SetOwner(identity);
security.SetAccessRuleProtection(true, false);
security.AddAccessRule(new FileSystemAccessRule(identity, FileSystemRights.FullControl,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None, AccessControlType.Allow));
new DirectoryInfo(root).Create(security);
try
{
using var parent = CreateFile(root, 0x80000000, 1, IntPtr.Zero, 3, 0x02200000, IntPtr.Zero);
if (parent.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error());
using var snapshot = CreateDirectoryRelative(parent, "snapshot", security, out var result, out var information);
Assert.Equal(0, result);
Assert.Equal(2, information.ToInt64());
Assert.False(snapshot.IsInvalid);
var path = Path.Combine(root, "snapshot");
var actual = new DirectoryInfo(path).GetAccessControl();
Assert.True(actual.AreAccessRulesProtected);
Assert.Equal(identity, actual.GetOwner(typeof(SecurityIdentifier)));
Assert.All(actual.GetAccessRules(true, true, typeof(SecurityIdentifier)).Cast<FileSystemAccessRule>(),
rule => Assert.Equal(identity, rule.IdentityReference));
Assert.Throws<IOException>(() => Directory.Move(path, path + ".moved"));
using var collision = CreateDirectoryRelative(parent, "snapshot", security, out var collisionResult, out _);
Assert.Equal(unchecked((int)0xc0000035), collisionResult);
}
finally
{
if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
}
}

[SupportedOSPlatform("windows")]
private static SafeFileHandle CreateDirectoryRelative(SafeFileHandle parent, string name, DirectorySecurity security,
out int result, out IntPtr information)
{
var nameBuffer = Marshal.StringToHGlobalUni(name);
var namePointer = Marshal.AllocHGlobal(Marshal.SizeOf<UnicodeString>());
var descriptorBytes = security.GetSecurityDescriptorBinaryForm();
var descriptor = Marshal.AllocHGlobal(descriptorBytes.Length);
try
{
Marshal.Copy(descriptorBytes, 0, descriptor, descriptorBytes.Length);
var unicode = new UnicodeString
{
Length = checked((ushort)(name.Length * 2)),
MaximumLength = checked((ushort)((name.Length + 1) * 2)),
Buffer = nameBuffer
};
Marshal.StructureToPtr(unicode, namePointer, false);
var attributes = new ObjectAttributes
{
Length = Marshal.SizeOf<ObjectAttributes>(),
RootDirectory = parent.DangerousGetHandle(),
ObjectName = namePointer,
Attributes = 0x40,
SecurityDescriptor = descriptor
};
result = NtCreateFile(out var handle, 0x00120081, ref attributes, out var status,
IntPtr.Zero, 0x80, 1, 2, 0x00200021, IntPtr.Zero, 0);
information = status.Information;
return handle;
}
finally
{
Marshal.FreeHGlobal(descriptor);
Marshal.FreeHGlobal(namePointer);
Marshal.FreeHGlobal(nameBuffer);
}
}

[StructLayout(LayoutKind.Sequential)]
private struct UnicodeString
{
public ushort Length, MaximumLength;
public IntPtr Buffer;
}

[StructLayout(LayoutKind.Sequential)]
private struct ObjectAttributes
{
public int Length;
public IntPtr RootDirectory, ObjectName;
public uint Attributes;
public IntPtr SecurityDescriptor, SecurityQualityOfService;
}

[StructLayout(LayoutKind.Sequential)]
private struct IoStatusBlock
{
public IntPtr Status, Information;
}

[DllImport("kernel32.dll", EntryPoint = "CreateFileW", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafeFileHandle CreateFile(string path, uint access, uint share, IntPtr security,
uint creation, uint flags, IntPtr template);

[DllImport("ntdll.dll")]
private static extern int NtCreateFile(out SafeFileHandle handle, uint access, ref ObjectAttributes attributes,
out IoStatusBlock status, IntPtr allocationSize, uint fileAttributes, uint share, uint disposition,
uint options, IntPtr extendedAttributes, uint extendedAttributesLength);
}
131 changes: 131 additions & 0 deletions tests/CoreTest/Ipc/WindowsDllSearchExperimentTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
using System.Diagnostics;
using System.Runtime.Versioning;

namespace CoreTest.Ipc;

/// <summary>Demonstrates loader search behavior, not a protected updater launcher.</summary>
public sealed class WindowsDllSearchExperimentTests
{
[Fact]
public async Task SanitizedPathDoesNotRestrictExplicitDllPaths()
{
if (!OperatingSystem.IsWindows()) return;
await RunExperiment();
}

[Fact]
public async Task NativeAotSqliteUsesAdjacentDependencyAndFailsWhenItIsMissing()
{
if (!OperatingSystem.IsWindows()) return;
var executable = Environment.GetEnvironmentVariable("GU_WINDOWS_NATIVE_LOCK_PEER");
if (executable == null) return;
await RunSqliteExperiment(executable);
}

[SupportedOSPlatform("windows")]
private static async Task RunSqliteExperiment(string executable)
{
var root = Path.Combine(Path.GetTempPath(), "gu-sqlite-search-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(root);
try
{
var adjacent = await RunSqlitePeer(executable, root);
Assert.True(adjacent.ExitCode == 0, adjacent.Error);
Assert.Equal(Path.Combine(Path.GetDirectoryName(executable)!, "e_sqlite3.dll"),
adjacent.Output.Trim(), ignoreCase: true);

var isolated = Path.Combine(root, "peer.exe");
File.Copy(executable, isolated);
var missing = await RunSqlitePeer(isolated, root);
Assert.NotEqual(0, missing.ExitCode);
Assert.Contains("e_sqlite3", missing.Error + missing.Output, StringComparison.OrdinalIgnoreCase);
}
finally
{
Directory.Delete(root, recursive: true);
}
}

private static async Task<(int ExitCode, string Output, string Error)> RunSqlitePeer(string executable, string directory)
{
var start = new ProcessStartInfo(executable)
{
UseShellExecute = false,
WorkingDirectory = directory,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
start.Environment["PATH"] = Environment.SystemDirectory;
start.ArgumentList.Add("--sqlite-module-probe");
using var peer = Process.Start(start) ?? throw new InvalidOperationException("SQLite probe did not start.");
var output = peer.StandardOutput.ReadToEndAsync();
var error = peer.StandardError.ReadToEndAsync();
try
{
await peer.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(30));
return (peer.ExitCode, await output, await error);
}
finally
{
if (!peer.HasExited) peer.Kill(entireProcessTree: true);
await peer.WaitForExitAsync();
}
}

[SupportedOSPlatform("windows")]
private static async Task RunExperiment()
{
var root = Path.Combine(Path.GetTempPath(), "gu-dll-search-" + Guid.NewGuid().ToString("N"));
var injection = Path.Combine(root, "injection");
var workingDirectory = Path.Combine(root, "working");
Directory.CreateDirectory(injection);
Directory.CreateDirectory(workingDirectory);
try
{
var source = Path.Combine(AppContext.BaseDirectory, "runtimes", "win-x64", "native", "e_sqlite3.dll");
var name = "gu_probe_" + Guid.NewGuid().ToString("N") + ".dll";
var candidate = Path.Combine(injection, name);
File.Copy(source, candidate);
var executable = Environment.GetEnvironmentVariable("GU_WINDOWS_NATIVE_LOCK_PEER")
?? Path.Combine(AppContext.BaseDirectory, "ReportWorker.exe");

Assert.Equal("loaded", await RunPeer(executable, workingDirectory, injection, name));
Assert.Equal("error:126", await RunPeer(executable, workingDirectory, Environment.SystemDirectory, name));
Assert.Equal("loaded", await RunPeer(executable, workingDirectory, Environment.SystemDirectory, candidate));
}
finally
{
Directory.Delete(root, recursive: true);
}
}

private static async Task<string?> RunPeer(string executable, string workingDirectory, string path, string dll)
{
var start = new ProcessStartInfo(executable)
{
UseShellExecute = false,
WorkingDirectory = workingDirectory,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
start.Environment["PATH"] = path;
start.ArgumentList.Add("--dll-search-probe");
start.ArgumentList.Add(dll);
using var peer = Process.Start(start) ?? throw new InvalidOperationException("DLL search probe did not start.");
var output = peer.StandardOutput.ReadToEndAsync();
var error = peer.StandardError.ReadToEndAsync();
try
{
await peer.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(30));
Assert.True(peer.ExitCode == 0, await error);
return (await output).Trim();
}
finally
{
if (!peer.HasExited) peer.Kill(entireProcessTree: true);
await peer.WaitForExitAsync();
}
}
}
Loading
Loading