public void SetAccessControl_ConnectedStream() { using (var pair = CreateServerClientPair()) { var security = new PipeSecurity(); pair.readablePipe.SetAccessControl(security); pair.writeablePipe.SetAccessControl(security); } }
/// Invoking the StartAsync event signals that the language server should be started, and triggers a call to this routine. /// This routine contains the logic to start the server and estabilishes a connection that is returned (exceptions here are shown in the info bar of VS). public async Task <Connection> ActivateAsync(CancellationToken token) { await Task.Yield(); Telemetry.SendEvent(Telemetry.ExtensionEvent.Activate); try { #if MANUAL string ServerReaderPipe = $"QsLanguageServerReaderPipe"; string ServerWriterPipe = $"QsLanguageServerWriterPipe"; #else string ServerReaderPipe = $"QsLanguageServerReaderPipe{this.LaunchTime}"; string ServerWriterPipe = $"QsLanguageServerWriterPipe{this.LaunchTime}"; ProcessStartInfo info = new ProcessStartInfo { FileName = LanguageServerPath, UseShellExecute = false, CreateNoWindow = true, Arguments = $"--writer={ServerWriterPipe} --reader={ServerReaderPipe} --log={this.LogFile}" }; Process process = new Process { StartInfo = info }; if (!process.Start()) { return(null); } #endif var bufferSize = 256; var pipeSecurity = new PipeSecurity(); var id = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null); // I don't think WorldSid ("Everyone") is necessary pipeSecurity.AddAccessRule(new PipeAccessRule(id, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow)); var readerPipe = new NamedPipeServerStream(ServerWriterPipe, PipeDirection.InOut, 4, PipeTransmissionMode.Message, PipeOptions.Asynchronous, bufferSize, bufferSize, pipeSecurity); var writerPipe = new NamedPipeServerStream(ServerReaderPipe, PipeDirection.InOut, 4, PipeTransmissionMode.Message, PipeOptions.Asynchronous, bufferSize, bufferSize, pipeSecurity); await readerPipe.WaitForConnectionAsync(token).ConfigureAwait(true); await writerPipe.WaitForConnectionAsync(token).ConfigureAwait(true); return(new Connection(readerPipe, writerPipe)); } catch (Exception e) { Telemetry.SendEvent(Telemetry.ExtensionEvent.Error, ("id", e.GetType().Name), ("reason", e.Message)); throw; } }
private void StartServerPump() { if (!is_running) { return; } try { PipeSecurity ps = new PipeSecurity(); ps.AddAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow)); var npss = new NamedPipeServerStream(IPCCommon.PIPE_NAME, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 512, 512, ps); npss.BeginWaitForConnection(async_result => { try { using (var npss_in_callback = (NamedPipeServerStream)async_result.AsyncState) { npss_in_callback.EndWaitForConnection(async_result); npss_in_callback.WaitForPipeDrain(); StreamReader sr = new StreamReader(npss_in_callback); var line = sr.ReadLine(); if (null != IPCServerMessage) { IPCServerMessage(line); } npss_in_callback.Close(); // Listen for another client. Note that this is NOT recursive as we are currently inside a lambda. StartServerPump(); } } catch (Exception ex) { Logging.Error(ex, "Error while processing pipe connection."); } }, npss); } catch (Exception ex) { Logging.Error(ex, "Error while waiting for pipe connection."); } }
private void StartNamedPipeServer() { if (!StartServer) { return; } #if NETCOREAPP2_1 _server = new NamedPipeServerStream( PipeName, PipeDirection.In, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, PipeOptions.CurrentUserOnly); #elif NET461 using (var currentIdentity = WindowsIdentity.GetCurrent()) { var identifier = currentIdentity.Owner; // Grant full control to the owner so multiple servers can be opened. // Full control is the default per MSDN docs for CreateNamedPipe. var rule = new PipeAccessRule(identifier, PipeAccessRights.FullControl, AccessControlType.Allow); var pipeSecurity = new PipeSecurity(); pipeSecurity.AddAccessRule(rule); pipeSecurity.SetOwner(identifier); _server = new NamedPipeServerStream( PipeName, PipeDirection.In, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 0, 0, pipeSecurity); } #else #error Platform not supported #endif try { _server.BeginWaitForConnection(Listen, null); } catch (ObjectDisposedException) { // The server was disposed before getting a connection } }
public void CreatePipe2() { string ss; if (strPipeName2 == "") { ss = "Cannot create pipe " + strPipeName2; LogMessage(ss);//DataPipeInfoTxt, ss); return; } if (DataSrvHandle != null) { return; } try { PipeSecurity pipeSa = new PipeSecurity(); pipeSa.SetAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow)); DataSrvHandle = new NamedPipeServerStream( strPipeName2, // The unique pipe name. PipeDirection.In, // The pipe is read only NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, // Message type pipe PipeOptions.Asynchronous, // No additional parameters MAX_DATA_SIZE, // Input buffer size MAX_DATA_SIZE, // Output buffer size pipeSa, // Pipe security attributes HandleInheritability.None // Not inheritable ); ss = "The server named pipe " + strPipeName2 + " is created"; LogMessage(ss);//DataPipeInfoTxt, ss); if (EmulatorEnabled == false) { DataSrvHandle.WaitForConnection(); } ss = "The named pipe " + strPipeName2 + " is connected"; LogMessage(ss);//DataPipeInfoTxt, ss); DataPipeConnected = true; } catch (Exception ex) { ss = "Cannot create pipe " + strPipeName2; LogMessage(ss); //DataPipeInfoTxt, ss); LogMessage(ex.Message); //DataPipeInfoTxt, ex.Message); DataPipeConnected = false; } }
public NpListener(string pipeName, int maxConnections = 254, ILog log = null, IStats stats = null) { _log = log ?? _log; _stats = stats ?? _stats; if (maxConnections > 254) { maxConnections = 254; } _maxConnections = maxConnections; this.PipeName = pipeName; _pipeSecurity = new PipeSecurity(); _pipeSecurity.AddAccessRule(new PipeAccessRule(@"Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow)); _pipeSecurity.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().User, PipeAccessRights.FullControl, AccessControlType.Allow)); _pipeSecurity.AddAccessRule(new PipeAccessRule(@"SYSTEM", PipeAccessRights.FullControl, AccessControlType.Allow)); }
private PipeSecurity GetPipeSecurityObject() { if (SidType == WellKnownSidType.NullSid) { return(null); } SecurityIdentifier sid = new SecurityIdentifier(SidType, null); PipeAccessRule pipeAccessRule = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, AccessControlType.Allow); PipeSecurity ps = new PipeSecurity(); ps.AddAccessRule(pipeAccessRule); return(ps); }
static void Main(string[] args) { var ps = new PipeSecurity(); var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null); ps.AddAccessRule(new PipeAccessRule(everyone, PipeAccessRights.FullControl, AccessControlType.Allow)); while (true) { var pipe = new NamedPipeServerStream("testpipe", PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 1024, 1024, ps); pipe.BeginWaitForConnection(new AsyncCallback(ConnectCallBack), pipe); Thread.Sleep(1000); } }
private void CreatePipe() { var pipeSecurity = new PipeSecurity(); pipeSecurity.AddAccessRule(new PipeAccessRule(new SecurityIdentifier( WellKnownSidType.CreatorOwnerSid, null), PipeAccessRights.FullControl, AccessControlType.Allow)); pipeSecurity.AddAccessRule(new PipeAccessRule(new SecurityIdentifier( WellKnownSidType.AuthenticatedUserSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow)); pipe = new NamedPipeServerStream(PIPE_NAME, PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, (int)BUFFER_SIZE_BYTES, (int)BUFFER_SIZE_BYTES, pipeSecurity); pipe.BeginWaitForConnection(HandleConnection, null); }
/// <summary> /// Connect to the given process id and return a pipe. /// Throws on cancellation. /// </summary> /// <param name="processId">Proces id to try to connect to.</param> /// <param name="timeoutMs">Timeout to allow in connecting to process.</param> /// <param name="cancellationToken">Cancellation token to cancel connection to server.</param> /// <param name="pipeStream"> /// An open <see cref="NamedPipeClientStream"/> to the server process or null on failure /// (including IOException). /// </param> /// <returns> /// </returns> private bool TryConnectToProcess(int processId, int timeoutMs, CancellationToken cancellationToken, out NamedPipeClientStream pipeStream) { pipeStream = null; cancellationToken.ThrowIfCancellationRequested(); try { // Machine-local named pipes are named "\\.\pipe\<pipename>". // We use the pipe name followed by the process id. // The NamedPipeClientStream class handles the "\\.\pipe\" part for us. string pipeName = BuildProtocolConstants.PipeName + processId.ToString(); CompilerServerLogger.Log("Attempt to open named pipe '{0}'", pipeName); pipeStream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); cancellationToken.ThrowIfCancellationRequested(); CompilerServerLogger.Log("Attempt to connect named pipe '{0}'", pipeName); pipeStream.Connect(timeoutMs); CompilerServerLogger.Log("Named pipe '{0}' connected", pipeName); cancellationToken.ThrowIfCancellationRequested(); // Verify that we own the pipe. SecurityIdentifier currentIdentity = WindowsIdentity.GetCurrent().Owner; PipeSecurity remoteSecurity = pipeStream.GetAccessControl(); IdentityReference remoteOwner = remoteSecurity.GetOwner(typeof(SecurityIdentifier)); if (remoteOwner != currentIdentity) { CompilerServerLogger.Log("Owner of named pipe is incorrect"); return(false); } return(true); } catch (IOException e) { CompilerServerLogger.LogException(e, "Opening/connecting named pipe"); return(false); } catch (TimeoutException e) { CompilerServerLogger.LogException(e, "Timeout while opening/connecting named pipe"); return(false); } }
private void StartServerListner() { string module = string.Empty, message, messageType, processId; PipeSecurity ps = new PipeSecurity(); ps.AddAccessRule(new PipeAccessRule("Users", PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow)); ps.AddAccessRule(new PipeAccessRule("CREATOR OWNER", PipeAccessRights.FullControl, AccessControlType.Allow)); ps.AddAccessRule(new PipeAccessRule("SYSTEM", PipeAccessRights.FullControl, AccessControlType.Allow)); ps.AddAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow)); using (var pipeStream = new NamedPipeServerStream("PipeToMonitor", PipeDirection.InOut, Monitors.Length, PipeTransmissionMode.Message, PipeOptions.WriteThrough, 1024, 1024, ps)) { pipeStream.WaitForConnection(); using (var sr = new StreamReader(pipeStream)) { while ((message = sr.ReadLine()) != null) { module = message.Split(';')[0]; messageType = message.Split(';')[1]; processId = message.Split(';')[2]; if (module == "Critial Monitor") { criticalProcessId = processId; SpawnProcess("CRITICAL"); } else { nonCriticalProcessId = processId; SpawnProcess("NONCRITICAL"); } switch (messageType) { case "Connected": Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"Connected: {module}"); break; } } } } Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"Connection Lost: {module}"); }
private PipeSecurity CreateSecuritySettings() { var currentUserSid = $@"{Environment.UserDomainName}\{Environment.UserName}"; var pipeAccess = new PipeSecurity(); /*pipeAccess.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.FullControl, * AccessControlType.Allow));*/ pipeAccess.AddAccessRule(new PipeAccessRule(currentUserSid, PipeAccessRights.FullControl, AccessControlType.Allow)); pipeAccess.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.NetworkSid, null), PipeAccessRights.FullControl, AccessControlType.Deny)); pipeAccess.AddAccessRule(new PipeAccessRule( new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null), PipeAccessRights.FullControl, AccessControlType.Deny)); return(pipeAccess); }
private void reInitPipe() { if (pipeServer != null) { pipeServer.Close(); pipeServer = null; } var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); var rule = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow); var sec = new PipeSecurity(); sec.AddAccessRule(rule); pipeServer = new NamedPipeServerStream(HealthCheckSettings.HEALTH_CHECK_PIPE, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 0, 0, sec); pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), pipeServer); }
private static PipeSecurity GetLowLevelPipeSecurity() { PipeSecurity pipeSecurity = new PipeSecurity(); PipeAccessRule aceClients = new PipeAccessRule( new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow); PipeAccessRule aceOwner = new PipeAccessRule( WindowsIdentity.GetCurrent().Owner, PipeAccessRights.FullControl, AccessControlType.Allow); pipeSecurity.AddAccessRule(aceClients); pipeSecurity.AddAccessRule(aceOwner); return(pipeSecurity); }
private void InitAndProcessNPListener(CancellationToken cancellationToken) { // Create the security ACL to allow EVERYONE group to access this pipe for R/W/Pipe-Instance creation System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null); PipeSecurity securityAcl = new PipeSecurity(); securityAcl.AddAccessRule(new PipeAccessRule(sid, PipeAccessRights.ReadWrite | PipeAccessRights.Synchronize | PipeAccessRights.CreateNewInstance, System.Security.AccessControl.AccessControlType.Allow)); // Loop to start a named pipe listener. When a connection is accepted, queue to the ThreadPool and initiate the next listener. while (!cancellationToken.IsCancellationRequested) { NamedPipeServerStream pipeServer = new NamedPipeServerStream("SFBlockStorePipe", PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.WriteThrough, GatewayPayloadConst.payloadHeaderSize, GatewayPayloadConst.payloadHeaderSize, securityAcl); pipeServer.WaitForConnection(); ThreadPool.QueueUserWorkItem((state) => this.ProcessNPClient(pipeServer, cancellationToken)); } }
private NamedPipeServerStream CreateSecuredPipe() { var user = WindowsIdentity.GetCurrent().User; var security = new PipeSecurity(); security.AddAccessRule(new PipeAccessRule( user, PipeAccessRights.FullControl, AccessControlType.Allow)); security.SetOwner(user); security.SetGroup(user); return(new NamedPipeServerStream( pipe, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, MaxBytes, MaxBytes, security)); }
/// <summary> /// Child process thread which will be executed upon calling the MozillaVPN.exe with the "broker" switch. /// </summary> private static void ChildProcess() { // Configure pipe security for the broker pipe PipeSecurity ps = new PipeSecurity(); SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); NTAccount account = (NTAccount)sid.Translate(typeof(NTAccount)); ps.AddAccessRule(new PipeAccessRule(account, PipeAccessRights.ReadWrite, AccessControlType.Allow)); ps.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().Owner, PipeAccessRights.FullControl, AccessControlType.Allow)); // Main child process loop - start the listener thread and listen for commands using (var brokerPipe = new NamedPipeServerStream(ProductConstants.InternalAppName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 512, 512, ps)) { new IPC(brokerPipe).BrokerListenerThread(); } }
public static string[] RunSimulationService(string npipe, string log) { string[] result = new string[5]; try { //https://helperbyte.com/questions/171742/how-to-connect-to-a-named-pipe-without-administrator-rights PipeSecurity ps = new PipeSecurity(); ps.SetAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow)); //logger.TimestampInfo("starting!"); string technique, pbsleep, tsleep, cleanup, variation; using (var pipeServer = new NamedPipeServerStream(npipe, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 4028, 4028, ps)) { var reader = new StreamReader(pipeServer); var writer = new StreamWriter(pipeServer); pipeServer.WaitForConnection(); var line = reader.ReadLine(); if (line.ToLower().StartsWith("technique:")) { string[] options = line.Split(' '); technique = options[0].Replace("technique:", ""); variation = options[1].Replace("variation:", ""); pbsleep = options[2].Replace("pbsleep:", ""); tsleep = options[3].Replace("tsleep:", ""); cleanup = options[4].Replace("cleanup:", ""); writer.WriteLine("ACK"); writer.Flush(); result[0] = technique; result[1] = variation; result[2] = pbsleep; result[3] = tsleep; result[4] = cleanup; return(result); } pipeServer.Disconnect(); } return(result); } catch { return(result); } }
private void WaitForConnection(string pipeName, PipeSecurity pipeSecurity) { NamedPipeServerStream handshakePipe = null; NamedPipeServerStream dataPipe = null; NamedPipeConnection <TRead, TWrite> connection = null; var connectionPipeName = GetNextConnectionPipeName(pipeName); try { // Send the client the name of the data pipe to use handshakePipe = PipeServerFactory.CreateAndConnectPipe(pipeName, pipeSecurity); var stringSerializer = new BinaryFormatterSerializer <string>(); var handshakeWrapper = new PipeStreamWrapper <string, string>(handshakePipe, stringSerializer, stringSerializer); handshakeWrapper.WriteObject(connectionPipeName); handshakeWrapper.WaitForPipeDrain(); handshakeWrapper.Close(); // Wait for the client to connect to the data pipe dataPipe = PipeServerFactory.CreatePipe(connectionPipeName, pipeSecurity); dataPipe.WaitForConnection(); // Add the client's connection to the list of connections connection = ConnectionFactory.CreateConnection <TRead, TWrite>(dataPipe, this.deserializer, this.serializer); connection.ReceiveMessage += ClientOnReceiveMessage; connection.Disconnected += ClientOnDisconnected; connection.Error += ConnectionOnError; connection.Open(); lock (_connections) { _connections.Add(connection); } ClientOnConnected(connection); } // Catch the IOException that is raised if the pipe is broken or disconnected. catch (Exception e) { Console.Error.WriteLine("Named pipe is broken or disconnected: {0}", e); Cleanup(handshakePipe); Cleanup(dataPipe); ClientOnDisconnected(connection); } }
private void AuroraCommandsServerIPC() { PipeSecurity pipeSa = new PipeSecurity(); pipeSa.SetAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow)); while (isRunning) { try { using (IPCCommandpipeStream = new NamedPipeServerStream( "Aurora\\interface", PipeDirection.In, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, PipeOptions.None, 5 * 1024, 5 * 1024, pipeSa, HandleInheritability.None )) { Global.logger.LogLine(String.Format("[AuroraCommandsServerIPC] Pipe created {0}", IPCCommandpipeStream?.GetHashCode())); IPCCommandpipeStream?.WaitForConnection(); Global.logger.LogLine("[AuroraCommandsServerIPC] Pipe connection established"); using (StreamReader sr = new StreamReader(IPCCommandpipeStream)) { string temp; while ((temp = sr.ReadLine()) != null) { Global.logger.LogLine("[AuroraCommandsServerIPC] Recieved command: " + temp); string[] split = temp.Contains(':') ? temp.Split(':') : new[] { temp }; CommandRecieved.Invoke(split[0], split.Length > 1 ? split[1] : ""); } } } Global.logger.LogLine("[AuroraCommandsServerIPC] Pipe connection lost"); } catch (Exception exc) { Global.logger.LogLine("[AuroraCommandsServerIPC] Named Pipe Exception, " + exc, Logging_Level.Error); } } }
public void NamedPipeDefaultPermissionsWork() { if (PlatformID.Win32NT != Environment.OSVersion.Platform) { Assert.Ignore(); } string name = @"Local\MonoTestPipeNPNPW"; using (NamedPipeServerStream server = CreateNamedServer(false, name, null, 0)) { PipeSecurity security = server.GetAccessControl(); AuthorizationRuleCollection rules = security.GetAccessRules(true, false, typeof(SecurityIdentifier)); Assert.AreNotEqual(0, rules.Count); } }
protected NamedPipeServerStream CreateServerPipe(string pipePathIn) { NamedPipeServerStream newPipe = new NamedPipeServerStream( pipePathIn, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 0, 0, null, HandleInheritability.None, PipeAccessRights.ChangePermissions ); if (SimplePipeAccessLevel.Default != this.accessLevel) { PipeSecurity listenerAccess = newPipe.GetAccessControl(); switch (this.accessLevel) { case SimplePipeAccessLevel.AuthenticatedUsers: listenerAccess.AddAccessRule(new PipeAccessRule( new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow )); break; default: // This shouldn't happen. break; } // Always allow the owner full control. listenerAccess.AddAccessRule(new PipeAccessRule( WindowsIdentity.GetCurrent().Owner, PipeAccessRights.FullControl, AccessControlType.Allow )); newPipe.SetAccessControl(listenerAccess); } return(newPipe); }
private void CreatePipeServer() { PipeSecurity ps = new PipeSecurity(); ps.AddAccessRule(new PipeAccessRule("Users", PipeAccessRights.CreateNewInstance | PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow)); beaconServer = new NamedPipeServerStream("TransMockBeacon", PipeDirection.InOut, 10, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 8, 8, ps); connectResult = beaconServer.BeginWaitForConnection(cb => ClientConnected(cb), beaconServer); }
/// <summary> /// Create an instance of the pipe. This might be the first instance, or a subsequent instance. /// There always needs to be an instance of the pipe created to listen for a new client connection. /// </summary> /// <returns>The pipe instance or throws an exception.</returns> private NamedPipeServerStream ConstructPipe(string pipeName) { CompilerServerLogger.Log("Constructing pipe '{0}'.", pipeName); #if NET46 SecurityIdentifier identifier = WindowsIdentity.GetCurrent().Owner; PipeSecurity security = new PipeSecurity(); // Restrict access to just this account. PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow); security.AddAccessRule(rule); security.SetOwner(identifier); NamedPipeServerStream pipeStream = new NamedPipeServerStream( pipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, // Maximum connections. PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.WriteThrough, PipeBufferSize, // Default input buffer PipeBufferSize, // Default output buffer security, HandleInheritability.None); #else // The overload of NamedPipeServerStream with the PipeAccessRule // parameter was removed in netstandard. However, the default // constructor does not provide WRITE_DAC, so attempting to use // SetAccessControl will always fail. So, completely ignore ACLs on // netcore, and trust that our `ClientAndOurIdentitiesMatch` // verification will catch any invalid connections. // Issue to add WRITE_DAC support: // https://github.com/dotnet/corefx/issues/24040 NamedPipeServerStream pipeStream = new NamedPipeServerStream( pipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, // Maximum connections. PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.WriteThrough, PipeBufferSize, // Default input buffer PipeBufferSize); // Default output buffer #endif CompilerServerLogger.Log("Successfully constructed pipe '{0}'.", pipeName); return(pipeStream); }
public void SimpleUnaryWithACLsDenied(NamedPipeChannelContextFactory factory) { PipeSecurity security = new PipeSecurity(); SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); security.AddAccessRule(new PipeAccessRule(sid, PipeAccessRights.ReadWrite, AccessControlType.Allow)); security.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().User, PipeAccessRights.ReadWrite, AccessControlType.Deny)); NamedPipeServerOptions options = new NamedPipeServerOptions { PipeSecurity = security }; using var ctx = factory.Create(options); var exception = Assert.Throws <UnauthorizedAccessException>(() => ctx.Client.SimpleUnary(new RequestMessage { Value = 10 })); }
// This code needs to be in a separate method so that we don't try (and fail) to load the Windows-only APIs when JIT-ing the code // on non-Windows operating systems private void ValidateRemotePipeSecurityOnWindows(NamedPipeClientStream nodeStream) { SecurityIdentifier identifier = WindowsIdentity.GetCurrent().Owner; #if FEATURE_PIPE_SECURITY PipeSecurity remoteSecurity = nodeStream.GetAccessControl(); #else var remoteSecurity = new PipeSecurity(nodeStream.SafePipeHandle, System.Security.AccessControl.AccessControlSections.Access | System.Security.AccessControl.AccessControlSections.Owner | System.Security.AccessControl.AccessControlSections.Group); #endif IdentityReference remoteOwner = remoteSecurity.GetOwner(typeof(SecurityIdentifier)); if (remoteOwner != identifier) { CommunicationsUtilities.Trace("The remote pipe owner {0} does not match {1}", remoteOwner.Value, identifier.Value); throw new UnauthorizedAccessException(); } }
// Creates a PipeSecurity that allows users read/write access // Source: https://stackoverflow.com/a/51559281 private static PipeSecurity CreateSystemIOPipeSecurity() { PipeSecurity pipeSecurity = new PipeSecurity(); var worldSid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); var authenticatedSid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null); var systemSid = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null); var adminsSid = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); pipeSecurity.AddAccessRule(new PipeAccessRule(systemSid, PipeAccessRights.FullControl, AccessControlType.Allow)); pipeSecurity.AddAccessRule(new PipeAccessRule(adminsSid, PipeAccessRights.FullControl, AccessControlType.Allow)); // Allow Everyone read and write access to the pipe. pipeSecurity.AddAccessRule(new PipeAccessRule(worldSid, PipeAccessRights.ReadWrite, AccessControlType.Allow)); pipeSecurity.AddAccessRule(new PipeAccessRule(authenticatedSid, PipeAccessRights.ReadWrite, AccessControlType.Allow)); return(pipeSecurity); }
public void ThredNamedPipeSetup() { namedPipe = new Thread(() => { PipeSecurity ps = new PipeSecurity(); byte[] tmp = new byte[1024]; int nRead; //Is this okay to do? Everyone Read/Write? PipeAccessRule psRule = new PipeAccessRule(@"Everyone", PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow); ps.AddAccessRule(psRule); while (true) { NamedPipeServerStream namedPipeServer = new NamedPipeServerStream("test-pipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 1, 1, ps); namedPipeServer.WaitForConnection(); string filename; using (var reader = new StreamReader(namedPipeServer)) { filename = reader.ReadLine(); } if (filename.Length == 0) { continue; } // namedPipeServer.Disconnect(); File_Item f = new File_Item(); //string filename = Encoding.ASCII.GetString(tmp); f.fileName = Path.GetFileName(filename); f.path = Path.GetDirectoryName(filename); app.Dispatcher.BeginInvoke(new Action(() => { FileList.Add(f); if (s == null) { s = new MainWindow(); s.Show(); } s.Activate(); s.WindowState = WindowState.Normal; })); } }); namedPipe.Start(); }
internal static NamedPipeServerStream CreateNamedPipe( string pipeName, PipeDirection pipeDirection) { #if CoreCLR return(new NamedPipeServerStream( pipeName: pipeName, direction: pipeDirection, maxNumberOfServerInstances: 1, transmissionMode: PipeTransmissionMode.Byte, options: PipeOptions.CurrentUserOnly | PipeOptions.Asynchronous)); #else // In .NET Framework, we must manually ACL the named pipes we create var 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, domainSid: null).Translate(typeof(NTAccount)), PipeAccessRights.FullControl, AccessControlType.Allow)); } else { // Allow the current user read/write access to the pipe. pipeSecurity.AddAccessRule(new PipeAccessRule( WindowsIdentity.GetCurrent().User, PipeAccessRights.ReadWrite, AccessControlType.Allow)); } return(new NamedPipeServerStream( pipeName, pipeDirection, maxNumberOfServerInstances: 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, inBufferSize: PipeBufferSize, outBufferSize: PipeBufferSize, pipeSecurity)); #endif }
private NamedPipeServerStream CreateNamedPipe( string pipeName, PipeSecurity expectedSecurity, PipeDirection direction = DefaultPipeDirection, int maxNumberOfServerInstances = DefaultNumberOfServerInstances, PipeTransmissionMode transmissionMode = DefaultPipeTransmissionMode, PipeOptions options = DefaultPipeOptions, int inBufferSize = DefaultBufferSize, int outBufferSize = DefaultBufferSize, HandleInheritability inheritability = DefaultInheritability, PipeAccessRights additionalAccessRights = 0) { NamedPipeServerStream pipe = NamedPipeServerStreamAcl.Create(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, expectedSecurity, inheritability, additionalAccessRights); Assert.NotNull(pipe); return(pipe); }
/// <summary> /// The CreateSystemIOPipeSecurity function creates a new PipeSecurity /// object to allow All Users read and write access to a pipe. /// </summary> /// <returns> /// A PipeSecurity object that allows All Users read and write access to a pipe /// </returns> /// <see cref="http://msdn.microsoft.com/en-us/library/aa365600(VS.85).aspx"/> static PipeSecurity CreateSystemIOPipeSecurity() { try { PipeSecurity pipeSecurity = new PipeSecurity(); System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null); PipeAccessRule psRule = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow); pipeSecurity.AddAccessRule(psRule); return(pipeSecurity); } catch (Exception ex) { WriteLog(ex.Message); return(null); } }