如何在.NET Core中设置NamedPipeServerStream的管道安全性

12

我正在将一个库从.NET Framework 4.6.1移植到.NET Standard 2.0。在Framework中,NamedPipeServerStream构造函数可以接受一个PipeSecurity参数,但在Core中没有这个选项。如何在Core中设置NamedPipeServerStream的安全性?

2个回答

14

Net 6.0引入了NamedPipeServerStreamAcl类

您可以使用Create方法创建带有PipeSecurity的流...

using System.IO.Pipes;
using System.Security.AccessControl;
using System.Security.Principal;

if (!System.OperatingSystem.IsWindows())
    throw new PlatformNotSupportedException("Windows only");

SecurityIdentifier securityIdentifier = new SecurityIdentifier(
    WellKnownSidType.AuthenticatedUserSid, null);

PipeSecurity pipeSecurity = new PipeSecurity();
pipeSecurity.AddAccessRule(new PipeAccessRule(securityIdentifier,
    PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance,
    AccessControlType.Allow));

NamedPipeServerStream stream = NamedPipeServerStreamAcl.Create(
    "SecurityTestPipe", PipeDirection.InOut,
    NamedPipeServerStream.MaxAllowedServerInstances,
    PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 0, 0, pipeSecurity);

3

看起来这是一个已知的问题,详见System.IO.Pipes.AccessControl包无法工作 #26869。最后一篇帖子中提到了一种解决方法,建议使用NamedPipeServerStream.NetFrameworkVersion nuget包,它将公开NamedPipeServerStreamConstructors.New(...),应该能够模拟所有完整 .NET Framework 构造函数的行为。

下面是nuget的github代码示例:

using System.IO.Pipes;

var pipeSecurity = new PipeSecurity();
pipeSecurity.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow));

using var serverStream = NamedPipeServerStreamConstructors.New(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.WriteThrough, 0, 0, pipeSecurity);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接