XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Security.AccessControl;
using System.Security.Principal;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Buffers.Binary;
using System.Text;
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using Microsoft.Win32.SafeHandles;
using System.IO.Pipes;
using XFEToolBox.Client.Core.Search;
using XFEToolBox.Client.Core.Search.Service;
using XFEToolBox.Indexing.Service.IPC;
using XFEToolBox.Indexing.Service.Installation;

var root = Path.Combine(Path.GetTempPath(), "xfetoolbox-service-acl-" + Guid.NewGuid().ToString("N"));
var child = Path.Combine(root, "project");
var file = Path.Combine(child, "public.txt");
var secretFolder = Path.Combine(root, "hidden");
var secret = Path.Combine(secretFolder, "private.txt");
var junction = Path.Combine(root, "junction");
Directory.CreateDirectory(child);
Directory.CreateDirectory(secretFolder);
File.WriteAllText(file, "fixture");
File.WriteAllText(secret, "fixture");
var info = new DirectoryInfo(secretFolder);
var original = info.GetAccessControl();
var passed = 0;
try
{
    Check(new CallerFileAccess().IsAccessible(new(file, false)), "Caller-readable file is discoverable");
    Check(new CallerFileAccess(Path.GetPathRoot(root)).IsAccessible(new(file, false)), "Drive-root scope includes descendants");
    Check(new CallerFileAccess(child).IsAccessible(new(file, false)), "Directory scope includes own descendants");
    Check(!new CallerFileAccess(child + "2").IsAccessible(new(file, false)), "Scope rejects path-prefix sibling");
    Check(!new CallerFileAccess().IsAccessible(new(@"\\server\share\file.txt", false)), "UNC/device paths are rejected");
    Check(new CallerFileAccess().IsAccessible(new(Path.Combine(child, "missing.txt"), false)), "Name authorization does not stat each file (USN owns liveness)");
    using var identity = WindowsIdentity.GetCurrent();
    var fileInfo = new FileInfo(file);
    var originalFileAcl = fileInfo.GetAccessControl();
    try
    {
        var deniedFile = fileInfo.GetAccessControl();
        deniedFile.AddAccessRule(new FileSystemAccessRule(identity.User!, FileSystemRights.ReadAttributes | FileSystemRights.ReadData,
            AccessControlType.Deny));
        fileInfo.SetAccessControl(deniedFile);
        Check(new CallerFileAccess().IsAccessible(new(file, false)), "Listable filename is visible even when the file denies read/attributes");
        var readDenied = false;
        try { using var forbidden = File.OpenRead(file); }
        catch (UnauthorizedAccessException) { readDenied = true; }
        Check(readDenied, "Filename search does not grant content access to a denied file");
    }
    finally
    {
        var restoreFile = new FileSecurity();
        restoreFile.SetSecurityDescriptorBinaryForm(originalFileAcl.GetSecurityDescriptorBinaryForm(), AccessControlSections.Access);
        fileInfo.SetAccessControl(restoreFile);
    }
    var denied = info.GetAccessControl();
    denied.AddAccessRule(new FileSystemAccessRule(identity.User!, FileSystemRights.ListDirectory | FileSystemRights.ReadAttributes,
        InheritanceFlags.None, PropagationFlags.None, AccessControlType.Deny));
    info.SetAccessControl(denied);
    Check(!new CallerFileAccess().IsAccessible(new(secret, false)), "Ancestor deny ACL blocks otherwise readable child");
    var visibleSearch = typeof(CallerFileAccess).Assembly.GetType("XFEToolBox.Indexing.Service.Host.IndexingServiceHost")!
        .GetMethod("SearchVisible", BindingFlags.NonPublic | BindingFlags.Static)!;
    var many = new FileSearchIndex();
    many.AddOrUpdate(Enumerable.Range(0, 9000).Select(number => new FileSearchEntry(Path.Combine(secretFolder, $"candidate{number:D5}.txt"), false)));
    many.AddOrUpdate(Enumerable.Range(9000, 200).Select(number => new FileSearchEntry(Path.Combine(child, $"candidate{number:D5}.txt"), false)));
    var calls = 0;
    Func<int, int, Func<FileSearchEntry, bool>?, FileSearchResults?> ranked = (offset, limit, filter) =>
    {
        calls++;
        return many.TrySearch("*", offset, limit, default, filter);
    };
    var later = (FileSearchResults)visibleSearch.Invoke(null, [100, new CallerFileAccess(), false, ranked, CancellationToken.None])!;
    Check(later.Items.Count == 101 && later.Items.All(item => item.Entry.DirectoryPath == child), "ACL fallback finds allowed names beyond 8192 hidden-prefix candidates");
    Check(later.TotalMatches == 200 && calls == 9, "Fallback counts only authorized matches, with bounded ranked-prefix passes");
    calls = 0;
    var leading = (FileSearchResults)visibleSearch.Invoke(null, [10, new CallerFileAccess(child), true, ranked, CancellationToken.None])!;
    Check(leading.Items.Count == 11 && leading.TotalMatches == 11 && calls == 1, "Leading accessible candidates return early without exposing global counts");
    RestoreAcl();
    Check(new CallerFileAccess().IsAccessible(new(secret, false)), "New request rechecks changed ACL (no cross-request grant cache)");
    Junction.Create(junction, child);
    Check(!new CallerFileAccess().IsAccessible(new(junction, true)), "Directory reparse points are not disclosed");
    Check(!new CallerFileAccess().IsAccessible(new(Path.Combine(junction, "public.txt"), false)), "Traversal through a junction is rejected");
    var rejectPath = typeof(IndexingServiceInstaller).GetMethod("RejectReparsePath", BindingFlags.NonPublic | BindingFlags.Static)!;
    Check(Throws<InvalidDataException>(() => rejectPath.Invoke(null, [Path.Combine(junction, "public.txt")])), "Installer rejects reparse ancestors without installation");
    var validate = typeof(IndexingServiceInstaller).GetMethod("RequireTrustedSecurity", BindingFlags.NonPublic | BindingFlags.Static)!;
    var userOwned = new DirectorySecurity();
    userOwned.SetOwner(identity.User!);
    Check(Throws<UnauthorizedAccessException>(() => validate.Invoke(null, [userOwned])), "Installer rejects a user-owned privileged cache");
    var userWritable = new DirectorySecurity();
    userWritable.SetOwner(new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null));
    userWritable.AddAccessRule(new FileSystemAccessRule(identity.User!, FileSystemRights.Write, AccessControlType.Allow));
    Check(Throws<UnauthorizedAccessException>(() => validate.Invoke(null, [userWritable])), "Installer rejects a user-writable privileged cache");
    var trusted = new DirectorySecurity();
    trusted.SetOwner(new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null));
    trusted.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null),
        FileSystemRights.FullControl, AccessControlType.Allow));
    validate.Invoke(null, [trusted]);
    Check(true, "Installer accepts a SYSTEM-owned restricted cache descriptor");
    var factory = typeof(CallerFileAccess).Assembly.GetType("XFEToolBox.Indexing.Service.IPC.SecurePipeFactory")!
        .GetMethod("Create", BindingFlags.NonPublic | BindingFlags.Static)!;
    var pipeName = "xfetoolbox-service-security-" + Guid.NewGuid().ToString("N");
    using var pipe = (NamedPipeServerStream)factory.Invoke(null, [true, pipeName])!;
    Check(Throws<System.ComponentModel.Win32Exception>(() => factory.Invoke(null, [true, pipeName])), "First-pipe-instance prevents duplicate ownership");
    if (!new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator))
    {
        Check(Throws<System.ComponentModel.Win32Exception>(() => factory.Invoke(null, [false, pipeName])), "Ordinary user cannot add an impersonating pipe instance");
    }
    var waiting = pipe.WaitForConnectionAsync();
    using var connection = NativePipe.Connect(pipeName, 0x0012019B);
    Check(!connection.IsInvalid, "Ordinary client can use least-privilege pipe rights");
    using var client = new NamedPipeClientStream(PipeDirection.InOut, true, true, connection);
    await waiting;
    await IndexingServiceProtocol.WriteAsync(client, new IndexingServiceRequest(1, "status"), 16384, default);
    var request = await IndexingServiceProtocol.ReadAsync<IndexingServiceRequest>(pipe, 16384, default);
    var impersonated = false;
    pipe.RunAsClient(() =>
    {
        using var caller = WindowsIdentity.GetCurrent(true);
        impersonated = caller is not null && caller.User == identity.User && caller.ImpersonationLevel == TokenImpersonationLevel.Impersonation;
    });
    Check(impersonated && request.Operation == "status", "Pipe keeps the actual caller's impersonation identity");
    var verifier = typeof(IndexingServiceClient).Assembly.GetType("XFEToolBox.Client.Core.Search.Service.IndexingServiceTrust")!
        .GetMethod("IsTrustedServer", BindingFlags.NonPublic | BindingFlags.Static)!;
    Check(!(bool)verifier.Invoke(null, [client.SafePipeHandle])!, "Client rejects a pipe not owned by the SCM-registered SYSTEM service");
    var monitorMethod = typeof(CallerFileAccess).Assembly.GetType("XFEToolBox.Indexing.Service.Host.IndexingServiceHost")!
        .GetMethod("ObserveClientDisconnectAsync", BindingFlags.NonPublic | BindingFlags.Static)!;
    using var abandonedRequest = new CancellationTokenSource();
    var unfinished = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
    var monitoring = (Task)monitorMethod.Invoke(null, [pipe, abandonedRequest, unfinished.Task])!;
    var queryCancelled = Task.Run(() =>
    {
        Func<int, int, Func<FileSearchEntry, bool>?, FileSearchResults?> slowQuery = (_, _, _) =>
        {
            while (!abandonedRequest.IsCancellationRequested) Thread.SpinWait(100);
            return null;
        };
        return visibleSearch.Invoke(null, [100, new CallerFileAccess(), false, slowQuery, abandonedRequest.Token]);
    });
    var cancelWatch = Stopwatch.StartNew();
    client.Dispose();
    Check(await Task.WhenAny(monitoring, Task.Delay(2000)) == monitoring, "Disconnected-client monitor terminates promptly");
    await monitoring;
    await queryCancelled;
    Check(abandonedRequest.IsCancellationRequested && cancelWatch.ElapsedMilliseconds < 500,
        "Disconnect cancels a running metadata query within 500 ms instead of the 4 s deadline");
    pipe.Disconnect();
    var waitAgain = pipe.WaitForConnectionAsync();
    using var nextHandle = NativePipe.Connect(pipeName, 0x0012019B);
    using var nextClient = new NamedPipeClientStream(PipeDirection.InOut, true, true, nextHandle);
    await waitAgain;
    using var successfulRequest = new CancellationTokenSource();
    var success = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
    var cancellationExceptions = 0;
    void ObserveCancel(object? sender, FirstChanceExceptionEventArgs args)
    {
        if (args.Exception is OperationCanceledException && args.Exception.StackTrace?.Contains("IndexingServiceHost", StringComparison.Ordinal) == true)
            Interlocked.Increment(ref cancellationExceptions);
    }
    AppDomain.CurrentDomain.FirstChanceException += ObserveCancel;
    try
    {
        var successMonitor = (Task)monitorMethod.Invoke(null, [pipe, successfulRequest, success.Task])!;
        await Task.Delay(120);
        Check(!successfulRequest.IsCancellationRequested, "An idle connected client is not mistaken for a disconnect");
        success.TrySetResult();
        await successMonitor;
        Check(!successfulRequest.IsCancellationRequested && cancellationExceptions == 0,
            "Successful requests stop monitoring without cancellation exceptions");
    }
    finally { AppDomain.CurrentDomain.FirstChanceException -= ObserveCancel; }
    var earlyName = pipeName + "-early";
    using var earlyServer = (NamedPipeServerStream)factory.Invoke(null, [true, earlyName])!;
    var earlyWaiting = earlyServer.WaitForConnectionAsync();
    using var earlyHandle = NativePipe.Connect(earlyName, 0x0012019B);
    using var earlyClient = new NamedPipeClientStream(PipeDirection.InOut, true, true, earlyHandle);
    await earlyWaiting;
    earlyClient.Dispose();
    var earlyRead = await earlyServer.ReadAsync(new byte[4]);
    Check(earlyRead == 0 && !earlyServer.IsConnected, "Client disconnect before writing sets managed pipe to Broken/IsConnected=false");
    using var poisoned = NativePipe.Connect(earlyName, 0x0012019B);
    var poisonError = Marshal.GetLastWin32Error();
    Check(poisoned.IsInvalid && poisonError == 231, "Broken native instance remains ERROR_PIPE_BUSY until explicitly disconnected");
    var resetBroken = typeof(CallerFileAccess).Assembly.GetType("XFEToolBox.Indexing.Service.Host.IndexingServiceHost")!
        .GetMethod("ResetClientConnection", BindingFlags.NonPublic | BindingFlags.Static)!;
    resetBroken.Invoke(null, [earlyServer]);
    var healthyWaiting = earlyServer.WaitForConnectionAsync();
    using var healthyHandle = NativePipe.Connect(earlyName, 0x0012019B);
    using var healthyClient = new NamedPipeClientStream(PipeDirection.InOut, true, true, healthyHandle);
    await healthyWaiting;
    Check(earlyServer.IsConnected, "Explicit Disconnect resets a broken instance for new requests");
    var drainName = pipeName + "-drain";
    using var drainServer = (NamedPipeServerStream)factory.Invoke(null, [true, drainName])!;
    var drainWaiting = drainServer.WaitForConnectionAsync();
    using var drainHandle = NativePipe.Connect(drainName, 0x0012019B);
    using var drainClient = new NamedPipeClientStream(PipeDirection.InOut, true, true, drainHandle);
    await drainWaiting;
    var drainResponse = new IndexingServiceResponse(1, new(false, 0, 1, 1));
    await IndexingServiceProtocol.WriteAsync(drainServer, drainResponse, 16384, default);
    var waitForClose = typeof(CallerFileAccess).Assembly.GetType("XFEToolBox.Indexing.Service.Host.IndexingServiceHost")!
        .GetMethod("WaitForClientCloseAsync", BindingFlags.NonPublic | BindingFlags.Static)!;
    using var drainBudget = new CancellationTokenSource(TimeSpan.FromSeconds(2));
    var draining = (Task)waitForClose.Invoke(null, [drainServer, drainBudget.Token])!;
    await Task.Delay(75);
    Check(!draining.IsCompleted, "Server retains unread response bytes for a delayed ordinary client");
    var received = await IndexingServiceProtocol.ReadAsync<IndexingServiceResponse>(drainClient, 16384, default);
    Check(received.Status.ReadyVolumes == 1, "Delayed client receives the complete framed response before disconnect");
    drainClient.Dispose();
    await draining;
    resetBroken.Invoke(null, [drainServer]);
    Check(!drainServer.IsConnected, "Response completion resets the EOF/Broken instance for reuse");
    passed += InstallerSourceSafetyTests.Run();
    Console.WriteLine($"PASS {passed} isolated metadata security checks; no service installation or volume scan.");
}
finally
{
    RestoreAcl();
    if (Directory.Exists(junction)) Directory.Delete(junction);
    File.Delete(file);
    File.Delete(secret);
    Directory.Delete(child);
    Directory.Delete(secretFolder);
    Directory.Delete(root);
}

bool Throws<T>(Action action) where T : Exception
{
    try { action(); return false; }
    catch (TargetInvocationException error) when (error.InnerException is T) { return true; }
}

void Check(bool result, string name)
{
    if (!result) throw new InvalidOperationException(name);
    passed++;
    Console.WriteLine("PASS " + name);
}

void RestoreAcl()
{
    var restore = new DirectorySecurity();
    restore.SetSecurityDescriptorBinaryForm(original.GetSecurityDescriptorBinaryForm(), AccessControlSections.Access);
    info.SetAccessControl(restore);
}

static class Junction
{
    public static void Create(string path, string target)
    {
        Directory.CreateDirectory(path);
        var substitute = Encoding.Unicode.GetBytes(@"\??\" + target);
        var print = Encoding.Unicode.GetBytes(target);
        var buffer = new byte[20 + substitute.Length + print.Length];
        BinaryPrimitives.WriteUInt32LittleEndian(buffer, 0xA0000003);
        BinaryPrimitives.WriteUInt16LittleEndian(buffer.AsSpan(4), (ushort)(buffer.Length - 8));
        BinaryPrimitives.WriteUInt16LittleEndian(buffer.AsSpan(10), (ushort)substitute.Length);
        BinaryPrimitives.WriteUInt16LittleEndian(buffer.AsSpan(12), (ushort)(substitute.Length + 2));
        BinaryPrimitives.WriteUInt16LittleEndian(buffer.AsSpan(14), (ushort)print.Length);
        substitute.CopyTo(buffer.AsSpan(16));
        print.CopyTo(buffer.AsSpan(18 + substitute.Length));
        using var handle = CreateFileW(path, 0x40000000, 0, IntPtr.Zero, 3, 0x02000000 | 0x00200000, IntPtr.Zero);
        if (handle.IsInvalid || !DeviceIoControl(handle, 0x000900A4, buffer, buffer.Length, IntPtr.Zero, 0, out _, IntPtr.Zero))
            throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
    }

    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern SafeFileHandle CreateFileW(string path, uint access, uint share, IntPtr security, uint mode, uint flags, IntPtr template);
    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DeviceIoControl(SafeFileHandle handle, uint code,
        byte[] input, int inputSize, IntPtr output, int outputSize, out uint bytes, IntPtr overlapped);
}

static class NativePipe
{
    internal static SafePipeHandle Connect(string name, uint access) => CreateFileW(@"\\.\pipe\" + name, access, 0,
        IntPtr.Zero, 3, 0x40000000 | 0x00100000 | 0x00020000, IntPtr.Zero);
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern SafePipeHandle CreateFileW(string name, uint access, uint share, IntPtr security,
        uint creation, uint attributes, IntPtr template);
}