Пример #1
0
        public void StartPipeServer()
        {
            try
            {
                Task serverTask = Task.Factory.StartNew(() =>
                {
                    PipeSecurity ps = new PipeSecurity();
                    System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.BuiltinUsersSid, null);
                    PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
                    ps.AddAccessRule(par);
                    var server = new NamedPipeServerStream("ForecourtToPumpSim", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024, ps);
                    Console.WriteLine("Waiting for client connection...");
                    server.WaitForConnection();


                    StreamReader serverReader = new StreamReader(server);
                    StreamWriter serverWriter = new StreamWriter(server);
                    ConnectedEvent.Set();


                    while (true)
                    {
                        string line     = serverReader.ReadLine();
                        string response = "";
                        HandleForecourtMessages(line, ref response);

                        serverWriter.WriteLine(response);
                        serverWriter.Flush();
                    }
                });
            }
            catch (IOException e)
            {
            }
        }
Пример #2
0
        public async Task <Connection> ActivateAsync(CancellationToken token)
        {
            ProcessStartInfo info = new ProcessStartInfo();
            var programPath       = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Server", @"LanguageServerWithUI.exe");

            info.FileName         = programPath;
            info.WorkingDirectory = Path.GetDirectoryName(programPath);

            var stdInPipeName  = @"output";
            var stdOutPipeName = @"input";

            var pipeAccessRule = new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
            var pipeSecurity   = new PipeSecurity();

            pipeSecurity.AddAccessRule(pipeAccessRule);

            var bufferSize = 256;
            var readerPipe = new NamedPipeServerStream(stdInPipeName, PipeDirection.InOut, 4, PipeTransmissionMode.Message, PipeOptions.Asynchronous, bufferSize, bufferSize, pipeSecurity);
            var writerPipe = new NamedPipeServerStream(stdOutPipeName, PipeDirection.InOut, 4, PipeTransmissionMode.Message, PipeOptions.Asynchronous, bufferSize, bufferSize, pipeSecurity);

            Process process = new Process();

            process.StartInfo = info;

            if (process.Start())
            {
                await readerPipe.WaitForConnectionAsync(token);

                await writerPipe.WaitForConnectionAsync(token);

                return(new Connection(readerPipe, writerPipe));
            }

            return(null);
        }
Пример #3
0
        internal static PipeSecurity?CreatePipeSecurity()
        {
            if (PlatformInformation.IsRunningOnMono)
            {
                // Pipe security and additional access rights constructor arguments
                //  are not supported by Mono
                // https://github.com/dotnet/roslyn/pull/30810
                // https://github.com/mono/mono/issues/11406
                return(null);
            }

            var security = new PipeSecurity();
            SecurityIdentifier identifier = WindowsIdentity.GetCurrent().Owner;

            // Restrict access to just this account.
            PipeAccessRule rule = new PipeAccessRule(
                identifier,
                PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance,
                AccessControlType.Allow
                );

            security.AddAccessRule(rule);
            security.SetOwner(identifier);
            return(security);
        }
Пример #4
0
        private static NamedPipeServerStream CreateServer(string pipeName)
        {
            // Create a new pipe accessible by local authenticated users, disallow network
            var sidNetworkService = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null);
            var sidWorld          = new SecurityIdentifier(WellKnownSidType.WorldSid, null);

            var pipeSecurity = new PipeSecurity();

            // Alow Everyone to read/write to pipe
            var accessRule = new PipeAccessRule(sidWorld, PipeAccessRights.ReadWrite, AccessControlType.Allow);

            pipeSecurity.AddAccessRule(accessRule);

            // Deny network access to the named pipe
            accessRule = new PipeAccessRule(sidNetworkService, PipeAccessRights.ReadWrite, AccessControlType.Deny);
            pipeSecurity.AddAccessRule(accessRule);

            // Create pipe
            return(new NamedPipeServerStream(
                       pipeName,
                       PipeDirection.In,
                       1,
                       PipeTransmissionMode.Byte,
                       PipeOptions.Asynchronous,
                       0,
                       0,
                       pipeSecurity));
        }
Пример #5
0
        /// <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);

            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);

            CompilerServerLogger.Log("Successfully constructed pipe '{0}'.", pipeName);

            return(pipeStream);
        }
        public MainWindowViewModel()
        {
            var stdInPipeName  = @"input";
            var stdOutPipeName = @"output";

            var pipeAccessRule = new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
            var pipeSecurity   = new PipeSecurity();

            pipeSecurity.AddAccessRule(pipeAccessRule);

            var readerPipe = new NamedPipeClientStream(stdInPipeName);
            var writerPipe = new NamedPipeClientStream(stdOutPipeName);

            readerPipe.Connect();
            writerPipe.Connect();

            this.InitializedMessage = "The server has not yet been initialized.";
            this.languageServer     = new LanguageServer.LanguageServer(writerPipe, readerPipe);

            this.languageServer.OnInitialized   += OnInitialized;
            this.languageServer.Disconnected    += OnDisconnected;
            this.languageServer.PropertyChanged += OnLanguageServerPropertyChanged;

            DiagnosticItems.Add(new DiagnosticItem());
            this.LogMessage            = string.Empty;
            this.ResponseText          = string.Empty;
            this.MessageRequestOptions = "3";
        }
Пример #7
0
        private void ReadData()
        {
            var pipeSecurity = new PipeSecurity();
            var everyoneSecurityIdentifier = new SecurityIdentifier(
                WellKnownSidType.WorldSid, null);
            var everyoneAccessRule = new PipeAccessRule(everyoneSecurityIdentifier,
                                                        PipeAccessRights.FullControl, AccessControlType.Allow);

            pipeSecurity.AddAccessRule(everyoneAccessRule);

            using (var namedPipeServer = new NamedPipeServerStream(
                       _serverPipeConfiguration.Name, PipeDirection.InOut, 1,
                       PipeTransmissionMode.Byte, PipeOptions.Asynchronous,
                       0, 0, pipeSecurity))
            {
                while (true)
                {
                    if (_stopReading)
                    {
                        return;
                    }

                    ReadMessage(namedPipeServer);
                }
            }
        }
Пример #8
0
        /// <summary>
        /// Starts a new Pipe server on a new thread
        /// </summary>
        public void StartServer()
        {
            StopServer();
            Thread = new Thread((pipeName) =>
            {
                if (!(pipeName is String pipeNameString))
                {
                    throw new ArgumentNullException(nameof(pipeName));
                }
                _isRunning = true;
                while (true)
                {
                    string text;
                    try
                    {
                        PipeSecurity ps = new PipeSecurity();
                        System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
                        PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
                        //PipeAccessRule psRule = new PipeAccessRule(@"Everyone", PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
                        ps.AddAccessRule(par);
                        using (var server = new NamedPipeServerStream(pipeNameString,
                                                                      PipeDirection.InOut, 1,
                                                                      PipeTransmissionMode.Message, PipeOptions.None,
                                                                      4028, 4028, ps))
                        {
                            server.WaitForConnection();

                            using (StreamReader reader = new StreamReader(server))
                            {
                                text = reader.ReadToEnd();
                            }
                        }

                        if (text == EXIT_STRING)
                        {
                            break;
                        }

                        OnReceiveString(text);
                    }
                    catch (IOException e)
                    {
                        Log.Warn(e);
                        Thread.Sleep(50);
                    }
                    catch (Exception e)
                    {
                        Log.Error(e);
                        Thread.Sleep(50);
                    }


                    if (_isRunning == false)
                    {
                        break;
                    }
                }
            });
            Thread.Start(NamedPipeName);
        }
        public virtual async Task StartListeningAsync(Endpoint Endpoint, CancellationToken Token, Func <Object> GetHandler)
        {
            var EP = StreamName(Endpoint);

            while (true)
            {
                if (!Token.IsCancellationRequested)
                {
                    try {
                        var Security = new PipeSecurity();
                        {
                            var Everyone      = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                            var AllowEveryone = new PipeAccessRule(Everyone, PipeAccessRights.FullControl, System.Security.AccessControl.AccessControlType.Allow);
                            Security.SetAccessRule(AllowEveryone);
                        }

                        var C = new NamedPipeServerStream(EP, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 0, 0, Security);

                        await C.WaitForConnectionAsync(Token)
                        .DefaultAwait()
                        ;

                        _ = Task.Run(() => ProcessConnectionAsync(C, GetHandler));
                    } catch (TaskCanceledException) {
                    }
                }
                else
                {
                    break;
                }
            }
        }
Пример #10
0
        private NamedPipeServerStream CreateNewPipeServer()
        {
            var server = new NamedPipeServerStream(PipeName,
                                                   PipeDirection.InOut,
                                                   2,
                                                   PipeTransmissionMode.Byte,
                                                   PipeOptions.Asynchronous,
                                                   0,
                                                   0,
                                                   null,
                                                   HandleInheritability.None,
                                                   0);

            PipeSecurity accessControl = server.GetAccessControl();

            // Prevent 'Everyone' account from accessing pipe
            var securityIdentifier = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            var rule = new PipeAccessRule(securityIdentifier, PipeAccessRights.Read, AccessControlType.Allow);

            accessControl.RemoveAccessRule(rule);

            // Prevent 'Anonymous' account from accessing pipe
            securityIdentifier = new SecurityIdentifier(WellKnownSidType.AnonymousSid, null);
            rule = new PipeAccessRule(securityIdentifier, PipeAccessRights.Read, AccessControlType.Allow);
            accessControl.RemoveAccessRule(rule);

            return(server);
        }
Пример #11
0
        protected override async Task WaitAndProcessAsync(
            Func <Stream, CancellationToken, Task> process,
            CancellationToken cancellationToken)
        {
            if (process is null)
            {
                throw new ArgumentNullException(nameof(process));
            }

            // https://github.com/PowerShell/PowerShellEditorServices/blob/f45c6312a859cde4aa25ea347a345e1d35238350/src/PowerShellEditorServices.Protocol/MessageProtocol/Channel/NamedPipeServerListener.cs#L38-L67
            // Unfortunately, .NET Core does not support passing in a PipeSecurity object into the constructor for
            // NamedPipeServerStream so we are creating native Named Pipes and securing them using native APIs.
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                PipeSecurity   pipeSecurity = new PipeSecurity();
                PipeAccessRule psRule       = new PipeAccessRule(@"Everyone", PipeAccessRights.FullControl, System.Security.AccessControl.AccessControlType.Allow);
                pipeSecurity.AddAccessRule(psRule);
                using (var server = NamedPipeNative.CreateNamedPipe(_options.PipeName, (uint)_options.MaxConcurrentCalls, pipeSecurity))
                {
                    await server.WaitForConnectionAsync(cancellationToken).ConfigureAwait(false);
                    await process(server, cancellationToken).ConfigureAwait(false);
                }
            }

            // Use original logic on other platforms.
            else
            {
                using (var server = new NamedPipeServerStream(_options.PipeName, PipeDirection.InOut, _options.MaxConcurrentCalls,
                                                              PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
                {
                    await server.WaitForConnectionAsync(cancellationToken).ConfigureAwait(false);
                    await process(server, cancellationToken).ConfigureAwait(false);
                }
            }
        }
        public MainWindowViewModel()
        {
            var stdInPipeName  = @"input";
            var stdOutPipeName = @"output";

            var sid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);

            var pipeAccessRule = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
            var pipeSecurity   = new PipeSecurity();

            pipeSecurity.AddAccessRule(pipeAccessRule);

            var readerPipe = new NamedPipeClientStream(stdInPipeName);
            var writerPipe = new NamedPipeClientStream(stdOutPipeName);

            readerPipe.Connect();
            writerPipe.Connect();

            this.languageServer = new LanguageServer.LanguageServer(writerPipe, readerPipe);

            this.languageServer.Disconnected    += OnDisconnected;
            this.languageServer.PropertyChanged += OnLanguageServerPropertyChanged;

            Tags.Add(new DiagnosticTag());
            this.LogMessage   = string.Empty;
            this.ResponseText = string.Empty;
        }
Пример #13
0
        NamedPipeServerStream CreatePipeAccessControl()
        {
            // Fix up the DACL on the pipe before opening the listener instance
            // This won't disturb the SACL containing the mandatory integrity label
            NamedPipeServerStream pipeServer = new NamedPipeServerStream(
                PipeName,                                                   // The unique pipe name.
                PipeDirection,                                              // The pipe is duplex
                NamedPipeServerStream.MaxAllowedServerInstances,            // MaxAllowedServerInstances
                PipeTransmissionMode.Message,                               // Byte|Message-based communication
                PipeOptions.None,                                           // No additional parameters
                ReceiveBufferSize,                                          // Input buffer size
                SendBufferSize,                                             // Output buffer size
                null,                                                       // Pipe security attributes
                HandleInheritability.None,                                  // Not inheritable
                PipeAccessRights.ChangePermissions);

            PipeSecurity ps = pipeServer.GetAccessControl();

            PipeAccessRule aceClients = new PipeAccessRule(
                new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null), // or some other group defining the allowed clients
                PipeAccessRights.ReadWrite,
                AccessControlType.Allow);
            PipeAccessRule aceOwner = new PipeAccessRule(
                WindowsIdentity.GetCurrent().Owner,
                PipeAccessRights.FullControl,
                AccessControlType.Allow);

            ps.AddAccessRule(aceClients);
            ps.AddAccessRule(aceOwner);

            pipeServer.SetAccessControl(ps);

            return(pipeServer);
        }
Пример #14
0
        private static async void InitializeAppServiceConnection()
        {
            connection = new NamedPipeServerStream($@"FilesInteropService_ServerPipe", PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 2048, 2048, null, HandleInheritability.None, PipeAccessRights.ChangePermissions);

            PipeSecurity   Security   = connection.GetAccessControl();
            PipeAccessRule ClientRule = new PipeAccessRule(new SecurityIdentifier("S-1-15-2-1"), PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow);
            PipeAccessRule OwnerRule  = new PipeAccessRule(WindowsIdentity.GetCurrent().Owner, PipeAccessRights.FullControl, AccessControlType.Allow);

            Security.AddAccessRule(ClientRule);
            Security.AddAccessRule(OwnerRule);
            if (IsAdministrator())
            {
                PipeAccessRule EveryoneRule = new PipeAccessRule(new SecurityIdentifier("S-1-1-0"), PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow);
                Security.AddAccessRule(EveryoneRule); // TODO: find the minimum permission to allow connection when admin
            }
            connection.SetAccessControl(Security);

            await connection.WaitForConnectionAsync();

            if (connection.IsConnected)
            {
                var info = (Buffer : new byte[connection.InBufferSize], Message : new StringBuilder());
                BeginRead(info);
            }
        }
        public MainWindowViewModel()
        {
            Debug.Fail("test");
            var stdInPipeName  = @"input";
            var stdOutPipeName = @"output";

            var pipeAccessRule = new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
            var pipeSecurity   = new PipeSecurity();

            pipeSecurity.AddAccessRule(pipeAccessRule);

            var readerPipe = new NamedPipeClientStream(stdInPipeName);
            var writerPipe = new NamedPipeClientStream(stdOutPipeName);

            readerPipe.Connect();
            writerPipe.Connect();

            this.languageServer = new LanguageServer.LanguageServer(writerPipe, readerPipe);

            this.languageServer.Disconnected    += OnDisconnected;
            this.languageServer.PropertyChanged += OnLanguageServerPropertyChanged;

            Tags.Add(new DiagnosticTag());
            this.LogMessage   = string.Empty;
            this.ResponseText = string.Empty;
        }
Пример #16
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            string receivedText;

            PipeSecurity ps = new PipeSecurity();

            System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
            PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);

            ps.AddAccessRule(par);

            using (var pipeStream = new NamedPipeServerStream(
                       "test",
                       PipeDirection.InOut,
                       1,
                       PipeTransmissionMode.Message,
                       PipeOptions.Asynchronous,
                       4096,
                       4096,
                       ps))
            {
                await pipeStream.WaitForConnectionAsync(stoppingToken);

                using (var streamReader = new StreamReader(pipeStream))
                {
                    receivedText = await streamReader.ReadToEndAsync();
                }
            }
        }
Пример #17
0
        /// <summary>
        /// Starts a new pipe server and read response from client
        /// </summary>
        public static string ReceiveNamedPipeServerMessage()
        {
            try
            {
                PipeSecurity   ps     = new PipeSecurity();
                PipeAccessRule psRule = new PipeAccessRule(@"Everyone", PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
                ps.AddAccessRule(psRule);

                using (NamedPipeServerStream namedPipeServer =
                           new NamedPipeServerStream("test-pipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 1, 1, ps))
                {
                    namedPipeServer.WaitForConnection();

                    IFormatter f = new BinaryFormatter();
                    var        namedPipePayload = (NamedPipePayload)f.Deserialize(namedPipeServer);

                    return(namedPipePayload.SignalQuit ? null : namedPipePayload.Arguments);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }

            return(null);
        }
Пример #18
0
 protected bool AreAccessRulesEqual(PipeAccessRule expectedRule, PipeAccessRule actualRule)
 {
     return
         (expectedRule.AccessControlType == actualRule.AccessControlType &&
          expectedRule.PipeAccessRights == actualRule.PipeAccessRights &&
          expectedRule.InheritanceFlags == actualRule.InheritanceFlags &&
          expectedRule.PropagationFlags == actualRule.PropagationFlags);
 }
Пример #19
0
        protected PipeSecurity GetPipeSecurity(WellKnownSidType sid, PipeAccessRights rights, AccessControlType accessControl)
        {
            var security = new PipeSecurity();
            SecurityIdentifier identity = new SecurityIdentifier(sid, null);
            var accessRule = new PipeAccessRule(identity, rights, accessControl);

            security.AddAccessRule(accessRule);
            return(security);
        }
Пример #20
0
        ////////////////////////////////////////////////////////////////////////////////
        //
        ////////////////////////////////////////////////////////////////////////////////
        internal SMBServer(String pipeName)
        {
            SecurityIdentifier sid          = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
            PipeAccessRule     access       = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, AccessControlType.Allow);
            PipeSecurity       pipeSecurity = new PipeSecurity();

            pipeSecurity.AddAccessRule(access);
            namedPipeServerStream = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 100, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, pipeSecurity);
        }
Пример #21
0
        private void PipeThreadStart()
        {
            PipeSecurity   pSec     = new PipeSecurity();
            PipeAccessRule pAccRule = new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null)
                                                         , PipeAccessRights.ReadWrite | PipeAccessRights.Synchronize, System.Security.AccessControl.AccessControlType.Allow);

            pSec.AddAccessRule(pAccRule);

            using (_pipeServer = new NamedPipeServerStream("NKT_SQLINTERCEPT_PIPE",
                                                           PipeDirection.InOut,
                                                           NamedPipeServerStream.MaxAllowedServerInstances,
                                                           PipeTransmissionMode.Byte,
                                                           PipeOptions.None,
                                                           MAX_STRING_CCH * 2,
                                                           MAX_STRING_CCH * 2,
                                                           pSec,
                                                           HandleInheritability.Inheritable))
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("(pipe thread) Waiting for connection...");
                Console.ForegroundColor = ConsoleColor.Gray;

                try
                {
                    _pipeServer.WaitForConnection();

                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("(pipe thread) Client connected.");
                    Console.ForegroundColor = ConsoleColor.Gray;

                    while (true)
                    {
                        byte[] readBuf = new byte[MAX_STRING_CCH * 2];

                        int cbRead = _pipeServer.Read(readBuf, 0, MAX_STRING_CCH * 2);

                        string str = Encoding.Unicode.GetString(readBuf, 0, cbRead);

                        Console.WriteLine(str);
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine("--------------------------------------------------------");
                        Console.ForegroundColor = ConsoleColor.Gray;

                        if (_blockQuery)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("(pipe thread) QUERY ABORTED");
                            Console.ForegroundColor = ConsoleColor.Gray;
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine("(pipethread) Pipe or data marshaling operation exception! ({0})", ex.Message);
                }
            }
        }
Пример #22
0
        public void SetDefaultSecurity()
        {
            PipeSecurity       pipeSecurity = new PipeSecurity();
            SecurityIdentifier everyoneSID  = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            PipeAccessRule     accessRule   = new PipeAccessRule(everyoneSID, PipeAccessRights.ReadWrite, AccessControlType.Allow);

            pipeSecurity.AddAccessRule(accessRule);
            this.server.SetSecurity(pipeSecurity);
        }
        public NamedPipeServerStream CreatePipe(string name, int maxInstances = NamedPipeServerStream.MaxAllowedServerInstances)
        {
            PipeSecurity       ps  = new PipeSecurity();
            SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            PipeAccessRule     par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);

            ps.AddAccessRule(par);
            return(new NamedPipeServerStream(name, PipeDirection.InOut, maxInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024, ps));
        }
Пример #24
0
        /// <summary>
        /// Instantiates an endpoint to act as a client
        /// </summary>
        /// <param name="pipeName">The name of the pipe to which we should connect.</param>
        internal void InternalConstruct(string pipeName)
        {
            ErrorUtilities.VerifyThrowArgumentLength(pipeName, nameof(pipeName));

            _debugCommunications = (Environment.GetEnvironmentVariable("MSBUILDDEBUGCOMM") == "1");

            _status           = LinkStatus.Inactive;
            _asyncDataMonitor = new object();
            _sharedReadBuffer = InterningBinaryReader.CreateSharedBuffer();

            _packetStream = new MemoryStream();
            _binaryWriter = new BinaryWriter(_packetStream);

#if FEATURE_PIPE_SECURITY && FEATURE_NAMED_PIPE_SECURITY_CONSTRUCTOR
            if (!NativeMethodsShared.IsMono)
            {
                SecurityIdentifier identifier = WindowsIdentity.GetCurrent().Owner;
                PipeSecurity       security   = new PipeSecurity();

                // Restrict access to just this account.  We set the owner specifically here, and on the
                // pipe client side they will check the owner against this one - they must have identical
                // SIDs or the client will reject this server.  This is used to avoid attacks where a
                // hacked server creates a less restricted pipe in an attempt to lure us into using it and
                // then sending build requests to the real pipe client (which is the MSBuild Build Manager.)
                PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.ReadWrite, AccessControlType.Allow);
                security.AddAccessRule(rule);
                security.SetOwner(identifier);

                _pipeServer = new NamedPipeServerStream
                              (
                    pipeName,
                    PipeDirection.InOut,
                    1, // Only allow one connection at a time.
                    PipeTransmissionMode.Byte,
                    PipeOptions.Asynchronous | PipeOptions.WriteThrough,
                    PipeBufferSize, // Default input buffer
                    PipeBufferSize, // Default output buffer
                    security,
                    HandleInheritability.None
                              );
            }
            else
#endif
            {
                _pipeServer = new NamedPipeServerStream
                              (
                    pipeName,
                    PipeDirection.InOut,
                    1, // Only allow one connection at a time.
                    PipeTransmissionMode.Byte,
                    PipeOptions.Asynchronous | PipeOptions.WriteThrough,
                    PipeBufferSize, // Default input buffer
                    PipeBufferSize  // Default output buffer
                              );
            }
        }
Пример #25
0
        public static NamedPipeServerStream CreatePipe(string p_PipeName)
        {
            var s_Security   = new PipeSecurity();
            var s_Identifier = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            var s_AccessRule = new PipeAccessRule(s_Identifier, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);

            s_Security.AddAccessRule(s_AccessRule);

            return(new NamedPipeServerStream(p_PipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.WriteThrough, 1024, 1024, s_Security));
        }
Пример #26
0
        public NamedPipeManager()
        {
            SecurityIdentifier sid    = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            PipeAccessRule     psRule = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, AccessControlType.Allow);

            pipeSecurity = new PipeSecurity();
            pipeSecurity.AddAccessRule(psRule);

            NamedPipeStream_Server = new NamedPipeServerStream(Name, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 512, 512, pipeSecurity);
        }
Пример #27
0
        /// <summary>
        /// Creates a security profile for the pipes (Was used in .NET Framework.. No longer needed in Core 3? (Crashes))
        /// </summary>
        private static PipeSecurity CreateSystemIoPipeSecurity()
        {
            PipeSecurity   pipe_security = new PipeSecurity();
            PipeAccessRule access_rule   = new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow);

            pipe_security.AddAccessRule(access_rule);
            PipeAccessRule access_rule2 = new PipeAccessRule("Everyone", PipeAccessRights.FullControl, AccessControlType.Allow);

            pipe_security.AddAccessRule(access_rule2);
            return(pipe_security);
        }
Пример #28
0
        private void StartNamedPipeServer()
        {
            if (!StartServer)
            {
                return;
            }

#if NETCOREAPP2_1 || NETCOREAPP3_1 || NET5_0
            if (!System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
            {
                throw new PlatformNotSupportedException("The communication with the first instance is only supported on Windows");
            }

            _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, state: null !); // TODO-NULLABLE https://github.com/dotnet/runtime/pull/42442
            }
            catch (ObjectDisposedException)
            {
                // The server was disposed before getting a connection
            }
        }
Пример #29
0
        public NamedPipeProcessInteropServer(string pipeName)
        {
            _pipeName = pipeName;
            var _pipeSecurity = new PipeSecurity();
            var psEveryone    = new PipeAccessRule("Everyone", PipeAccessRights.FullControl, System.Security.AccessControl.AccessControlType.Allow);

            _pipeSecurity.AddAccessRule(psEveryone);
            _pipe           = new NamedPipeServerStream(_pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 100, 100, _pipeSecurity);
            stream          = _pipe;
            _timer.Elapsed += _timer_Elapsed;
        }
Пример #30
0
        //private static bool exit = false;

        public static void CreateNamedPipeServer(string pipeName)
        {
            PipeSecurity   pipeSecurityDescriptor = new PipeSecurity();
            PipeAccessRule everyoneAllowedRule    = new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow);
            PipeAccessRule networkDenyRule        = new PipeAccessRule("Network", PipeAccessRights.ReadWrite, AccessControlType.Deny); // This should only be used locally, so lets limit the scope

            pipeSecurityDescriptor.AddAccessRule(everyoneAllowedRule);
            //pipeSecurityDescriptor.AddAccessRule(networkDenyRule);

            // Gotta be careful with the buffer sizes. There's a max limit on how much data you can write to a pipe in one sweep. IIRC it's ~55,000, but I dunno for sure.
            pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 10, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 32768, 32768, pipeSecurityDescriptor);
        }