diff --git a/.github/workflows/windows-protected-launch.yml b/.github/workflows/windows-protected-launch.yml new file mode 100644 index 00000000..1c840502 --- /dev/null +++ b/.github/workflows/windows-protected-launch.yml @@ -0,0 +1,25 @@ +name: Windows protected launch + +on: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + native-aot: + runs-on: windows-latest + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-dotnet@v5 + with: + dotnet-version: '10.0.x' + - name: Publish cooperative Native AOT peer + run: dotnet publish tests/NativeSnapshotWorker/NativeSnapshotWorker.csproj -c Release -f net10.0 -r win-x64 -p:PublishAot=true -p:TargetFrameworks=net10.0 -o native-snapshot-peer + - name: Exercise snapshot and process ownership + shell: pwsh + run: | + $env:GU_WINDOWS_SNAPSHOT_PEER = Join-Path $PWD 'native-snapshot-peer\NativeSnapshotWorker.exe' + dotnet test tests/CoreTest/CoreTest.csproj -c Release --filter "FullyQualifiedName~WindowsImageSnapshotLeaseTests" --logger "console;verbosity=detailed" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } diff --git a/docs/windows-protected-launch.md b/docs/windows-protected-launch.md new file mode 100644 index 00000000..a5d13d89 --- /dev/null +++ b/docs/windows-protected-launch.md @@ -0,0 +1,68 @@ +# Windows protected native launch + +`WindowsNativeLaunchLease` is an opt-in primitive, not an authenticated channel +or an updater integration. It is available on .NET 8 and later and requires +Windows 10 version 2004 or later and local fixed NTFS paths. Other platforms +fail closed. The default profile is disabled; the host must explicitly select +`TrustedWindowsSystemAndCooperativeNativeAot`. + +The host must pin the absolute source executable path and SHA-256, explicitly +list every required application DLL name in a separately audited manifest and +provide exactly one pinned dependency file for each name, provide an explicit +list of names that the deployer has established are trusted Windows system +modules, and provide an absolute staging parent. The launcher checks normal and +delay import names in the staged native PE files against these lists and rejects +forwarded application exports. The system-name list is a deployer assertion, +not proof that a file in System32 is a Windows component. The host must also +audit application SxS manifests and the peer's runtime loading behavior. +An application name cannot also be classified as a system name. The host must +audit both lists for the exact peer; omitting an application name from both the +manifest and the files, or falsely classifying it as a system name, cannot be +detected from names alone. The system list must not be generated by treating +unknown imports as system imports. +Source directories and files are checked and leased while +copying. The launcher atomically creates a new private protected-DACL directory, +copies only the authorized files, checks the staged bytes, and holds the staged +objects and their namespace until the owned job is stopped. An existing writer +or delete handle to a source file makes acquisition fail. Normal deployment can +replace a source after its copy is complete; it does not change the snapshot. +Directory sharing does not freeze directory contents or security descriptors. + +The selected profile **trusts the Windows loader, API-set and SxS resolution, +and system DLLs**. The deployer must ensure untrusted users have not retained +write, delete, WRITE_DAC or WRITE_OWNER capabilities to those system objects. +This historical condition is not established by this API, a System32 path, +signatures, or repeated ACL checks. It does not extend to application DLLs. +The host must authorize the exact Native AOT peer hash and its cooperative +entry-point contract: before processing sensitive input, the peer restricts +DLL searches to its snapshot and trusted Windows system directories and loads +application dependencies by their absolute staged paths. It must not depend on +an application assembly supplied through an unaudited SxS manifest. This is not a sandbox: +trusted peer code can deliberately load other paths. + +The process starts suspended in a creation-time kill-on-close job, with no +inherited handles, then is resumed only after job membership is confirmed. +`DuplicateProcessHandle` returns an independently disposable query/synchronize +handle to the actual process; it does not authenticate the peer. Keep the +launch lease alive for the entire required operation and dispose duplicated +process handles when no longer needed. +`WaitForExitAsync` +returns the exit code; cancellation terminates the job and releases the lease. +`DisposeAsync` terminates the job, waits for its processes to exit, and attempts +identity-checked, non-recursive cleanup. Cleanup failures are reported. +The lease remains rooted until disposal; neglecting it retains resources. + +The executable path, working directory and `AppContext.BaseDirectory` are in +staging, not the original installation. The host must provide installation +context separately; applications depending on relative paths must be adapted. +Each launch uses disk space for a full copy. Failed creation, a crash or a +failed cleanup can leave protected staging files; no crash recovery is provided. +Cleanup must never delete a replacement by path. Parent termination closes the +job, but does not guarantee immediate cleanup. + +This boundary excludes malicious processes running as the same Windows user and +administrators. It does not claim kernel image-section identity, prevent all +behavior of the authorized program, authenticate either peer, or replace a +later handshake and endpoint authorization. Do not pass credentials or nonces +in arguments, environment variables, files or logs. No Client/Updater wiring, +IPC or credential transfer is provided. diff --git a/src/GeneralUpdate.Core/Security/WindowsImageSnapshotLease.cs b/src/GeneralUpdate.Core/Security/WindowsImageSnapshotLease.cs new file mode 100644 index 00000000..468deff0 --- /dev/null +++ b/src/GeneralUpdate.Core/Security/WindowsImageSnapshotLease.cs @@ -0,0 +1,463 @@ +#if NET8_0_OR_GREATER +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using System.Security.AccessControl; +using System.Security.Cryptography; +using System.Security.Principal; +using System.Threading; +using Microsoft.Win32.SafeHandles; + +namespace GeneralUpdate.Core.Security; + +/// A host-authorized file to copy into a Windows execution snapshot. +public sealed class WindowsSnapshotFile +{ + public WindowsSnapshotFile(string sourcePath, byte[] sha256) + { + SourcePath = sourcePath ?? throw new ArgumentNullException(nameof(sourcePath)); + if (sha256 == null || sha256.Length != 32) throw new ArgumentException("A SHA256 digest is required.", nameof(sha256)); + Sha256 = (byte[])sha256.Clone(); + } + + public string SourcePath { get; } + internal byte[] Sha256 { get; } +} + +/// +/// Keeps a private, hash-verified Windows file snapshot and its ancestor handles open. +/// This object does not launch or authenticate a process. +/// +public sealed class WindowsImageSnapshotLease : IDisposable +{ + private readonly List _handles; + private readonly SafeFileHandle _parent; + private readonly SafeFileHandle _directory; + private readonly string _directoryName; + private readonly List<(string Name, SafeFileHandle Handle)> _files; + private int _disposed; + + private WindowsImageSnapshotLease(string directory, string image, List handles, + SafeFileHandle parent, SafeFileHandle directoryHandle, string directoryName, + List<(string Name, SafeFileHandle Handle)> files) + { + DirectoryPath = directory; + ImagePath = image; + _handles = handles; + _parent = parent; + _directory = directoryHandle; + _directoryName = directoryName; + _files = files; + } + + public string DirectoryPath { get; } + public string ImagePath { get; } + + /// + /// Creates a new protected snapshot. The feature is disabled unless explicitly enabled. + /// The caller must separately establish a controlled launch and a trusted peer contract. + /// Cleanup uses relative handles and verifies object identities before deletion. + /// + public static WindowsImageSnapshotLease Create(bool enabled, string snapshotParent, + WindowsSnapshotFile image, IReadOnlyList dependencies, + CancellationToken cancellationToken = default) + { + if (!OperatingSystem.IsWindows()) throw new PlatformNotSupportedException("Windows is required."); + if (!enabled) throw new InvalidOperationException("Windows image snapshots are disabled."); + if (snapshotParent == null) throw new ArgumentNullException(nameof(snapshotParent)); + if (image == null) throw new ArgumentNullException(nameof(image)); + if (dependencies == null) throw new ArgumentNullException(nameof(dependencies)); + return CreateWindows(snapshotParent, image, dependencies, cancellationToken); + } + + [SupportedOSPlatform("windows")] + private static WindowsImageSnapshotLease CreateWindows(string snapshotParent, WindowsSnapshotFile image, + IReadOnlyList dependencies, CancellationToken cancellationToken) + { + var user = WindowsIdentity.GetCurrent().User + ?? throw new InvalidOperationException("The current user has no SID."); + var parentPath = ValidatePath(snapshotParent); + var files = new List { image }; + files.AddRange(dependencies); + var names = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var file in files) + { + if (file == null) throw new ArgumentException("A dependency is null.", nameof(dependencies)); + var source = ValidatePath(file.SourcePath); + var name = Path.GetFileName(source); + if (!names.Add(name)) throw new ArgumentException("Snapshot file names must be distinct.", nameof(dependencies)); + if (ReferenceEquals(file, image)) + { + if (!name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException("The image must be an executable.", nameof(image)); + } + else if (!name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException("Dependencies must be DLL files.", nameof(dependencies)); + } + + var leases = new List(); + var heldFiles = new List<(string Name, SafeFileHandle Handle)>(); + try + { + cancellationToken.ThrowIfCancellationRequested(); + var parent = LockAncestors(parentPath, user, leases); + var directorySecurity = new DirectorySecurity(); + directorySecurity.SetOwner(user); + directorySecurity.SetAccessRuleProtection(true, false); + directorySecurity.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.FullControl, + InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, + PropagationFlags.None, AccessControlType.Allow)); + var directoryName = "gu-snapshot-" + Guid.NewGuid().ToString("N"); + var snapshot = CreateRelative(parent, directoryName, directorySecurity, directory: true, write: true); + leases.Add(snapshot); + ValidateHandle(snapshot, user, directory: true, ancestor: false, privateSnapshot: true); + var directoryPath = Path.Combine(parentPath, directoryName); + + foreach (var file in files) + { + cancellationToken.ThrowIfCancellationRequested(); + CopyVerifiedFile(file, snapshot, user, leases, heldFiles, cancellationToken); + } + var heldDirectory = NtOpenRelative(parent, directoryName, null, directory: true, write: false, create: false, share: 3); + try + { + if (!GetFileInformationByHandle(snapshot, out var created) || + !GetFileInformationByHandle(heldDirectory, out var held)) + throw new Win32Exception(Marshal.GetLastWin32Error()); + if (created.VolumeSerialNumber != held.VolumeSerialNumber || + created.FileIndexHigh != held.FileIndexHigh || created.FileIndexLow != held.FileIndexLow) + throw new InvalidDataException("The snapshot directory changed during creation."); + ValidateHandle(heldDirectory, user, directory: true, ancestor: false, privateSnapshot: true); + leases.Add(heldDirectory); + } + catch + { + heldDirectory.Dispose(); + throw; + } + snapshot.Dispose(); + return new WindowsImageSnapshotLease(directoryPath, Path.Combine(directoryPath, Path.GetFileName(image.SourcePath)), + leases, parent, heldDirectory, directoryName, heldFiles); + } + catch + { + for (var i = leases.Count - 1; i >= 0; i--) leases[i].Dispose(); + throw; + } + } + + [SupportedOSPlatform("windows")] + private static void CopyVerifiedFile(WindowsSnapshotFile file, SafeFileHandle snapshot, SecurityIdentifier user, + List leases, List<(string Name, SafeFileHandle Handle)> heldFiles, CancellationToken cancellationToken) + { + var path = ValidatePath(file.SourcePath); + var sourceLeases = new List(); + try + { + LockAncestors(Path.GetDirectoryName(path)!, user, sourceLeases); + using var source = OpenPath(path, directory: false, root: false); + ValidateHandle(source, user, directory: false, ancestor: false); + var security = new FileSecurity(); + security.SetOwner(user); + security.SetAccessRuleProtection(true, false); + security.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.FullControl, AccessControlType.Allow)); + var name = Path.GetFileName(path); + using (var destination = CreateRelative(snapshot, name, security, directory: false, write: true)) + using (var stream = new FileStream(destination, FileAccess.ReadWrite)) + using (var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256)) + { + ValidateHandle(destination, user, directory: false, ancestor: false, privateSnapshot: true); + var buffer = new byte[81920]; + long offset = 0; + int count; + while ((count = RandomAccess.Read(source, buffer, offset)) != 0) + { + cancellationToken.ThrowIfCancellationRequested(); + hash.AppendData(buffer, 0, count); + stream.Write(buffer, 0, count); + offset += count; + } + if (!CryptographicOperations.FixedTimeEquals(hash.GetHashAndReset(), file.Sha256)) + throw new InvalidDataException("A source file does not match its authorized SHA256."); + stream.Flush(); + stream.Position = 0; + if (!CryptographicOperations.FixedTimeEquals(SHA256.HashData(stream), file.Sha256)) + throw new InvalidDataException("A snapshot file does not match its authorized SHA256."); + } + var held = OpenRelative(snapshot, name, directory: false); + try + { + ValidateHandle(held, user, directory: false, ancestor: false, privateSnapshot: true); + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + var buffer = new byte[81920]; + long offset = 0; + int count; + while ((count = RandomAccess.Read(held, buffer, offset)) != 0) + { + cancellationToken.ThrowIfCancellationRequested(); + hash.AppendData(buffer, 0, count); + offset += count; + } + if (!CryptographicOperations.FixedTimeEquals(hash.GetHashAndReset(), file.Sha256)) + throw new InvalidDataException("The held snapshot file does not match its authorized SHA256."); + leases.Add(held); + heldFiles.Add((name, held)); + } + catch + { + held.Dispose(); + throw; + } + } + finally + { + for (var i = sourceLeases.Count - 1; i >= 0; i--) sourceLeases[i].Dispose(); + } + } + + [SupportedOSPlatform("windows")] + private static string ValidatePath(string path) + { + if (string.IsNullOrWhiteSpace(path) || !Path.IsPathFullyQualified(path)) + throw new ArgumentException("An absolute local path is required.", nameof(path)); + var full = Path.GetFullPath(path); + var root = Path.GetPathRoot(full); + if (root == null || root.Length != 3 || root[1] != ':' || !string.Equals(path.TrimEnd('\\'), full.TrimEnd('\\'), StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException("A canonical local drive path is required.", nameof(path)); + var drive = new DriveInfo(root); + if (drive.DriveType != DriveType.Fixed || !string.Equals(drive.DriveFormat, "NTFS", StringComparison.OrdinalIgnoreCase)) + throw new PlatformNotSupportedException("A local fixed NTFS volume is required."); + foreach (var component in full.Substring(root.Length).Split('\\')) + if (component.Length == 0 || component.IndexOf(':') >= 0 || component.EndsWith(".", StringComparison.Ordinal) || component.EndsWith(" ", StringComparison.Ordinal)) + throw new ArgumentException("The path contains an unsupported component.", nameof(path)); + return full; + } + + [SupportedOSPlatform("windows")] + private static SafeFileHandle LockAncestors(string path, SecurityIdentifier user, List leases) + { + var root = Path.GetPathRoot(path)!; + var current = root; + var handle = OpenPath(current, directory: true, root: true); + leases.Add(handle); + ValidateHandle(handle, user, directory: true, ancestor: true); + foreach (var component in path.Substring(root.Length).Split('\\')) + { + if (component.Length == 0) continue; + current = Path.Combine(current, component); + handle = OpenPath(current, directory: true, root: false); + leases.Add(handle); + ValidateHandle(handle, user, directory: true, ancestor: true); + } + return handle; + } + + [SupportedOSPlatform("windows")] + private static SafeFileHandle OpenPath(string path, bool directory, bool root) + { + var handle = CreateFile(path, 0x80000000, root ? 7u : directory ? 3u : 1u, IntPtr.Zero, 3, + 0x00200000 | (directory ? 0x02000000u : 0u), IntPtr.Zero); + if (!handle.IsInvalid) return handle; + var error = Marshal.GetLastWin32Error(); + handle.Dispose(); + throw new Win32Exception(error, "Unable to acquire a protected file handle."); + } + + [SupportedOSPlatform("windows")] + private static void ValidateHandle(SafeFileHandle handle, SecurityIdentifier user, bool directory, bool ancestor, + bool privateSnapshot = false) + { + if (!GetFileInformationByHandle(handle, out var information)) throw new Win32Exception(Marshal.GetLastWin32Error()); + if ((information.FileAttributes & 0x400) != 0 || ((information.FileAttributes & 0x10) != 0) != directory) + throw new InvalidDataException("A path component is a reparse point or has an unexpected type."); + var error = GetSecurityInfo(handle, 1, 0x1 | 0x4, out _, out _, out _, out _, out var descriptor); + if (error != 0) throw new Win32Exception((int)error, "Unable to read an object security descriptor."); + try + { + var bytes = new byte[GetSecurityDescriptorLength(descriptor)]; + Marshal.Copy(descriptor, bytes, 0, bytes.Length); + var security = new RawSecurityDescriptor(bytes, 0); + if (security.Owner == null || !IsTrusted(security.Owner, user) || + (security.ControlFlags & ControlFlags.DiscretionaryAclPresent) == 0 || security.DiscretionaryAcl == null) + throw new InvalidDataException("The object owner or DACL is not trusted."); + if (privateSnapshot && (!security.Owner.Equals(user) || + (security.ControlFlags & ControlFlags.DiscretionaryAclProtected) == 0)) + throw new InvalidDataException("The snapshot owner or DACL protection is invalid."); + const uint namespaceRights = 0x000d0040 | 0x50000000; + const uint fileWriteRights = namespaceRights | 0x00000116; + foreach (GenericAce ace in security.DiscretionaryAcl) + { + if (ace is not CommonAce common || common.IsCallback) + throw new InvalidDataException("The object has an unsupported access rule."); + if (common.AceQualifier == AceQualifier.AccessDenied) continue; + if (common.AceQualifier != AceQualifier.AccessAllowed) + throw new InvalidDataException("The object has an unsupported access rule."); + if (privateSnapshot && !common.SecurityIdentifier.Equals(user)) + throw new InvalidDataException("A snapshot access rule grants another principal access."); + if ((ace.AceFlags & AceFlags.InheritOnly) != 0) continue; + if (!IsTrusted(common.SecurityIdentifier, user) && + (unchecked((uint)common.AccessMask) & (ancestor ? namespaceRights : fileWriteRights)) != 0) + throw new InvalidDataException("An untrusted principal can modify the object or namespace."); + } + } + finally + { + LocalFree(descriptor); + } + } + + [SupportedOSPlatform("windows")] + private static bool IsTrusted(SecurityIdentifier sid, SecurityIdentifier user) => + sid.Equals(user) || sid.IsWellKnown(WellKnownSidType.LocalSystemSid) || + sid.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid) || + sid.Value == "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464"; + + [SupportedOSPlatform("windows")] + private static SafeFileHandle CreateRelative(SafeFileHandle parent, string name, ObjectSecurity security, bool directory, bool write) => + NtOpenRelative(parent, name, security.GetSecurityDescriptorBinaryForm(), directory, write, create: true); + + [SupportedOSPlatform("windows")] + private static SafeFileHandle OpenRelative(SafeFileHandle parent, string name, bool directory) => + NtOpenRelative(parent, name, null, directory, write: false, create: false); + + private static SafeFileHandle NtOpenRelative(SafeFileHandle parent, string name, byte[]? security, + bool directory, bool write, bool create, uint share = 1, bool delete = false) + { + var nameBuffer = Marshal.StringToHGlobalUni(name); + var namePointer = Marshal.AllocHGlobal(Marshal.SizeOf()); + var descriptor = security == null ? IntPtr.Zero : Marshal.AllocHGlobal(security.Length); + try + { + if (security != null) Marshal.Copy(security, 0, descriptor, security.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(), + RootDirectory = parent.DangerousGetHandle(), + ObjectName = namePointer, + Attributes = 0x40, + SecurityDescriptor = descriptor + }; + var access = delete ? 0x00110080u : directory ? (write ? 0x00120083u : 0x00120081u) : write ? 0xc0100000u : 0x80100000u; + var options = 0x00200020u | (directory ? 1u : 0x40u); + var status = NtCreateFile(out var handle, access, ref attributes, out _, IntPtr.Zero, 0x80, share, + create ? 2u : 1u, options, IntPtr.Zero, 0); + if (status == 0 && !handle.IsInvalid) return handle; + handle.Dispose(); + var error = (int)RtlNtStatusToDosError(status); + throw new Win32Exception(error, $"Unable to create or open a snapshot object (NTSTATUS 0x{status:x8}, Win32 {error})."); + } + finally + { + if (descriptor != IntPtr.Zero) Marshal.FreeHGlobal(descriptor); + Marshal.FreeHGlobal(namePointer); + Marshal.FreeHGlobal(nameBuffer); + } + } + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + try + { + foreach (var file in _files) + DeleteVerified(_directory, file.Name, file.Handle, directory: false); + DeleteVerified(_parent, _directoryName, _directory, directory: true); + } + finally + { + for (var i = _handles.Count - 1; i >= 0; i--) _handles[i].Dispose(); + } + } + + private static void DeleteVerified(SafeFileHandle parent, string name, SafeFileHandle original, bool directory) + { + using var retained = NtOpenRelative(parent, name, null, directory, write: false, create: false, share: 7); + RequireSameObject(original, retained); + original.Dispose(); + using var deleteHandle = OpenForCleanup(parent, name, directory); + RequireSameObject(retained, deleteHandle); + var disposition = new FileDispositionInformation { DeleteFile = true }; + var status = NtSetInformationFile(deleteHandle, out _, ref disposition, 1, 13); + if (status != 0) + { + var error = (int)RtlNtStatusToDosError(status); + throw new Win32Exception(error, $"Unable to delete the snapshot object (NTSTATUS 0x{status:x8}, Win32 {error})."); + } + } + + private static SafeFileHandle OpenForCleanup(SafeFileHandle parent, string name, bool directory) + { + for (var attempt = 0; ; attempt++) + { + try { return NtOpenRelative(parent, name, null, directory, write: false, create: false, share: 3, delete: true); } + catch (Win32Exception error) when (error.NativeErrorCode == 32 && attempt < 19) + { + Thread.Sleep(50); + } + } + } + + private static void RequireSameObject(SafeFileHandle first, SafeFileHandle second) + { + if (!GetFileInformationByHandle(first, out var a) || !GetFileInformationByHandle(second, out var b)) + throw new Win32Exception(Marshal.GetLastWin32Error()); + if (a.VolumeSerialNumber != b.VolumeSerialNumber || a.FileIndexHigh != b.FileIndexHigh || a.FileIndexLow != b.FileIndexLow) + throw new InvalidDataException("A snapshot object changed during cleanup."); + } + + [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; } + [StructLayout(LayoutKind.Sequential)] + private struct FileDispositionInformation { [MarshalAs(UnmanagedType.U1)] public bool DeleteFile; } + [StructLayout(LayoutKind.Sequential)] + private struct FileInformation + { + public uint FileAttributes; + public System.Runtime.InteropServices.ComTypes.FILETIME CreationTime, LastAccessTime, LastWriteTime; + public uint VolumeSerialNumber, FileSizeHigh, FileSizeLow, NumberOfLinks, FileIndexHigh, FileIndexLow; + } + + [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("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetFileInformationByHandle(SafeFileHandle handle, out FileInformation information); + [DllImport("advapi32.dll")] + private static extern uint GetSecurityInfo(SafeFileHandle handle, int type, uint information, out IntPtr owner, + out IntPtr group, out IntPtr dacl, out IntPtr sacl, out IntPtr descriptor); + [DllImport("advapi32.dll")] + private static extern uint GetSecurityDescriptorLength(IntPtr descriptor); + [DllImport("kernel32.dll")] + private static extern IntPtr LocalFree(IntPtr pointer); + [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); + [DllImport("ntdll.dll")] + private static extern int NtSetInformationFile(SafeFileHandle handle, out IoStatusBlock status, + ref FileDispositionInformation information, uint length, int informationClass); + [DllImport("ntdll.dll")] + private static extern uint RtlNtStatusToDosError(int status); +} +#endif diff --git a/src/GeneralUpdate.Core/Security/WindowsNativeImportPolicy.cs b/src/GeneralUpdate.Core/Security/WindowsNativeImportPolicy.cs new file mode 100644 index 00000000..3c00bec7 --- /dev/null +++ b/src/GeneralUpdate.Core/Security/WindowsNativeImportPolicy.cs @@ -0,0 +1,152 @@ +#if NET8_0_OR_GREATER +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection.Metadata; +using System.Reflection.PortableExecutable; +using System.Text; + +namespace GeneralUpdate.Core.Security; + +internal static class WindowsNativeImportPolicy +{ + internal static void ValidateManifest(IReadOnlyList dependencies, + IReadOnlyList applicationModules, IReadOnlyList systemModules) + { + var application = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var name in applicationModules) + if (!IsModuleName(name) || !application.Add(name)) + throw new ArgumentException("Application module names must be distinct DLL names.", nameof(applicationModules)); + var files = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var dependency in dependencies) + if (!files.Add(Path.GetFileName(dependency.SourcePath))) + throw new ArgumentException("Application dependency file names must be distinct.", nameof(dependencies)); + if (!files.SetEquals(application)) + throw new ArgumentException("Every application module must have exactly one authorized dependency file.", nameof(dependencies)); + foreach (var name in systemModules) + if (application.Contains(name)) + throw new ArgumentException("An application module cannot be classified as a system module.", nameof(systemModules)); + } + + internal static void Validate(string directory, IReadOnlyList files, + IReadOnlyList systemModules) + { + var application = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var file in files) application.Add(Path.GetFileName(file.SourcePath)); + var system = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var name in systemModules) + { + if (!IsModuleName(name) || !system.Add(name) || application.Contains(name)) + throw new ArgumentException("System module names must be distinct DLL names and cannot name an application file.", nameof(systemModules)); + } + foreach (var file in files) + { + var path = Path.Combine(directory, Path.GetFileName(file.SourcePath)); + using var stream = File.OpenRead(path); + using var pe = new PEReader(stream); + var header = pe.PEHeaders.PEHeader; + if (header == null || pe.PEHeaders.CorHeader != null) + throw new InvalidDataException("A snapshot file is not a native PE image."); + RejectForwardedExports(pe, header.ExportTableDirectory); + foreach (var name in ReadImports(pe, header.ImportTableDirectory)) + if (!system.Contains(name) && !application.Contains(name)) + throw new InvalidDataException("A native import is not in the authorized application or system module lists: " + name); + foreach (var name in ReadDelayImports(pe, header.DelayImportTableDirectory)) + if (!system.Contains(name) && !application.Contains(name)) + throw new InvalidDataException("A delay-loaded import is not in the authorized application or system module lists: " + name); + } + } + + private static IEnumerable ReadDelayImports(PEReader pe, DirectoryEntry imports) + { + if (imports.RelativeVirtualAddress == 0 && imports.Size == 0) yield break; + if (imports.RelativeVirtualAddress <= 0 || imports.Size < 32) + throw new InvalidDataException("The delay import table is invalid."); + var reader = pe.GetSectionData(imports.RelativeVirtualAddress).GetReader(0, imports.Size); + for (var i = 0; i < 4096 && reader.RemainingBytes >= 32; i++) + { + var attributes = reader.ReadUInt32(); + var nameAddress = reader.ReadUInt32(); + var rest = 0u; + for (var field = 0; field < 6; field++) rest |= reader.ReadUInt32(); + if ((attributes | nameAddress | rest) == 0) yield break; + if (attributes != 1 || nameAddress == 0 || nameAddress > int.MaxValue) + throw new InvalidDataException("A delay import descriptor is unsupported."); + var name = ReadModuleName(pe.GetSectionData((int)nameAddress).GetReader()); + if (!IsModuleName(name)) throw new InvalidDataException("A delay import is not a supported DLL name."); + yield return name; + } + throw new InvalidDataException("The delay import table is not terminated or is too large."); + } + + private static IEnumerable ReadImports(PEReader pe, DirectoryEntry imports) + { + if (imports.RelativeVirtualAddress == 0 && imports.Size == 0) yield break; + if (imports.RelativeVirtualAddress <= 0 || imports.Size < 20) + throw new InvalidDataException("The native import table is invalid."); + var reader = pe.GetSectionData(imports.RelativeVirtualAddress).GetReader(0, imports.Size); + for (var i = 0; i < 4096 && reader.RemainingBytes >= 20; i++) + { + var originalThunk = reader.ReadUInt32(); + var timestamp = reader.ReadUInt32(); + var forwarder = reader.ReadUInt32(); + var nameAddress = reader.ReadUInt32(); + var thunk = reader.ReadUInt32(); + if ((originalThunk | timestamp | forwarder | nameAddress | thunk) == 0) yield break; + if (nameAddress == 0 || nameAddress > int.MaxValue) throw new InvalidDataException("A native import name is invalid."); + var name = ReadModuleName(pe.GetSectionData((int)nameAddress).GetReader()); + if (!IsModuleName(name)) throw new InvalidDataException("A native import is not a supported DLL name."); + yield return name; + } + throw new InvalidDataException("The native import table is not terminated or is too large."); + } + + private static string ReadModuleName(BlobReader reader) + { + var bytes = new List(); + while (reader.RemainingBytes > 0 && bytes.Count < 260) + { + var value = reader.ReadByte(); + if (value == 0) return Encoding.ASCII.GetString(bytes.ToArray()); + if (value > 0x7f) throw new InvalidDataException("A native import name is not ASCII."); + bytes.Add(value); + } + throw new InvalidDataException("A native import name is not terminated or is too long."); + } + + private static bool IsModuleName(string? name) + { + if (string.IsNullOrEmpty(name) || name.Length > 259 || name[0] == '.' || name.Contains("..", StringComparison.Ordinal) || + !name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) return false; + foreach (var c in name) + if (!(c >= 'a' && c <= 'z') && !(c >= 'A' && c <= 'Z') && + !(c >= '0' && c <= '9') && c != '_' && c != '-' && c != '.') + return false; + return true; + } + + private static void RejectForwardedExports(PEReader pe, DirectoryEntry exports) + { + if (exports.RelativeVirtualAddress == 0 && exports.Size == 0) return; + if (exports.RelativeVirtualAddress <= 0 || exports.Size < 40) + throw new InvalidDataException("The native export table is invalid."); + var reader = pe.GetSectionData(exports.RelativeVirtualAddress).GetReader(0, exports.Size); + reader.Offset = 20; + var count = reader.ReadUInt32(); + reader.Offset = 28; + var functions = reader.ReadUInt32(); + if (count > 65536 || (count != 0 && (functions == 0 || functions > int.MaxValue))) + throw new InvalidDataException("The native export address table is invalid."); + if (count == 0) return; + var addresses = pe.GetSectionData((int)functions).GetReader(0, checked((int)count * 4)); + var start = (uint)exports.RelativeVirtualAddress; + var end = (ulong)start + (uint)exports.Size; + for (var i = 0; i < count; i++) + { + var address = addresses.ReadUInt32(); + if (address >= start && address < end) + throw new InvalidDataException("Forwarded application exports are not supported."); + } + } +} +#endif diff --git a/src/GeneralUpdate.Core/Security/WindowsNativeLaunchLease.cs b/src/GeneralUpdate.Core/Security/WindowsNativeLaunchLease.cs new file mode 100644 index 00000000..0be9c712 --- /dev/null +++ b/src/GeneralUpdate.Core/Security/WindowsNativeLaunchLease.cs @@ -0,0 +1,390 @@ +#if NET8_0_OR_GREATER +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Win32.SafeHandles; + +namespace GeneralUpdate.Core.Security; + +/// Trust profile explicitly selected by the host for a native launch. +public enum WindowsNativeLaunchProfile +{ + Disabled = 0, + TrustedWindowsSystemAndCooperativeNativeAot = 1 +} + +/// +/// Owns a snapshot, a process handle and a kill-on-close job. This is not peer +/// authentication and does not provide a communication channel. +/// +public sealed class WindowsNativeLaunchLease : IAsyncDisposable +{ + private static readonly HashSet Active = new(); + private readonly SafeFileHandle _job; + private readonly SafeFileHandle _process; + private readonly WindowsImageSnapshotLease _snapshot; + private readonly SemaphoreSlim _disposeLock = new(1, 1); + private bool _disposed; + + private WindowsNativeLaunchLease(SafeFileHandle job, SafeFileHandle process, WindowsImageSnapshotLease snapshot) + { + _job = job; + _process = process; + _snapshot = snapshot; + } + + public string SnapshotDirectory => _snapshot.DirectoryPath; + + /// + /// Returns an independently owned handle to this exact process, limited to + /// query and synchronization. The caller must dispose the returned handle. + /// + public SafeProcessHandle DuplicateProcessHandle() + { + _disposeLock.Wait(); + try + { + if (_disposed) throw new ObjectDisposedException(nameof(WindowsNativeLaunchLease)); + var current = GetCurrentProcess(); + if (!DuplicateHandle(current, _process, current, out var duplicate, 0x00101000, false, 0)) + throw new Win32Exception(Marshal.GetLastWin32Error()); + return duplicate; + } + finally { _disposeLock.Release(); } + } + + /// + /// Starts a host-authorized, cooperative Windows Native AOT peer. The explicitly selected + /// profile trusts the Windows loader, API-set/SxS resolution and system DLLs; the deployer + /// must guarantee that untrusted users have never retained write or security-modification + /// access to those system objects. This method cannot verify that historical condition. + /// The hash identifies the peer and its trusted entry-point contract; this method does not inspect its code. + /// The peer must limit DLL loading to its authorized snapshot and Windows system + /// directories before handling sensitive input. The supplied system module names + /// are a host assertion of trusted OS components, not proof based on their names. + /// Do not pass secrets in arguments. + /// No handles are inherited. The working directory and executable directory are the + /// snapshot, not the application installation directory. + /// + public static WindowsNativeLaunchLease Start(WindowsNativeLaunchProfile profile, string snapshotParent, + WindowsSnapshotFile image, System.Collections.Generic.IReadOnlyList dependencies, + System.Collections.Generic.IReadOnlyList applicationModules, + System.Collections.Generic.IReadOnlyList systemModules, + System.Collections.Generic.IReadOnlyList arguments, CancellationToken cancellationToken = default) + { + if (!OperatingSystem.IsWindows()) throw new PlatformNotSupportedException("Windows is required."); + if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 19041)) + throw new PlatformNotSupportedException("Windows 10 version 2004 or later is required."); + if (profile != WindowsNativeLaunchProfile.TrustedWindowsSystemAndCooperativeNativeAot) + throw new InvalidOperationException("The trusted Windows system and cooperative Native AOT profile is not enabled."); + if (dependencies == null) throw new ArgumentNullException(nameof(dependencies)); + if (applicationModules == null) throw new ArgumentNullException(nameof(applicationModules)); + if (systemModules == null) throw new ArgumentNullException(nameof(systemModules)); + if (arguments == null) throw new ArgumentNullException(nameof(arguments)); + var argumentCopy = new string[arguments.Count]; + for (var i = 0; i < argumentCopy.Length; i++) + argumentCopy[i] = arguments[i] ?? throw new ArgumentException("Arguments must not contain null values.", nameof(arguments)); + var systemCopy = new string[systemModules.Count]; + for (var i = 0; i < systemCopy.Length; i++) + systemCopy[i] = systemModules[i] ?? throw new ArgumentException("System module names must not be null.", nameof(systemModules)); + var dependencyCopy = new WindowsSnapshotFile[dependencies.Count]; + for (var i = 0; i < dependencyCopy.Length; i++) + dependencyCopy[i] = dependencies[i] ?? throw new ArgumentException("Dependencies must not contain null values.", nameof(dependencies)); + WindowsNativeImportPolicy.ValidateManifest(dependencyCopy, applicationModules, systemCopy); + return StartWindows(snapshotParent, image, dependencyCopy, systemCopy, argumentCopy, cancellationToken); + } + + [SupportedOSPlatform("windows")] + private static WindowsNativeLaunchLease StartWindows(string snapshotParent, + WindowsSnapshotFile image, System.Collections.Generic.IReadOnlyList dependencies, + System.Collections.Generic.IReadOnlyList systemModules, + System.Collections.Generic.IReadOnlyList arguments, CancellationToken cancellationToken) + { + foreach (var argument in arguments) + if (argument == null || argument.IndexOf('\0') >= 0) + throw new ArgumentException("Arguments must not contain null values or NUL characters.", nameof(arguments)); + cancellationToken.ThrowIfCancellationRequested(); + var snapshot = WindowsImageSnapshotLease.Create(true, snapshotParent, image, dependencies, cancellationToken); + SafeFileHandle? job = null; + try + { + var files = new List { image }; + files.AddRange(dependencies); + WindowsNativeImportPolicy.Validate(snapshot.DirectoryPath, files, systemModules); + job = CreateJobObject(IntPtr.Zero, null); + if (job.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error()); + var limits = new ExtendedLimitInformation + { + BasicLimitInformation = new BasicLimitInformation { LimitFlags = 0x2000 } + }; + if (!SetInformationJobObject(job, 9, ref limits, (uint)Marshal.SizeOf())) + throw new Win32Exception(Marshal.GetLastWin32Error()); + var size = IntPtr.Zero; + InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref size); + if (size == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); + var list = Marshal.AllocHGlobal(size); + var jobPointer = Marshal.AllocHGlobal(IntPtr.Size); + var initialized = false; + try + { + if (!InitializeProcThreadAttributeList(list, 1, 0, ref size)) + throw new Win32Exception(Marshal.GetLastWin32Error()); + initialized = true; + Marshal.WriteIntPtr(jobPointer, job.DangerousGetHandle()); + if (!UpdateProcThreadAttribute(list, 0, new IntPtr(0x0002000d), jobPointer, + new IntPtr(IntPtr.Size), IntPtr.Zero, IntPtr.Zero)) + throw new Win32Exception(Marshal.GetLastWin32Error()); + var windows = new StringBuilder(32768); + var length = GetWindowsDirectory(windows, (uint)windows.Capacity); + if (length == 0 || length >= windows.Capacity) throw new Win32Exception(Marshal.GetLastWin32Error()); + var system = Environment.SystemDirectory; + if (string.IsNullOrEmpty(system) || !Path.IsPathFullyQualified(system)) + throw new InvalidOperationException("The Windows system directory is unavailable."); + var environment = "PATH=" + system + "\0SystemRoot=" + windows + "\0WINDIR=" + windows + "\0\0"; + var environmentPointer = Marshal.StringToHGlobalUni(environment); + try + { + var command = new StringBuilder(Quote(snapshot.ImagePath)); + foreach (var argument in arguments) command.Append(' ').Append(Quote(argument)); + var startup = new StartupInfoEx + { + StartupInfo = new StartupInfo { Size = Marshal.SizeOf() }, + AttributeList = list + }; + cancellationToken.ThrowIfCancellationRequested(); + if (!CreateProcess(snapshot.ImagePath, command, IntPtr.Zero, IntPtr.Zero, false, + 0x00080000 | 0x08000000 | 0x00000004 | 0x00000400, environmentPointer, + snapshot.DirectoryPath, ref startup, out var process)) + throw new Win32Exception(Marshal.GetLastWin32Error()); + var resumed = false; + WindowsNativeLaunchLease? result = null; + using var thread = new SafeFileHandle(process.Thread, true); + var processHandle = new SafeFileHandle(process.Process, true); + try + { + if (!IsProcessInJob(processHandle, job, out var assigned)) + throw new Win32Exception(Marshal.GetLastWin32Error()); + if (!assigned) throw new InvalidOperationException("The created process is not in the job."); + cancellationToken.ThrowIfCancellationRequested(); + result = new WindowsNativeLaunchLease(job, processHandle, snapshot); + lock (Active) Active.Add(result); + if (ResumeThread(thread) == uint.MaxValue) + throw new Win32Exception(Marshal.GetLastWin32Error()); + resumed = true; + job = null; + return result; + } + finally + { + if (!resumed) + { + if (result != null) + lock (Active) Active.Remove(result); + try + { + TerminateProcess(processHandle, 1); + job?.Dispose(); + job = null; + if (WaitForSingleObject(processHandle, uint.MaxValue) != 0) + throw new Win32Exception(Marshal.GetLastWin32Error(), "Failed to wait for the suspended process."); + } + finally { processHandle.Dispose(); } + } + } + } + finally { Marshal.FreeHGlobal(environmentPointer); } + } + finally + { + if (initialized) DeleteProcThreadAttributeList(list); + Marshal.FreeHGlobal(jobPointer); + Marshal.FreeHGlobal(list); + } + } + catch + { + job?.Dispose(); + snapshot.Dispose(); + throw; + } + } + + private static string Quote(string value) + { + var result = new StringBuilder("\""); + var slashes = 0; + foreach (var c in value) + { + if (c == '\\') { slashes++; continue; } + if (c == '"') result.Append('\\', slashes * 2 + 1); + else result.Append('\\', slashes); + result.Append(c); + slashes = 0; + } + result.Append('\\', slashes * 2).Append('"'); + return result.ToString(); + } + + /// Waits for the owned process. Cancellation stops the job and releases the lease. + public async Task WaitForExitAsync(CancellationToken cancellationToken = default) + { + try + { + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + await _disposeLock.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + if (_disposed) throw new ObjectDisposedException(nameof(WindowsNativeLaunchLease)); + var wait = WaitForSingleObject(_process, 0); + if (wait == 0) + { + if (!GetExitCodeProcess(_process, out var code)) throw new Win32Exception(Marshal.GetLastWin32Error()); + return code; + } + if (wait != 258) throw new Win32Exception(Marshal.GetLastWin32Error()); + } + finally { _disposeLock.Release(); } + await Task.Delay(100, cancellationToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) + { + await DisposeAsync().ConfigureAwait(false); + throw; + } + } + + /// Closes the job, waits for the process to exit, and releases snapshot handles. + public async ValueTask DisposeAsync() + { + await _disposeLock.WaitAsync().ConfigureAwait(false); + try + { + if (_disposed) return; + if (!TerminateJobObject(_job, 1)) + throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to terminate the owned job."); + var result = await Task.Run(() => + { + var wait = WaitForSingleObject(_process, uint.MaxValue); + return (Wait: wait, Error: wait == 0 ? 0 : Marshal.GetLastWin32Error()); + }).ConfigureAwait(false); + if (result.Wait != 0) throw new Win32Exception(result.Error, "Unable to wait for the terminated process."); + while (true) + { + if (!QueryInformationJobObject(_job, 1, out var accounting, + (uint)Marshal.SizeOf(), IntPtr.Zero)) + throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to inspect the owned job."); + if (accounting.ActiveProcesses == 0) break; + await Task.Delay(50).ConfigureAwait(false); + } + _job.Dispose(); + _process.Dispose(); + try { _snapshot.Dispose(); } + finally + { + _disposed = true; + lock (Active) Active.Remove(this); + } + } + finally { _disposeLock.Release(); } + } + + [StructLayout(LayoutKind.Sequential)] + private struct BasicLimitInformation + { + public long PerProcessUserTimeLimit, PerJobUserTimeLimit; + public uint LimitFlags; + public UIntPtr MinimumWorkingSetSize, MaximumWorkingSetSize; + public uint ActiveProcessLimit; + public UIntPtr Affinity; + public uint PriorityClass, SchedulingClass; + } + [StructLayout(LayoutKind.Sequential)] + private struct IoCounters + { + public ulong ReadOperationCount, WriteOperationCount, OtherOperationCount; + public ulong ReadTransferCount, WriteTransferCount, OtherTransferCount; + } + [StructLayout(LayoutKind.Sequential)] + private struct BasicAccountingInformation + { + public long TotalUserTime, TotalKernelTime, ThisPeriodTotalUserTime, ThisPeriodTotalKernelTime; + public uint TotalPageFaultCount, TotalProcesses, ActiveProcesses, TotalTerminatedProcesses; + } + [StructLayout(LayoutKind.Sequential)] + private struct ExtendedLimitInformation + { + public BasicLimitInformation BasicLimitInformation; + public IoCounters IoInfo; + public UIntPtr ProcessMemoryLimit, JobMemoryLimit, PeakProcessMemoryUsed, PeakJobMemoryUsed; + } + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct StartupInfo + { + public int Size; + public string? Reserved, Desktop, Title; + public int X, Y, XSize, YSize, XCountChars, YCountChars, FillAttribute, Flags; + public short ShowWindow, Reserved2; + public IntPtr ReservedPointer, StandardInput, StandardOutput, StandardError; + } + [StructLayout(LayoutKind.Sequential)] + private struct StartupInfoEx { public StartupInfo StartupInfo; public IntPtr AttributeList; } + [StructLayout(LayoutKind.Sequential)] + private struct ProcessInformation { public IntPtr Process, Thread; public int ProcessId, ThreadId; } + + [DllImport("kernel32.dll", EntryPoint = "CreateJobObjectW", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern SafeFileHandle CreateJobObject(IntPtr attributes, string? name); + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool SetInformationJobObject(SafeFileHandle job, int informationClass, ref ExtendedLimitInformation information, uint length); + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool TerminateJobObject(SafeFileHandle job, uint exitCode); + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool QueryInformationJobObject(SafeFileHandle job, int informationClass, + out BasicAccountingInformation information, uint length, IntPtr returnLength); + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool InitializeProcThreadAttributeList(IntPtr list, int count, int flags, ref IntPtr size); + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool UpdateProcThreadAttribute(IntPtr list, int flags, IntPtr attribute, IntPtr value, IntPtr size, IntPtr previousValue, IntPtr returnSize); + [DllImport("kernel32.dll")] + private static extern void DeleteProcThreadAttributeList(IntPtr list); + [DllImport("kernel32.dll", EntryPoint = "GetWindowsDirectoryW", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern uint GetWindowsDirectory(StringBuilder buffer, uint size); + [DllImport("kernel32.dll", EntryPoint = "CreateProcessW", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool CreateProcess(string application, StringBuilder command, IntPtr processAttributes, + IntPtr threadAttributes, [MarshalAs(UnmanagedType.Bool)] bool inheritHandles, uint flags, IntPtr environment, + string currentDirectory, ref StartupInfoEx startup, out ProcessInformation process); + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool IsProcessInJob(SafeFileHandle process, SafeFileHandle job, [MarshalAs(UnmanagedType.Bool)] out bool result); + [DllImport("kernel32.dll", SetLastError = true)] + private static extern uint ResumeThread(SafeFileHandle thread); + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool TerminateProcess(SafeFileHandle process, uint exitCode); + [DllImport("kernel32.dll", SetLastError = true)] + private static extern uint WaitForSingleObject(SafeFileHandle handle, uint milliseconds); + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetExitCodeProcess(SafeFileHandle process, out uint exitCode); + [DllImport("kernel32.dll")] + private static extern IntPtr GetCurrentProcess(); + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool DuplicateHandle(IntPtr sourceProcess, SafeFileHandle source, IntPtr targetProcess, + out SafeProcessHandle target, uint access, [MarshalAs(UnmanagedType.Bool)] bool inherit, uint options); +} +#endif diff --git a/tests/CoreTest/Ipc/WindowsImageSnapshotLeaseTests.cs b/tests/CoreTest/Ipc/WindowsImageSnapshotLeaseTests.cs new file mode 100644 index 00000000..f4bb3ab5 --- /dev/null +++ b/tests/CoreTest/Ipc/WindowsImageSnapshotLeaseTests.cs @@ -0,0 +1,568 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.Reflection.PortableExecutable; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using System.Security.AccessControl; +using System.Security.Cryptography; +using System.Security.Principal; +using GeneralUpdate.Core.Security; +using Microsoft.Win32.SafeHandles; + +namespace CoreTest.Ipc; + +public sealed class WindowsImageSnapshotLeaseTests +{ + [Fact] + public void DisabledProfileIsRejected() + { + var image = new WindowsSnapshotFile("unused.exe", new byte[32]); + if (OperatingSystem.IsWindows()) + { + Assert.Throws(() => WindowsImageSnapshotLease.Create(false, "unused", image, Array.Empty())); + if (OperatingSystem.IsWindowsVersionAtLeast(10, 0, 19041)) + { + Assert.Throws(() => WindowsNativeLaunchLease.Start( + WindowsNativeLaunchProfile.Disabled, "unused", image, Array.Empty(), Array.Empty(), Array.Empty(), Array.Empty())); + Assert.Throws(() => WindowsNativeLaunchLease.Start( + (WindowsNativeLaunchProfile)42, "unused", image, Array.Empty(), Array.Empty(), Array.Empty(), Array.Empty())); + } + } + else + { + Assert.Throws(() => WindowsImageSnapshotLease.Create(false, "unused", image, Array.Empty())); + Assert.Throws(() => WindowsNativeLaunchLease.Start( + WindowsNativeLaunchProfile.TrustedWindowsSystemAndCooperativeNativeAot, + "unused", image, Array.Empty(), Array.Empty(), Array.Empty(), Array.Empty())); + } + } + + [Fact] + public void VerifiedSnapshotHoldsImageAndDirectory() + { + if (!OperatingSystem.IsWindows()) return; + using var fixture = new Fixture(); + using var lease = fixture.Create(); + Assert.Equal(File.ReadAllBytes(fixture.Image), File.ReadAllBytes(lease.ImagePath)); + Assert.Equal(File.ReadAllBytes(fixture.Dependency), File.ReadAllBytes(Path.Combine(lease.DirectoryPath, "native.dll"))); + var security = new DirectoryInfo(lease.DirectoryPath).GetAccessControl(); + Assert.True(security.AreAccessRulesProtected); + Assert.Equal(WindowsIdentity.GetCurrent().User, security.GetOwner(typeof(SecurityIdentifier))); + var write = Assert.Throws(() => File.WriteAllText(lease.ImagePath, "changed")); + Assert.Equal(32, write.HResult & 0xffff); + var move = Assert.Throws(() => Directory.Move(lease.DirectoryPath, lease.DirectoryPath + ".moved")); + Assert.Equal(32, move.HResult & 0xffff); + } + + [Fact] + public void DisposalDeletesTheHeldSnapshot() + { + if (!OperatingSystem.IsWindows()) return; + using var fixture = new Fixture(); + var lease = fixture.Create(); + var path = lease.DirectoryPath; + lease.Dispose(); + Assert.False(Directory.Exists(path)); + lease.Dispose(); + } + + [Fact] + public void DeploymentCanReplaceSourceWhileSnapshotRemainsFixed() + { + if (!OperatingSystem.IsWindows()) return; + using var fixture = new Fixture(); + using var lease = fixture.Create(); + var replacement = fixture.Image + ".new"; + File.WriteAllText(replacement, "new deployment"); + File.Move(replacement, fixture.Image, overwrite: true); + Assert.Equal("new deployment", File.ReadAllText(fixture.Image)); + Assert.Equal("image bytes", File.ReadAllText(lease.ImagePath)); + } + + [Fact] + public void UnexpectedChildIsNotRecursivelyDeleted() + { + if (!OperatingSystem.IsWindows()) return; + using var fixture = new Fixture(); + var lease = fixture.Create(); + var path = Path.Combine(lease.DirectoryPath, "unexpected.txt"); + File.WriteAllText(path, "preserve"); + var failure = Assert.Throws(() => lease.Dispose()); + Assert.Equal(145, failure.NativeErrorCode); + Assert.Equal("preserve", File.ReadAllText(path)); + } + + [Fact] + public void HashMismatchAndExistingWriteHandleAreRejected() + { + if (!OperatingSystem.IsWindows()) return; + using var fixture = new Fixture(); + var bad = new WindowsSnapshotFile(fixture.Image, new byte[32]); + Assert.Throws(() => WindowsImageSnapshotLease.Create(true, fixture.Staging, bad, Array.Empty())); + var image = new WindowsSnapshotFile(fixture.Image, SHA256.HashData(File.ReadAllBytes(fixture.Image))); + using var existing = new FileStream(fixture.Image, FileMode.Open, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete); + var failure = Assert.Throws(() => + WindowsImageSnapshotLease.Create(true, fixture.Staging, image, Array.Empty())); + Assert.Equal(32, failure.NativeErrorCode); + } + + [Fact] + public void UntrustedWriteRuleIsRejected() + { + if (!OperatingSystem.IsWindows()) return; + using var fixture = new Fixture(); + var security = new FileInfo(fixture.Image).GetAccessControl(); + security.AddAccessRule(new FileSystemAccessRule( + new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), + FileSystemRights.WriteData, AccessControlType.Allow)); + new FileInfo(fixture.Image).SetAccessControl(security); + Assert.Throws(() => fixture.Create()); + } + + [Fact] + public void ExistingDeleteHandleAndAncestorJunctionAreRejected() + { + if (!OperatingSystem.IsWindows()) return; + using var fixture = new Fixture(); + var image = new WindowsSnapshotFile(fixture.Image, SHA256.HashData(File.ReadAllBytes(fixture.Image))); + using (var handle = CreateFile(fixture.Image, 0x00010000, 7, IntPtr.Zero, 3, 0x80, IntPtr.Zero)) + { + if (handle.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error()); + var failure = Assert.Throws(() => + WindowsImageSnapshotLease.Create(true, fixture.Staging, image, Array.Empty())); + Assert.Equal(32, failure.NativeErrorCode); + } + var junction = Path.Combine(fixture.Root, "junction"); + var start = new ProcessStartInfo(Path.Combine(Environment.SystemDirectory, "cmd.exe")) + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + foreach (var argument in new[] { "/c", "mklink", "/J", junction, fixture.Root }) + start.ArgumentList.Add(argument); + using var command = Process.Start(start) ?? throw new InvalidOperationException("Could not start mklink."); + var output = command.StandardOutput.ReadToEnd(); + var error = command.StandardError.ReadToEnd(); + command.WaitForExit(); + Assert.True(command.ExitCode == 0, output + error); + try + { + var throughJunction = new WindowsSnapshotFile(Path.Combine(junction, "image.exe"), + SHA256.HashData(File.ReadAllBytes(fixture.Image))); + Assert.Throws(() => + WindowsImageSnapshotLease.Create(true, fixture.Staging, throughJunction, Array.Empty())); + } + finally { Directory.Delete(junction); } + } + + [Fact] + public async Task LaunchUsesTheSnapshotAndCancellationEndsTheJob() + { + if (!OperatingSystem.IsWindows()) return; + using var fixture = new Fixture(); + var native = Environment.GetEnvironmentVariable("GU_WINDOWS_SNAPSHOT_PEER"); + var dependencies = Array.Empty(); + string[] arguments; + var marker = Path.Combine(fixture.Root, "child marker.txt"); + if (native != null) + { + File.Copy(native, fixture.Image, overwrite: true); + var sqlite = Path.Combine(fixture.Root, "e_sqlite3.dll"); + File.Copy(Path.Combine(Path.GetDirectoryName(native)!, "e_sqlite3.dll"), sqlite); + dependencies = new[] { new WindowsSnapshotFile(sqlite, SHA256.HashData(File.ReadAllBytes(sqlite))) }; + arguments = new[] { "--snapshot-probe", marker, "wait" }; + } + else + { + File.Copy(Path.Combine(Environment.SystemDirectory, "cmd.exe"), fixture.Image, overwrite: true); + arguments = new[] { "/c", "ping", "-n", "120", "127.0.0.1" }; + } + var image = new WindowsSnapshotFile(fixture.Image, SHA256.HashData(File.ReadAllBytes(fixture.Image))); + var systems = TrustedModules(new[] { fixture.Image }.Concat(dependencies.Select(item => item.SourcePath))); + var lease = WindowsNativeLaunchLease.Start(WindowsNativeLaunchProfile.TrustedWindowsSystemAndCooperativeNativeAot, + fixture.Staging, image, dependencies, dependencies.Select(item => Path.GetFileName(item.SourcePath)).ToArray(), systems, arguments); + await using (lease) + { + using (var process = lease.DuplicateProcessHandle()) + { + Assert.False(TerminateProcess(process, 123)); + Assert.Equal(5, Marshal.GetLastWin32Error()); + } + if (native != null) + { + for (var i = 0; i < 200 && !File.Exists(marker + ".ready") && !File.Exists(marker + ".error"); i++) await Task.Delay(50); + Assert.True(File.Exists(marker + ".ready"), File.Exists(marker + ".error") ? File.ReadAllText(marker + ".error") : "Native AOT peer did not load SQLite and create the marker."); + Assert.Equal(Path.Combine(lease.SnapshotDirectory, "e_sqlite3.dll"), File.ReadAllLines(marker)[0], ignoreCase: true); + } + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2)); + await Assert.ThrowsAnyAsync(() => lease.WaitForExitAsync(timeout.Token)); + } + } + + [Fact] + public async Task InvalidImageHashNeverStartsAndNormalExitIsReported() + { + if (!OperatingSystem.IsWindows()) return; + using var fixture = new Fixture(); + File.Copy(Path.Combine(Environment.SystemDirectory, "cmd.exe"), fixture.Image, overwrite: true); + var marker = Path.Combine(fixture.Root, "unexpected.txt"); + var bad = new WindowsSnapshotFile(fixture.Image, new byte[32]); + Assert.Throws(() => WindowsNativeLaunchLease.Start(WindowsNativeLaunchProfile.TrustedWindowsSystemAndCooperativeNativeAot, fixture.Staging, bad, + Array.Empty(), Array.Empty(), Array.Empty(), new[] { "/c", "echo", "bad", ">", marker })); + var good = new WindowsSnapshotFile(fixture.Image, SHA256.HashData(File.ReadAllBytes(fixture.Image))); + var badDependency = new WindowsSnapshotFile(fixture.Dependency, new byte[32]); + Assert.Throws(() => WindowsNativeLaunchLease.Start(WindowsNativeLaunchProfile.TrustedWindowsSystemAndCooperativeNativeAot, + fixture.Staging, good, new[] { badDependency }, new[] { "native.dll" }, Array.Empty(), new[] { "/c", "echo", "bad", ">", marker })); + Assert.Throws(() => WindowsNativeLaunchLease.Start(WindowsNativeLaunchProfile.TrustedWindowsSystemAndCooperativeNativeAot, + fixture.Staging, good, Array.Empty(), Array.Empty(), Array.Empty(), new[] { "/c", "echo", "bad", ">", marker })); + Assert.False(File.Exists(marker)); + await using var lease = WindowsNativeLaunchLease.Start(WindowsNativeLaunchProfile.TrustedWindowsSystemAndCooperativeNativeAot, fixture.Staging, good, + Array.Empty(), Array.Empty(), TrustedModules(new[] { fixture.Image }), new[] { "/c", "exit 1" }); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + Assert.Equal(1u, await lease.WaitForExitAsync(timeout.Token)); + } + + [Fact] + public void MissingReplacedOrMisclassifiedApplicationModuleNeverStarts() + { + if (!OperatingSystem.IsWindows()) return; + using var fixture = new Fixture(); + File.Copy(Path.Combine(Environment.SystemDirectory, "cmd.exe"), fixture.Image, overwrite: true); + var image = new WindowsSnapshotFile(fixture.Image, SHA256.HashData(File.ReadAllBytes(fixture.Image))); + var expected = new WindowsSnapshotFile(fixture.Dependency, SHA256.HashData(File.ReadAllBytes(fixture.Dependency))); + var marker = Path.Combine(fixture.Root, "unexpected.txt"); + var arguments = new[] { "/c", "echo", "bad", ">", marker }; + Assert.Throws(() => WindowsNativeLaunchLease.Start( + WindowsNativeLaunchProfile.TrustedWindowsSystemAndCooperativeNativeAot, fixture.Staging, image, + Array.Empty(), new[] { "native.dll" }, new[] { "NATIVE.DLL" }, arguments)); + Assert.Throws(() => WindowsNativeLaunchLease.Start( + WindowsNativeLaunchProfile.TrustedWindowsSystemAndCooperativeNativeAot, fixture.Staging, image, + new[] { expected }, new[] { "native.dll" }, new[] { "NATIVE.DLL" }, arguments)); + Assert.Throws(() => WindowsNativeLaunchLease.Start( + WindowsNativeLaunchProfile.TrustedWindowsSystemAndCooperativeNativeAot, fixture.Staging, image, + new[] { expected }, new[] { @"sub\native.dll" }, Array.Empty(), arguments)); + File.WriteAllText(fixture.Dependency, "replacement"); + Assert.Throws(() => WindowsNativeLaunchLease.Start( + WindowsNativeLaunchProfile.TrustedWindowsSystemAndCooperativeNativeAot, fixture.Staging, image, + new[] { expected }, new[] { "NATIVE.DLL" }, Array.Empty(), arguments)); + Assert.False(File.Exists(marker)); + } + + [Fact] + public void TruncatedNativeImageNeverStarts() + { + if (!OperatingSystem.IsWindows()) return; + using var fixture = new Fixture(); + File.WriteAllBytes(fixture.Image, new byte[] { 0x4d, 0x5a }); + var image = new WindowsSnapshotFile(fixture.Image, SHA256.HashData(File.ReadAllBytes(fixture.Image))); + var marker = Path.Combine(fixture.Root, "unexpected.txt"); + Assert.ThrowsAny(() => WindowsNativeLaunchLease.Start( + WindowsNativeLaunchProfile.TrustedWindowsSystemAndCooperativeNativeAot, fixture.Staging, image, + Array.Empty(), Array.Empty(), Array.Empty(), + new[] { "/c", "echo", "bad", ">", marker })); + Assert.False(File.Exists(marker)); + } + + [Theory] + [InlineData(0, 0x7fffffff, 0x7fffffff)] + [InlineData(1, 0x7fffffff, 0x7fffffff)] + [InlineData(13, 0x7fffffff, 0x7fffffff)] + public void OutOfBoundsNativeDirectoryNeverStarts(int index, int rva, int size) + { + if (!OperatingSystem.IsWindows()) return; + using var fixture = new Fixture(); + var bytes = File.ReadAllBytes(Path.Combine(Environment.SystemDirectory, "cmd.exe")); + var peOffset = BitConverter.ToInt32(bytes, 0x3c); + var optional = checked(peOffset + 24); + var magic = BitConverter.ToUInt16(bytes, optional); + var directories = checked(optional + (magic == 0x20b ? 112 : 96)); + var entry = checked(directories + index * 8); + BitConverter.GetBytes(rva).CopyTo(bytes, entry); + BitConverter.GetBytes(size).CopyTo(bytes, entry + 4); + File.WriteAllBytes(fixture.Image, bytes); + var image = new WindowsSnapshotFile(fixture.Image, SHA256.HashData(bytes)); + var marker = Path.Combine(fixture.Root, "unexpected.txt"); + Assert.ThrowsAny(() => WindowsNativeLaunchLease.Start( + WindowsNativeLaunchProfile.TrustedWindowsSystemAndCooperativeNativeAot, fixture.Staging, image, + Array.Empty(), Array.Empty(), Array.Empty(), + new[] { "/c", "echo", "bad", ">", marker })); + Assert.False(File.Exists(marker)); + } + + [NativeAotTheory] + [InlineData(false)] + [InlineData(true)] + public async Task SnapshotJobStopsChildOnOwnerExit(bool killOwner) + { + if (!OperatingSystem.IsWindows()) return; + var native = Environment.GetEnvironmentVariable("GU_WINDOWS_SNAPSHOT_PEER") + ?? throw new InvalidOperationException("The Native AOT snapshot peer is required."); + using var fixture = new Fixture(); + File.Copy(native, fixture.Image, overwrite: true); + var sqlite = Path.Combine(fixture.Root, "e_sqlite3.dll"); + File.Copy(Path.Combine(Path.GetDirectoryName(native)!, "e_sqlite3.dll"), sqlite); + var marker = Path.Combine(fixture.Root, "child.txt"); + var start = new ProcessStartInfo(native) + { + UseShellExecute = false, RedirectStandardInput = true, RedirectStandardError = true, CreateNoWindow = true + }; + foreach (var argument in new[] { "--snapshot-owner-probe", fixture.Staging, fixture.Image, sqlite, marker }) + start.ArgumentList.Add(argument); + foreach (var module in TrustedModules(new[] { fixture.Image, sqlite })) start.ArgumentList.Add(module); + using var owner = Process.Start(start) ?? throw new InvalidOperationException("Could not start the owner."); + var errors = owner.StandardError.ReadToEndAsync(); + Process? child = null; + try + { + for (var i = 0; i < 600 && !File.Exists(marker + ".ready") && !File.Exists(marker + ".error") && !owner.HasExited; i++) await Task.Delay(50); + Assert.True(File.Exists(marker + ".ready"), File.Exists(marker + ".error") ? File.ReadAllText(marker + ".error") : + owner.HasExited ? await errors : "Child did not start."); + var lines = File.ReadAllLines(marker); + child = Process.GetProcessById(int.Parse(lines[1])); + Assert.False(child.HasExited); + if (killOwner) owner.Kill(); + else await owner.StandardInput.WriteLineAsync("release"); + await owner.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(30)); + if (!killOwner) Assert.True(owner.ExitCode == 0, await errors); + await child.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(30)); + } + finally + { + if (!owner.HasExited) owner.Kill(); + await owner.WaitForExitAsync(); + if (child != null) + { + if (!child.HasExited) child.Kill(); + await child.WaitForExitAsync(); + child.Dispose(); + } + } + } + + [NativeAotFact] + public async Task SnapshotLaunchInheritsNoUnlistedHandles() + { + if (!OperatingSystem.IsWindows()) return; + var native = Environment.GetEnvironmentVariable("GU_WINDOWS_SNAPSHOT_PEER") + ?? throw new InvalidOperationException("The Native AOT snapshot peer is required."); + using var fixture = new Fixture(); + File.Copy(native, fixture.Image, overwrite: true); + var marker = Path.Combine(fixture.Root, "inherited.txt"); + var attributes = new SecurityAttributes { Length = Marshal.SizeOf(), InheritHandle = true }; + using var first = CreateInheritableFile(fixture.Dependency, 0x80000000, 7, ref attributes, 3, 0x80, IntPtr.Zero); + using var second = CreateInheritableFile(fixture.Dependency, 0x80000000, 7, ref attributes, 3, 0x80, IntPtr.Zero); + if (first.IsInvalid || second.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error()); + var image = new WindowsSnapshotFile(fixture.Image, SHA256.HashData(File.ReadAllBytes(fixture.Image))); + await using var lease = WindowsNativeLaunchLease.Start(WindowsNativeLaunchProfile.TrustedWindowsSystemAndCooperativeNativeAot, fixture.Staging, image, + Array.Empty(), Array.Empty(), TrustedModules(new[] { fixture.Image }), new[] { "--handle-list-probe", + first.DangerousGetHandle().ToInt64().ToString(), + second.DangerousGetHandle().ToInt64().ToString(), marker }); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + Assert.Equal(0u, await lease.WaitForExitAsync(timeout.Token)); + var lines = File.ReadAllLines(marker); + Assert.Equal(2, lines.Length); + Assert.DoesNotContain(lines, path => path.EndsWith(fixture.Dependency, StringComparison.OrdinalIgnoreCase)); + } + + [NativeAotFact] + public async Task AnotherProcessCannotReplaceHeldImageOrAncestor() + { + if (!OperatingSystem.IsWindows()) return; + var native = Environment.GetEnvironmentVariable("GU_WINDOWS_SNAPSHOT_PEER") + ?? throw new InvalidOperationException("The Native AOT snapshot peer is required."); + using var fixture = new Fixture(); + using var lease = fixture.Create(); + var marker = Path.Combine(fixture.Root, "conflicts.txt"); + var start = new ProcessStartInfo(native) + { + UseShellExecute = false, RedirectStandardError = true, CreateNoWindow = true + }; + foreach (var argument in new[] { "--snapshot-conflict-probe", lease.ImagePath, fixture.Staging, marker }) + start.ArgumentList.Add(argument); + using var process = Process.Start(start) ?? throw new InvalidOperationException("Could not start the probe."); + var errors = process.StandardError.ReadToEndAsync(); + try + { + await process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(30)); + Assert.True(process.ExitCode == 0, await errors); + Assert.Equal(new[] { "32", "32" }, File.ReadAllLines(marker)); + } + + finally + { + if (!process.HasExited) process.Kill(); + await process.WaitForExitAsync(); + } + } + + [NativeAotTheory] + [InlineData("write")] + [InlineData("delete")] + public async Task PriorCrossProcessWriteOrDeleteHandleRejectsSnapshot(string access) + { + var native = Environment.GetEnvironmentVariable("GU_WINDOWS_SNAPSHOT_PEER") + ?? throw new InvalidOperationException("The Native AOT snapshot peer is required."); + using var fixture = new Fixture(); + var image = new WindowsSnapshotFile(fixture.Image, SHA256.HashData(File.ReadAllBytes(fixture.Image))); + var start = new ProcessStartInfo(native) + { + UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, + RedirectStandardError = true, CreateNoWindow = true + }; + foreach (var argument in new[] { "--hold-file-probe", fixture.Image, access }) + start.ArgumentList.Add(argument); + using var process = Process.Start(start) ?? throw new InvalidOperationException("Could not start the probe."); + var errors = process.StandardError.ReadToEndAsync(); + try + { + var ready = await process.StandardOutput.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(30)); + Assert.True(ready == "ready", ready ?? await errors); + var failure = Assert.Throws(() => WindowsImageSnapshotLease.Create( + true, fixture.Staging, image, Array.Empty())); + Assert.Equal(32, failure.NativeErrorCode); + } + finally + { + if (!process.HasExited) await process.StandardInput.WriteLineAsync("release"); + try { await process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(30)); } + finally + { + if (!process.HasExited) + { + process.Kill(); + await process.WaitForExitAsync(); + } + } + } + } + + [NativeAotFact] + public async Task NativePeerReceivesExactArguments() + { + var native = Environment.GetEnvironmentVariable("GU_WINDOWS_SNAPSHOT_PEER") + ?? throw new InvalidOperationException("The Native AOT snapshot peer is required."); + using var fixture = new Fixture(); + File.Copy(native, fixture.Image, overwrite: true); + var marker = Path.Combine(fixture.Root, "arguments.txt"); + var values = new[] { "", "space value", "quote\"value", "slashes\\\\", "trailing space ", "unicode \u6d4b\u8bd5" }; + var arguments = new[] { "--argument-probe", marker }.Concat(values).ToArray(); + var image = new WindowsSnapshotFile(fixture.Image, SHA256.HashData(File.ReadAllBytes(fixture.Image))); + await using var lease = WindowsNativeLaunchLease.Start(WindowsNativeLaunchProfile.TrustedWindowsSystemAndCooperativeNativeAot, + fixture.Staging, image, Array.Empty(), Array.Empty(), TrustedModules(new[] { fixture.Image }), arguments); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + Assert.Equal(0u, await lease.WaitForExitAsync(timeout.Token)); + Assert.Equal(values, File.ReadAllLines(marker).Select(line => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(line)))); + } + + private static string[] TrustedModules(IEnumerable paths) + { + var files = paths.ToArray(); + var application = files.Select(Path.GetFileName).ToHashSet(StringComparer.OrdinalIgnoreCase); + var modules = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var path in files) + { + using var stream = File.OpenRead(path); + using var pe = new PEReader(stream); + var header = pe.PEHeaders.PEHeader ?? throw new InvalidDataException("Invalid PE image."); + void ReadTable(DirectoryEntry table, bool delay) + { + if (table.RelativeVirtualAddress == 0) return; + var reader = pe.GetSectionData(table.RelativeVirtualAddress).GetReader(0, table.Size); + var size = delay ? 32 : 20; + while (reader.RemainingBytes >= size) + { + var fields = new uint[delay ? 8 : 5]; + for (var i = 0; i < fields.Length; i++) fields[i] = reader.ReadUInt32(); + if (fields.All(value => value == 0)) return; + var address = fields[delay ? 1 : 3]; + var name = pe.GetSectionData(checked((int)address)).GetReader(); + var bytes = new List(); + byte value; + while ((value = name.ReadByte()) != 0) bytes.Add(value); + var module = System.Text.Encoding.ASCII.GetString(bytes.ToArray()); + if (!application.Contains(module)) modules.Add(module); + } + throw new InvalidDataException("Invalid test PE import table."); + } + ReadTable(header.ImportTableDirectory, delay: false); + ReadTable(header.DelayImportTableDirectory, delay: true); + } + return modules.ToArray(); + } + + public sealed class NativeAotFactAttribute : FactAttribute + { + public NativeAotFactAttribute() + { + if (!OperatingSystem.IsWindows() || string.IsNullOrEmpty(Environment.GetEnvironmentVariable("GU_WINDOWS_SNAPSHOT_PEER"))) + Skip = "The Windows Native AOT snapshot peer is required."; + } + } + + public sealed class NativeAotTheoryAttribute : TheoryAttribute + { + public NativeAotTheoryAttribute() + { + if (!OperatingSystem.IsWindows() || string.IsNullOrEmpty(Environment.GetEnvironmentVariable("GU_WINDOWS_SNAPSHOT_PEER"))) + Skip = "The Windows Native AOT snapshot peer is required."; + } + } + + [SupportedOSPlatform("windows")] + private sealed class Fixture : IDisposable + { + private readonly string _root = Path.Combine(Path.GetTempPath(), "gu-snapshot-test-" + Guid.NewGuid().ToString("N")); + public string Root => _root; + public string Staging { get; } + public string Image { get; } + public string Dependency { get; } + + public Fixture() + { + var user = WindowsIdentity.GetCurrent().User ?? throw new InvalidOperationException(); + var security = new DirectorySecurity(); + security.SetOwner(user); + security.SetAccessRuleProtection(true, false); + security.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.FullControl, + InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, + PropagationFlags.None, AccessControlType.Allow)); + new DirectoryInfo(_root).Create(security); + Staging = Path.Combine(_root, "staging"); + new DirectoryInfo(Staging).Create(security); + Image = Path.Combine(_root, "image.exe"); + Dependency = Path.Combine(_root, "native.dll"); + File.WriteAllText(Image, "image bytes"); + File.WriteAllText(Dependency, "dependency bytes"); + } + + public WindowsImageSnapshotLease Create() => WindowsImageSnapshotLease.Create(true, Staging, + new WindowsSnapshotFile(Image, SHA256.HashData(File.ReadAllBytes(Image))), + new[] { new WindowsSnapshotFile(Dependency, SHA256.HashData(File.ReadAllBytes(Dependency))) }); + + public void Dispose() + { + if (Directory.Exists(_root)) Directory.Delete(_root, recursive: true); + } + + } + + [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); + + [StructLayout(LayoutKind.Sequential)] + private struct SecurityAttributes + { + public int Length; + public IntPtr SecurityDescriptor; + [MarshalAs(UnmanagedType.Bool)] public bool InheritHandle; + } + [DllImport("kernel32.dll", EntryPoint = "CreateFileW", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern SafeFileHandle CreateInheritableFile(string path, uint access, uint share, ref SecurityAttributes security, + uint creation, uint flags, IntPtr template); + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool TerminateProcess(SafeProcessHandle process, uint exitCode); +} diff --git a/tests/NativeSnapshotWorker/NativeSnapshotWorker.csproj b/tests/NativeSnapshotWorker/NativeSnapshotWorker.csproj new file mode 100644 index 00000000..601478a7 --- /dev/null +++ b/tests/NativeSnapshotWorker/NativeSnapshotWorker.csproj @@ -0,0 +1,11 @@ + + + Exe + net10.0 + enable + enable + + + + + diff --git a/tests/NativeSnapshotWorker/Program.cs b/tests/NativeSnapshotWorker/Program.cs new file mode 100644 index 00000000..cac01072 --- /dev/null +++ b/tests/NativeSnapshotWorker/Program.cs @@ -0,0 +1,111 @@ +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using GeneralUpdate.Core.Security; +using Microsoft.Win32.SafeHandles; +using Microsoft.Data.Sqlite; + +if (args.Length == 3 && args[0] == "--hold-file-probe") +{ + using var file = Native.CreateFile(args[1], args[2] == "write" ? 0x40000000u : 0x00010000u, + 7, IntPtr.Zero, 3, 0x80, IntPtr.Zero); + if (file.IsInvalid) throw new InvalidOperationException($"CreateFile failed: {Marshal.GetLastWin32Error()}"); + Console.WriteLine("ready"); + await Console.Out.FlushAsync(); + await Console.In.ReadLineAsync(); + return 0; +} +if (args.Length >= 5 && args[0] == "--snapshot-owner-probe") +{ + var image = new WindowsSnapshotFile(args[2], SHA256.HashData(File.ReadAllBytes(args[2]))); + var dll = new WindowsSnapshotFile(args[3], SHA256.HashData(File.ReadAllBytes(args[3]))); + await using var lease = WindowsNativeLaunchLease.Start( + WindowsNativeLaunchProfile.TrustedWindowsSystemAndCooperativeNativeAot, + args[1], image, new[] { dll }, new[] { "e_sqlite3.dll" }, args.Skip(5).ToArray(), new[] { "--snapshot-probe", args[4], "wait" }); + await Console.In.ReadLineAsync(); + return 0; +} +if (args.Length == 3 && args[0] == "--snapshot-probe") +{ + try + { + if (!Native.SetDefaultDllDirectories(0x00000200 | 0x00000800)) + throw new InvalidOperationException($"SetDefaultDllDirectories failed: {Marshal.GetLastWin32Error()}"); + var sqlitePath = Path.Combine(AppContext.BaseDirectory, "e_sqlite3.dll"); + if (Native.LoadLibraryEx(sqlitePath, IntPtr.Zero, 0x00000100 | 0x00000800) == IntPtr.Zero) + throw new InvalidOperationException($"Loading the staged SQLite library failed: {Marshal.GetLastWin32Error()}"); + using var connection = new SqliteConnection("Data Source=:memory:"); + connection.Open(); + var module = Native.GetModuleHandle("e_sqlite3.dll"); + if (module == IntPtr.Zero) throw new InvalidOperationException("SQLite native module not found."); + var path = new StringBuilder(32768); + if (Native.GetModuleFileName(module, path, (uint)path.Capacity) == 0) + throw new InvalidOperationException($"GetModuleFileName failed: {Marshal.GetLastWin32Error()}"); + File.WriteAllLines(args[1], new[] { path.ToString(), Environment.ProcessId.ToString() }); + File.WriteAllText(args[1] + ".ready", "ready"); + if (args[2] == "wait") await Task.Delay(Timeout.InfiniteTimeSpan); + return 0; + } + catch (Exception ex) + { + File.WriteAllText(args[1] + ".error", ex.ToString()); + return 91; + } +} +if (args.Length == 4 && args[0] == "--handle-list-probe") +{ + File.WriteAllLines(args[3], new[] { Native.HandlePath(args[1]), Native.HandlePath(args[2]) }); + return 0; +} +if (args.Length >= 2 && args[0] == "--argument-probe") +{ + File.WriteAllLines(args[1], args.Skip(2).Select(value => Convert.ToBase64String(Encoding.UTF8.GetBytes(value)))); + return 0; +} +if (args.Length == 4 && args[0] == "--snapshot-conflict-probe") +{ + var errors = new string[2]; + for (var i = 0; i < errors.Length; i++) + { + var original = args[i + 1]; + var replacement = original + ".moved"; + if (Native.MoveFileEx(original, replacement, 0)) + { + if (!Native.MoveFileEx(replacement, original, 0)) + throw new InvalidOperationException($"Failed to restore moved object: {Marshal.GetLastWin32Error()}"); + errors[i] = "0"; + } + else errors[i] = Marshal.GetLastWin32Error().ToString(); + } + File.WriteAllLines(args[3], errors); + return 0; +} +return 2; + +internal static class Native +{ + internal static string HandlePath(string value) + { + var path = new StringBuilder(32768); + var length = GetFinalPathNameByHandle(new IntPtr(long.Parse(value)), path, (uint)path.Capacity, 0); + return length == 0 ? "" : path.ToString(); + } + + [DllImport("kernel32.dll", EntryPoint = "GetFinalPathNameByHandleW", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern uint GetFinalPathNameByHandle(IntPtr handle, StringBuilder path, uint size, uint flags); + [DllImport("kernel32.dll", EntryPoint = "MoveFileExW", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool MoveFileEx(string existing, string target, uint flags); + [DllImport("kernel32.dll", EntryPoint = "GetModuleHandleW", CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern IntPtr GetModuleHandle(string name); + [DllImport("kernel32.dll", EntryPoint = "GetModuleFileNameW", CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern uint GetModuleFileName(IntPtr module, StringBuilder path, uint size); + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool SetDefaultDllDirectories(uint flags); + [DllImport("kernel32.dll", EntryPoint = "LoadLibraryExW", CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern IntPtr LoadLibraryEx(string path, IntPtr file, uint flags); + [DllImport("kernel32.dll", EntryPoint = "CreateFileW", CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern SafeFileHandle CreateFile(string path, uint access, uint share, IntPtr security, + uint creation, uint flags, IntPtr template); +}