Search code examples
c#named-pipes.net-8.0

NamedPipeClientStream and System.UnauthorizedAccessException


I'm trying to use named pipes to let a Windows service and an application share messages.

SERVICE

var ps = new PipeSecurity();
//ps.SetAccessRule(new PipeAccessRule("Everyone",
    PipeAccessRights.ReadWrite, AccessControlType.Allow));
//ps.SetAccessRule(new PipeAccessRule(
//    new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null),
//    PipeAccessRights.ReadWrite,
//    AccessControlType.Allow));
//ps.SetAccessRule(new PipeAccessRule(
//    new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null),
//    PipeAccessRights.ReadWrite,
//    AccessControlType.Allow));
ps.SetAccessRule(new PipeAccessRule(
    new SecurityIdentifier(WellKnownSidType.WorldSid, null),
    PipeAccessRights.ReadWrite,
    AccessControlType.Allow));

var serverPipe = new NamedPipeServerStream(NamedPipeHelper.PipeName, 
    PipeDirection.InOut, 1, 
    PipeTransmissionMode.Message);
serverPipe.SetAccessControl(ps);
await serverPipe.WaitForConnectionAsync(ct);

APPLICATION

var clientPipe = new NamedPipeClientStream(".", NamedPipeHelper.PipeName, 
    PipeDirection.InOut);    
await clientPipe.ConnectAsync(TimeSpan.FromSeconds(3), ct);

As soon as application tries to connect to service, I get

System.UnauthorizedAccessException: Access to the path is denied

As you can see I set server security and also tried several different solutions, but nothing worked.
I've also tried to run the service as a simple application (running elevated), but when client connects from an unprivileged account I get the error.
If a run the app with a privileged user, connection works (both with service and the server running as a simple app).

Several blogs and websites are saying solution is to pass security within the ctor, but with net8 this is not possible.

I'm stuck, don't know how to solve this.


Solution

  • After a lot of reaserch I dig into this post and found David Steinberg's answer: that's the only working solution!

    var serverPipe =
        NamedPipeServerStreamAcl.Create(NamedPipeHelper.PipeName, 
        PipeDirection.InOut, 10, PipeTransmissionMode.Message, 
        PipeOptions.Asynchronous, default, default, ps);
    

    I hope this is not the intended behaviour of namedserverpipe and that it will be fixed in the future, 'cause it is absolutely not straigthforward to understand how you should use it.
    Why can't we use the regular ctor?