C# – Named pipe client unable to connect to server running as Network Service

cnamed-pipespermissionswindowswindows-services

I have a service running under the Network Service account. The service just sets up a named pipe and listens for connections:

NamedPipeServerStream listeningPipe = new NamedPipeServerStream("ourservicepipe",
    PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, 
    PipeTransmissionMode.Message, PipeOptions.Asynchronous);
listeningPipe.BeginWaitForConnection(OnPipeConnected, listeningPipe);

I have an application running on a standard user account on the same machine. It tries to connect to the named pipe created by the service:

NamedPipeClientStream pipe = new NamedPipeClientStream(".", "ourservicepipe", 
    PipeDirection.InOut, PipeOptions.Asynchronous);
pipe.Connect(2000);
pipe.ReadMode = PipeTransmissionMode.Message;

When I call Connect, it ends up throwing an InvalidOperationException. If I run the service on the same user, it connects fine. If I run the client as an administrator, it connects fine. This leads me to believe the problem is with permissions, but I have no idea which permissions I need to set during installation.

How can I allow the client to connect to the server, without requiring that the client run as an administrator?

Best Answer

Pipe server is created with the default service DACL so that only the administrator or system user can connect to the pipe. You need to set the pipe server with proper access rules to make all client connection to succeed. Below is the code to set the access rule to access everyone to access the pipe:

    PipeSecurity pipeSa = new PipeSecurity(); 
    pipeSa.SetAccessRule(new PipeAccessRule("Everyone", 
                    PipeAccessRights.ReadWrite, AccessControlType.Allow)); 
    listeningPipe.SetAccessControl(pipeSa);

It always better to define only a minimal set of users to access the pipe server to make it secure.

Related Topic