using System.ComponentModel; using System.IO.Pipes; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; using XFEToolBox.Client.Core.Search.Service; namespace XFEToolBox.Indexing.Service.IPC; internal static class SecurePipeFactory { internal const string SecurityDescriptor = "D:P(D;;GA;;;NU)(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x0012019B;;;AU)"; internal static NamedPipeServerStream Create(bool first, string? testName = null) { if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(SecurityDescriptor, 1, out var descriptor, out _)) throw new Win32Exception(Marshal.GetLastWin32Error()); try { var security = new SecurityAttributes { Length = Marshal.SizeOf(), Descriptor = descriptor }; // Local authenticated users may exchange messages, but cannot create pipe // instances. Remote clients are denied both in the DACL and by the pipe mode. var handle = CreateNamedPipeW(@"\\.\pipe\" + (testName ?? IndexingServiceProtocol.PipeName), 3u | 0x40000000u | (first ? 0x00080000u : 0u), 0x00000008, 8, 65536, 65536, 0, ref security); if (handle.IsInvalid) { var error = Marshal.GetLastWin32Error(); handle.Dispose(); throw new Win32Exception(error); } return new(PipeDirection.InOut, true, false, handle); } finally { LocalFree(descriptor); } } [StructLayout(LayoutKind.Sequential)] private struct SecurityAttributes { public int Length; public IntPtr Descriptor; public int InheritHandle; } [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool ConvertStringSecurityDescriptorToSecurityDescriptorW( string text, uint revision, out IntPtr descriptor, out uint size); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern SafePipeHandle CreateNamedPipeW(string name, uint openMode, uint pipeMode, uint instances, uint outSize, uint inSize, uint timeout, ref SecurityAttributes security); [DllImport("kernel32.dll")] private static extern IntPtr LocalFree(IntPtr memory); }