调用NamedPipeServerStream.SetAccessControl时“尝试执行未经授权的操作”

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

我正在尝试使用PipeSecurity来确保NamedPipeServerStream。当我在下面的代码段中调用this.pipeServer.SetAccessControl(pipeSecurity)时,我得到以下异常:

Attempted to perform an unauthorized operation.
    at System.Security.AccessControl.Win32.SetSecurityInfo(ResourceType type, String name, SafeHandle handle, SecurityInfos securityInformation, SecurityIdentifier owner, SecurityIdentifier group, GenericAcl sacl, GenericAcl dacl)
    at System.Security.AccessControl.NativeObjectSecurity.Persist(String name, SafeHandle handle, AccessControlSections includeSections, Object exceptionContext)
    at System.Security.AccessControl.NativeObjectSecurity.Persist(SafeHandle handle, AccessControlSections includeSections, Object exceptionContext)
    at System.IO.Pipes.PipeSecurity.Persist(SafeHandle handle)

码:

this.pipeServer =
    new NamedPipeServerStream(
        pipeName,
        PipeDirection.InOut,
        1,
        PipeTransmissionMode.Byte,
        PipeOptions.Asynchronous);

PipeSecurity pipeSecurity = new PipeSecurity();

WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);

if (principal.IsInRole(WindowsBuiltInRole.Administrator))
{
    // Allow the Administrators group full access to the pipe.
    pipeSecurity.AddAccessRule(new PipeAccessRule(
        new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null).Translate(typeof(NTAccount)),
        PipeAccessRights.FullControl, AccessControlType.Allow));
} else {
    // Allow current user read and write access to the pipe.
    pipeSecurity.AddAccessRule(new PipeAccessRule(
        WindowsIdentity.GetCurrent().User,
        PipeAccessRights.ReadWrite, AccessControlType.Allow));
}

this.pipeServer.SetAccessControl(pipeSecurity);

我做错了什么想法?

使用System.IO.AccessControl nuget包在.NET Framework(目标net451)和.NET Standard 1.6中发生这种情况:

https://www.nuget.org/packages/System.IO.Pipes.AccessControl/

编辑:

我能够使用#ifdef来使用适用于.NET Framework的the following constructor

public NamedPipeServerStream(string pipeName,System.IO.Pipes.PipeDirection direction,int maxNumberOfServerInstances,System.IO.Pipes.PipeTransmissionMode transmissionMode,System.IO.Pipes.PipeOptions options,int inBufferSize,int outBufferSize,System.IO.Pipes.PipeSecurity pipeSecurity )

但是,.NET Standard中不存在此构造函数。我尝试使用添加到.NET Core的this function

PipesAclExtensions.SetAccessControl(PipeStream, PipeSecurity)

但这会产生与以前相同的例外。

I created a gist to show this

c# .net named-pipes
1个回答
1
投票

我只是遇到了同样的问题并试图追踪它。

TL; DR

目前的状态(2019年2月)很可悲但却是正确的:它只适用于今天的NET标准中给出的类。

门票参考

在这种情况下,有趣的是* nix相关

可能的解决方法

仍然可以使用本机API调用来根据需要设置安全性,但这不适合胆小的人。一个基本上需要实现这些步骤:


PS:至少我们现在可以在代码中查找它。想象一下20年前遇到这个问题......

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