使用命名管道获取 ProcessID 的安全方法

问题描述 投票:0回答:1

我有一个由 GUI 和服务组成的应用程序。它们在同一台计算机上运行,并通过 WCF 通过命名管道进行通信。

从服务中,我尝试获取通过命名管道调用服务的进程的进程 ID。然而,当我使用 WCF 时,我很难做到这一点。

我创建了一个测试应用程序,允许我使用没有 WCF 的命名管道(直接通过 System.IO.Pipes)来执行此操作 - 但我能弄清楚如何执行此操作的唯一方法,要求我使用 SafePipeHandle.DangerousGetHandle( ).

我想知道是否有人可以给我一些指示

  • 是否可以使用 WCF 或不使用 DangerousGetHandle() 来获取 PID?
  • 使用 SafePipeHandle.DangerousGetHandle() 方法可以吗? (听起来不太安全)

我真的不想将 PID 作为元数据或作为 GUI 消息的一部分发送,因为这很容易被欺骗。

我的示例服务器代码:

static void Main(string[] args)
{
using (var server = new NamedPipeServerStream("TestPipe", PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
{
    Console.WriteLine("Server waiting for connection...");
    server.WaitForConnection();

    using (StreamReader reader = new StreamReader(server))
    {
        string message;
        while ((message = reader.ReadLine()) != null)
        {
            uint clientProcessId;
            if (NativeMethods.GetNamedPipeClientProcessId(server.SafePipeHandle.DangerousGetHandle(), out clientProcessId))
            {
                Console.WriteLine($"Received: {message} from PID {clientProcessId}");
            }
            else
            {
                Console.WriteLine("Failed to get client process ID.");
            }
        }
    }

    server.Disconnect();
}
Console.WriteLine("Server disconnected...");

}

NativeMethods 只是一个包装器:

public static class NativeMethods
{
   [DllImport("kernel32.dll", SetLastError = true)]
   public static extern bool GetNamedPipeClientProcessId(IntPtr Pipe, out uint ClientProcessId);
}

任何指点将不胜感激。我已经完全没有想法了:)

c# wcf named-pipes
1个回答
0
投票

我假设当服务器仍然连接到管道时,管道的句柄将保持有效,因此这是对一般不安全方法的安全使用。

警告的风险是针对标记为无效/重复使用的句柄,但我认为您的代码根本不可能出现这种情况:https://learn.microsoft.com/en-us/dotnet/ api/system.runtime.interopservices.safehandle.dangerousgethandle

© www.soinside.com 2019 - 2024. All rights reserved.